diff --git a/HBC/META.XML b/HBC/META.XML index e9ad5c15..4c4dc59d 100644 --- a/HBC/META.XML +++ b/HBC/META.XML @@ -2,8 +2,8 @@ USB Loader GX USB Loader GX Team - 1.0 r908 - 201002090353 + 1.0 r909 + 201002091053 Loads games from USB-devices USB Loader GX is a libwiigui based USB iso loader with a wii-like GUI. You can install games to your HDDs and boot them with shorter loading times. The interactive GUI is completely controllable with WiiMote, Classic Controller or GC Controller. diff --git a/source/FreeTypeGX.cpp b/source/FreeTypeGX.cpp index 2f61b70b..31b2294f 100644 --- a/source/FreeTypeGX.cpp +++ b/source/FreeTypeGX.cpp @@ -65,9 +65,10 @@ typedef struct ftgxDataOffset_ { * @param vertexIndex Optional vertex format index (GX_VTXFMT*) of the glyph textures as defined by the libogc gx.h header file. If not specified default value is GX_VTXFMT1. */ FreeTypeGX::FreeTypeGX(uint8_t textureFormat, uint8_t vertexIndex, uint32_t compatibilityMode) - : - ftFace(NULL), - ftFace_fromFile(NULL) { +: +ftFace(NULL), +ftFace_fromFile(NULL) +{ FT_Init_FreeType(&this->ftLibrary); this->textureFormat = textureFormat; @@ -94,8 +95,8 @@ FreeTypeGX::~FreeTypeGX() { */ wchar_t* FreeTypeGX::charToWideChar(const char* strChar) { wchar_t *strWChar; - strWChar = new(std::nothrow) wchar_t[strlen(strChar) + 1]; - if (!strWChar) return NULL; + strWChar = new(std::nothrow) wchar_t[strlen(strChar) + 1]; + if(!strWChar) return NULL; // UTF-8 int bt; bt = mbstowcs(strWChar, strChar, strlen(strChar)); @@ -260,29 +261,32 @@ void FreeTypeGX::clearGlyphData() { GX_DrawDone(); GX_Flush(); - for ( std::map::iterator i = this->fontDatas.begin(); i != this->fontDatas.end(); i++) { - for ( FTGX_Cache::iterator j = i->second.begin(); j != i->second.end(); j++) { - free(j->second.glyphDataTexture); - } - i->second.clear(); + for ( std::map::iterator i = this->fontDatas.begin(); i != this->fontDatas.end(); i++) + { + for ( FTGX_Cache::iterator j = i->second.begin(); j != i->second.end(); j++) + { + free(j->second.glyphDataTexture); + } + i->second.clear(); } - /* for ( std::map::iterator i = this->fontData.begin(); i != this->fontData.end(); i++) { - free(i->second.glyphDataTexture); - } - */ +/* for ( std::map::iterator i = this->fontData.begin(); i != this->fontData.end(); i++) { + free(i->second.glyphDataTexture); + } +*/ this->fontDatas.clear(); } void FreeTypeGX::changeSize(FT_UInt vPointSize, FT_UInt hPointSize/*=0*/) { - if (hPointSize == 0) hPointSize = vPointSize; - if (vPointSize > 255) vPointSize = 255;// limit to 255 - if (hPointSize > 255) hPointSize = 255; - if (this->ftPointSize_v != vPointSize || this->ftPointSize_h != hPointSize) { + if(hPointSize == 0) hPointSize = vPointSize; + if(vPointSize > 255) vPointSize = 255;// limit to 255 + if(hPointSize > 255) hPointSize = 255; + if(this->ftPointSize_v != vPointSize || this->ftPointSize_h != hPointSize) + { // this->clearGlyphData(); - this->ftPointSize_v = vPointSize; - this->ftPointSize_h = hPointSize; - FT_Set_Pixel_Sizes(this->ftFace, this->ftPointSize_h, this->ftPointSize_v); - } + this->ftPointSize_v = vPointSize; + this->ftPointSize_h = hPointSize; + FT_Set_Pixel_Sizes(this->ftFace, this->ftPointSize_h, this->ftPointSize_v); + } } /** @@ -356,42 +360,44 @@ uint16_t FreeTypeGX::adjustTextureHeight(uint16_t textureHeight, uint8_t texture * @param charCode The requested glyph's character code. * @return A pointer to the allocated font structure. */ -ftgxCharData *FreeTypeGX::cacheGlyphData(wchar_t charCode) { - FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; - return cacheGlyphData(charCode, fontData); +ftgxCharData *FreeTypeGX::cacheGlyphData(wchar_t charCode) +{ + FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; + return cacheGlyphData(charCode, fontData); } -ftgxCharData *FreeTypeGX::cacheGlyphData(wchar_t charCode, FTGX_Cache &fontData) { - FT_UInt gIndex; - uint16_t textureWidth = 0, textureHeight = 0; +ftgxCharData *FreeTypeGX::cacheGlyphData(wchar_t charCode, FTGX_Cache &fontData) +{ + FT_UInt gIndex; + uint16_t textureWidth = 0, textureHeight = 0; - gIndex = FT_Get_Char_Index( this->ftFace, charCode ); - if (!FT_Load_Glyph(this->ftFace, gIndex, FT_LOAD_DEFAULT )) { - FT_Render_Glyph( this->ftSlot, FT_RENDER_MODE_NORMAL ); + gIndex = FT_Get_Char_Index( this->ftFace, charCode ); + if (!FT_Load_Glyph(this->ftFace, gIndex, FT_LOAD_DEFAULT )) { + FT_Render_Glyph( this->ftSlot, FT_RENDER_MODE_NORMAL ); - if (this->ftSlot->format == FT_GLYPH_FORMAT_BITMAP) { - FT_Bitmap *glyphBitmap = &this->ftSlot->bitmap; + if (this->ftSlot->format == FT_GLYPH_FORMAT_BITMAP) { + FT_Bitmap *glyphBitmap = &this->ftSlot->bitmap; - textureWidth = adjustTextureWidth(glyphBitmap->width, this->textureFormat); - textureHeight = adjustTextureHeight(glyphBitmap->rows, this->textureFormat); + textureWidth = adjustTextureWidth(glyphBitmap->width, this->textureFormat); + textureHeight = adjustTextureHeight(glyphBitmap->rows, this->textureFormat); - fontData[charCode] = (ftgxCharData) { - this->ftSlot->bitmap_left, - this->ftSlot->advance.x >> 6, - gIndex, - textureWidth, - textureHeight, - this->ftSlot->bitmap_top, - this->ftSlot->bitmap_top, - glyphBitmap->rows - this->ftSlot->bitmap_top, - NULL - }; - this->loadGlyphData(glyphBitmap, &fontData[charCode]); + fontData[charCode] = (ftgxCharData) { + this->ftSlot->bitmap_left, + this->ftSlot->advance.x >> 6, + gIndex, + textureWidth, + textureHeight, + this->ftSlot->bitmap_top, + this->ftSlot->bitmap_top, + glyphBitmap->rows - this->ftSlot->bitmap_top, + NULL + }; + this->loadGlyphData(glyphBitmap, &fontData[charCode]); - return &fontData[charCode]; - } - } + return &fontData[charCode]; + } + } - return NULL; + return NULL; } /** @@ -546,8 +552,8 @@ uint16_t FreeTypeGX::drawText(int16_t x, int16_t y, const wchar_t *text, GXColor GXTexObj glyphTexture; FT_Vector pairDelta; ftgxDataOffset offset; - FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; - + FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; + if (textStyle & FTGX_JUSTIFY_MASK) { x_offset = this->getStyleOffsetWidth(this->getWidth(text), textStyle); } @@ -643,7 +649,7 @@ uint16_t FreeTypeGX::getWidth(const wchar_t *text) { uint16_t strLength = wcslen(text); uint16_t strWidth = 0; FT_Vector pairDelta; - FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; + FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; for (uint16_t i = 0; i < strLength; i++) { @@ -697,8 +703,8 @@ uint16_t FreeTypeGX::getHeight(const wchar_t *text) { ftgxDataOffset* FreeTypeGX::getOffset(const wchar_t *text, ftgxDataOffset* offset) { uint16_t strLength = wcslen(text); int16_t strMax = 0, strMin = 9999; - FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; - + FTGX_Cache &fontData = this->fontDatas[ftPointSize_v | ftPointSize_h << 8]; + for (uint16_t i = 0; i < strLength; i++) { ftgxCharData* glyphData = NULL; diff --git a/source/FreeTypeGX.h b/source/FreeTypeGX.h index 2f14be73..4fa2b17c 100644 --- a/source/FreeTypeGX.h +++ b/source/FreeTypeGX.h @@ -203,7 +203,9 @@ typedef struct ftgxDataOffset_ ftgxDataOffset; #define FTGX_COMPATIBILITY_GRRLIB FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_PASSCLR | FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_NONE #define FTGX_COMPATIBILITY_LIBWIISPRITE FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_MODULATE | FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_DIRECT -const GXColor ftgxWhite = (GXColor) {0xff, 0xff, 0xff, 0xff} +const GXColor ftgxWhite = (GXColor) { + 0xff, 0xff, 0xff, 0xff +} ; /**< Constant color value used only to sanitize Doxygen documentation. */ /*! \class FreeTypeGX @@ -231,7 +233,7 @@ private: uint8_t vertexIndex; /**< Vertex format descriptor index. */ uint32_t compatibilityMode; /**< Compatibility mode for default tev operations and vertex descriptors. */ // FTGX_Cache fontData; /**< Map which holds the glyph data structures for the corresponding characters. */ - std::map fontDatas; + std::map fontDatas; static uint16_t adjustTextureWidth(uint16_t textureWidth, uint8_t textureFormat); static uint16_t adjustTextureHeight(uint16_t textureHeight, uint8_t textureFormat); @@ -242,7 +244,7 @@ private: void unloadFont(); void clearGlyphData(); ftgxCharData *cacheGlyphData(wchar_t charCode); - ftgxCharData *cacheGlyphData(wchar_t charCode, FTGX_Cache &fontData); + ftgxCharData *cacheGlyphData(wchar_t charCode, FTGX_Cache &fontData); uint16_t cacheGlyphDataComplete(); void loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData); diff --git a/source/ZipFile.cpp b/source/ZipFile.cpp index 326e0c91..d1e27709 100644 --- a/source/ZipFile.cpp +++ b/source/ZipFile.cpp @@ -39,22 +39,26 @@ #include "ZipFile.h" #include "language/gettext.h" -ZipFile::ZipFile(const char *filepath) { +ZipFile::ZipFile(const char *filepath) +{ File = unzOpen(filepath); - if (File) + if(File) this->LoadList(); } -ZipFile::~ZipFile() { +ZipFile::~ZipFile() +{ unzClose(File); } -bool ZipFile::LoadList() { +bool ZipFile::LoadList() +{ return true; } -bool ZipFile::ExtractAll(const char *dest) { - if (!File) +bool ZipFile::ExtractAll(const char *dest) +{ + if(!File) return false; bool Stop = false; @@ -62,7 +66,7 @@ bool ZipFile::ExtractAll(const char *dest) { u32 blocksize = 1024*50; u8 *buffer = new u8[blocksize]; - if (!buffer) + if(!buffer) return false; char writepath[MAXPATHLEN]; @@ -70,14 +74,16 @@ bool ZipFile::ExtractAll(const char *dest) { memset(filename, 0, sizeof(filename)); int ret = unzGoToFirstFile(File); - if (ret != UNZ_OK) + if(ret != UNZ_OK) Stop = true; - while (!Stop) { - if (unzGetCurrentFileInfo(File, &cur_file_info, filename, sizeof(filename), NULL, NULL, NULL, NULL) != UNZ_OK) + while(!Stop) + { + if(unzGetCurrentFileInfo(File, &cur_file_info, filename, sizeof(filename), NULL, NULL, NULL, NULL) != UNZ_OK) Stop = true; - if (!Stop && filename[strlen(filename)-1] != '/') { + if(!Stop && filename[strlen(filename)-1] != '/') + { u32 uncompressed_size = cur_file_info.uncompressed_size; u32 done = 0; @@ -95,31 +101,33 @@ bool ZipFile::ExtractAll(const char *dest) { subfoldercreate(temppath); - if (ret == UNZ_OK) { + if(ret == UNZ_OK) + { FILE *pfile = fopen(writepath, "wb"); - do { + do + { ShowProgress(tr("Extracting files..."), 0, pointer+1, done, uncompressed_size); - if (uncompressed_size - done < blocksize) + if(uncompressed_size - done < blocksize) blocksize = uncompressed_size - done; ret = unzReadCurrentFile(File, buffer, blocksize); - if (ret == 0) + if(ret == 0) break; fwrite(buffer, 1, blocksize, pfile); done += ret; - } while (done < uncompressed_size); + } while(done < uncompressed_size); fclose(pfile); unzCloseCurrentFile(File); } } - if (unzGoToNextFile(File) != UNZ_OK) + if(unzGoToNextFile(File) != UNZ_OK) Stop = true; } diff --git a/source/ZipFile.h b/source/ZipFile.h index 84999235..88487565 100644 --- a/source/ZipFile.h +++ b/source/ZipFile.h @@ -30,27 +30,29 @@ #include "unzip/unzip.h" -typedef struct { - u64 offset; // ZipFile offset - u64 length; // uncompressed file length in 64 bytes for sizes higher than 4GB - bool isdir; // 0 - file, 1 - directory - char filename[256]; // full filename +typedef struct +{ + u64 offset; // ZipFile offset + u64 length; // uncompressed file length in 64 bytes for sizes higher than 4GB + bool isdir; // 0 - file, 1 - directory + char filename[256]; // full filename } FileStructure; -class ZipFile { -public: - //!Constructor - ZipFile(const char *filepath); - //!Destructor - ~ZipFile(); - //!Extract all files from a zip file to a directory - //!\param dest Destination path to where to extract - bool ExtractAll(const char *dest); -protected: - bool LoadList(); - unzFile File; - unz_file_info cur_file_info; - FileStructure *FileList; +class ZipFile +{ + public: + //!Constructor + ZipFile(const char *filepath); + //!Destructor + ~ZipFile(); + //!Extract all files from a zip file to a directory + //!\param dest Destination path to where to extract + bool ExtractAll(const char *dest); + protected: + bool LoadList(); + unzFile File; + unz_file_info cur_file_info; + FileStructure *FileList; }; #endif diff --git a/source/banner/MD5.c b/source/banner/MD5.c index 1b96a2b2..0aeb6bc9 100644 --- a/source/banner/MD5.c +++ b/source/banner/MD5.c @@ -7,10 +7,10 @@ * * Email: crh@ubiqx.mn.org * - * $Id: MD5.c,v 0.6 2005/06/08 18:35:59 crh Exp $ + * $Id: MD5.c,v 0.6 2005/06/08 18:35:59 crh Exp $ * - * - * Modifications and additions by dimok + * + * Modifications and additions by dimok * * -------------------------------------------------------------------------- ** * @@ -75,14 +75,14 @@ * * ========================================================================== ** */ - -#include -#include -#include -#include -#include -#include -#include + +#include +#include +#include +#include +#include +#include +#include #include "MD5.h" @@ -110,26 +110,29 @@ * array. They're divided up into four groups of 16. */ -static const uint8_t K[3][16] = { +static const uint8_t K[3][16] = + { /* Round 1: skipped (since it is simply sequential). */ { 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12 }, /* R2 */ { 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2 }, /* R3 */ { 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9 } /* R4 */ -}; + }; -static const uint8_t S[4][4] = { +static const uint8_t S[4][4] = + { { 7, 12, 17, 22 }, /* Round 1 */ { 5, 9, 14, 20 }, /* Round 2 */ { 4, 11, 16, 23 }, /* Round 3 */ { 6, 10, 15, 21 } /* Round 4 */ -}; + }; -static const uint32_t T[4][16] = { +static const uint32_t T[4][16] = + { { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, /* Round 1 */ - 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, - 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, - 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 }, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 }, { 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, /* Round 2 */ 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, @@ -145,7 +148,7 @@ static const uint32_t T[4][16] = { 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }, -}; + }; /* -------------------------------------------------------------------------- ** @@ -165,8 +168,8 @@ static const uint32_t T[4][16] = { #define md5H( X, Y, Z ) ( (X) ^ (Y) ^ (Z) ) #define md5I( X, Y, Z ) ( (Y) ^ ((X) | (~(Z))) ) -#define GetLongByte( L, idx ) ((unsigned char)(( L >> (((idx) & 0x03) << 3) ) & 0xFF)) - +#define GetLongByte( L, idx ) ((unsigned char)(( L >> (((idx) & 0x03) << 3) ) & 0xFF)) + #define STR2HEX(x) ((x >= 0x30) && (x <= 0x39)) ? x - 0x30 : toupper((int)x)-0x37 @@ -175,118 +178,122 @@ static const uint32_t T[4][16] = { */ static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) -/* ------------------------------------------------------------------------ ** - * Permute the ABCD "registers" using the 64-byte as a driver. - * - * Input: ABCD - Pointer to an array of four unsigned longwords. - * block - An array of bytes, 64 bytes in size. - * - * Output: none. - * - * Notes: The MD5 algorithm operates on a set of four longwords stored - * (conceptually) in four "registers". It is easy to imagine a - * simple MD4/5 chip that would operate this way. In any case, - * the mangling of the contents of those registers is driven by - * the input message. The message is chopped and finally padded - * into 64-byte chunks and each chunk is used to manipulate the - * contents of the registers. - * - * The MD5 Algorithm calls for padding the input to ensure that - * it is a multiple of 64 bytes in length. The last 16 bytes - * of the padding space are used to store the message length - * (the length of the original message, before padding, expressed - * in terms of bits). If there is not enough room for 16 bytes - * worth of bitcount (eg., if the original message was 122 bytes - * long) then the block is padded to the end with zeros and - * passed to this function. Then *another* block is filled with - * zeros except for the last 16 bytes which contain the length. - * - * Oh... and the algorithm requires that there be at least one - * padding byte. The first padding byte has a value of 0x80, - * and any others are 0x00. - * - * ------------------------------------------------------------------------ ** - */ -{ - int round; - int i, j; - uint8_t s; - uint32_t a, b, c, d; - uint32_t KeepABCD[4]; - uint32_t X[16]; + /* ------------------------------------------------------------------------ ** + * Permute the ABCD "registers" using the 64-byte as a driver. + * + * Input: ABCD - Pointer to an array of four unsigned longwords. + * block - An array of bytes, 64 bytes in size. + * + * Output: none. + * + * Notes: The MD5 algorithm operates on a set of four longwords stored + * (conceptually) in four "registers". It is easy to imagine a + * simple MD4/5 chip that would operate this way. In any case, + * the mangling of the contents of those registers is driven by + * the input message. The message is chopped and finally padded + * into 64-byte chunks and each chunk is used to manipulate the + * contents of the registers. + * + * The MD5 Algorithm calls for padding the input to ensure that + * it is a multiple of 64 bytes in length. The last 16 bytes + * of the padding space are used to store the message length + * (the length of the original message, before padding, expressed + * in terms of bits). If there is not enough room for 16 bytes + * worth of bitcount (eg., if the original message was 122 bytes + * long) then the block is padded to the end with zeros and + * passed to this function. Then *another* block is filled with + * zeros except for the last 16 bytes which contain the length. + * + * Oh... and the algorithm requires that there be at least one + * padding byte. The first padding byte has a value of 0x80, + * and any others are 0x00. + * + * ------------------------------------------------------------------------ ** + */ + { + int round; + int i, j; + uint8_t s; + uint32_t a, b, c, d; + uint32_t KeepABCD[4]; + uint32_t X[16]; - /* Store the current ABCD values for later re-use. - */ - for ( i = 0; i < 4; i++ ) - KeepABCD[i] = ABCD[i]; + /* Store the current ABCD values for later re-use. + */ + for( i = 0; i < 4; i++ ) + KeepABCD[i] = ABCD[i]; - /* Convert the input block into an array of unsigned longs, taking care - * to read the block in Little Endian order (the algorithm assumes this). - * The uint32_t values are then handled in host order. - */ - for ( i = 0, j = 0; i < 16; i++ ) { - X[i] = (uint32_t)block[j++]; - X[i] |= ((uint32_t)block[j++] << 8); - X[i] |= ((uint32_t)block[j++] << 16); - X[i] |= ((uint32_t)block[j++] << 24); + /* Convert the input block into an array of unsigned longs, taking care + * to read the block in Little Endian order (the algorithm assumes this). + * The uint32_t values are then handled in host order. + */ + for( i = 0, j = 0; i < 16; i++ ) + { + X[i] = (uint32_t)block[j++]; + X[i] |= ((uint32_t)block[j++] << 8); + X[i] |= ((uint32_t)block[j++] << 16); + X[i] |= ((uint32_t)block[j++] << 24); } - /* This loop performs the four rounds of permutations. - * The rounds are each very similar. The differences are in three areas: - * - The function (F, G, H, or I) used to perform bitwise permutations - * on the registers, - * - The order in which values from X[] are chosen. - * - Changes to the number of bits by which the registers are rotated. - * This implementation uses a switch statement to deal with some of the - * differences between rounds. Other differences are handled by storing - * values in arrays and using the round number to select the correct set - * of values. - * - * (My implementation appears to be a poor compromise between speed, size, - * and clarity. Ugh. [crh]) - */ - for ( round = 0; round < 4; round++ ) { - for ( i = 0; i < 16; i++ ) { - j = (4 - (i % 4)) & 0x3; /* handles the rotation of ABCD. */ - s = S[round][i%4]; /* is the bit shift for this iteration. */ + /* This loop performs the four rounds of permutations. + * The rounds are each very similar. The differences are in three areas: + * - The function (F, G, H, or I) used to perform bitwise permutations + * on the registers, + * - The order in which values from X[] are chosen. + * - Changes to the number of bits by which the registers are rotated. + * This implementation uses a switch statement to deal with some of the + * differences between rounds. Other differences are handled by storing + * values in arrays and using the round number to select the correct set + * of values. + * + * (My implementation appears to be a poor compromise between speed, size, + * and clarity. Ugh. [crh]) + */ + for( round = 0; round < 4; round++ ) + { + for( i = 0; i < 16; i++ ) + { + j = (4 - (i % 4)) & 0x3; /* handles the rotation of ABCD. */ + s = S[round][i%4]; /* is the bit shift for this iteration. */ - b = ABCD[(j+1) & 0x3]; /* Copy the b,c,d values per ABCD rotation. */ - c = ABCD[(j+2) & 0x3]; /* This isn't really necessary, it just looks */ - d = ABCD[(j+3) & 0x3]; /* clean & will hopefully be optimized away. */ + b = ABCD[(j+1) & 0x3]; /* Copy the b,c,d values per ABCD rotation. */ + c = ABCD[(j+2) & 0x3]; /* This isn't really necessary, it just looks */ + d = ABCD[(j+3) & 0x3]; /* clean & will hopefully be optimized away. */ - /* The actual perumation function. - * This is broken out to minimize the code within the switch(). - */ - switch ( round ) { - case 0: - /* round 1 */ - a = md5F( b, c, d ) + X[i]; - break; - case 1: - /* round 2 */ - a = md5G( b, c, d ) + X[ K[0][i] ]; - break; - case 2: - /* round 3 */ - a = md5H( b, c, d ) + X[ K[1][i] ]; - break; - default: - /* round 4 */ - a = md5I( b, c, d ) + X[ K[2][i] ]; - break; - } - a = 0xFFFFFFFF & ( ABCD[j] + a + T[round][i] ); - ABCD[j] = b + (0xFFFFFFFF & (( a << s ) | ( a >> (32 - s) ))); + /* The actual perumation function. + * This is broken out to minimize the code within the switch(). + */ + switch( round ) + { + case 0: + /* round 1 */ + a = md5F( b, c, d ) + X[i]; + break; + case 1: + /* round 2 */ + a = md5G( b, c, d ) + X[ K[0][i] ]; + break; + case 2: + /* round 3 */ + a = md5H( b, c, d ) + X[ K[1][i] ]; + break; + default: + /* round 4 */ + a = md5I( b, c, d ) + X[ K[2][i] ]; + break; } + a = 0xFFFFFFFF & ( ABCD[j] + a + T[round][i] ); + ABCD[j] = b + (0xFFFFFFFF & (( a << s ) | ( a >> (32 - s) ))); + } } - /* Use the stored original A, B, C, D values to perform - * one last convolution. - */ - for ( i = 0; i < 4; i++ ) - ABCD[i] = 0xFFFFFFFF & ( ABCD[i] + KeepABCD[i] ); + /* Use the stored original A, B, C, D values to perform + * one last convolution. + */ + for( i = 0; i < 4; i++ ) + ABCD[i] = 0xFFFFFFFF & ( ABCD[i] + KeepABCD[i] ); -} /* Permute */ + } /* Permute */ /* -------------------------------------------------------------------------- ** @@ -294,321 +301,330 @@ static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) */ auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ) -/* ------------------------------------------------------------------------ ** - * Initialize an MD5 context. - * - * Input: ctx - A pointer to the MD5 context structure to be initialized. - * Contexts are typically created thusly: - * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); - * - * Output: A pointer to the initialized context (same as ). - * - * Notes: The purpose of the context is to make it possible to generate - * an MD5 Message Digest in stages, rather than having to pass a - * single large block to a single MD5 function. The context - * structure keeps track of various bits of state information. - * - * Once the context is initialized, the blocks of message data - * are passed to the function. Once the - * final bit of data has been handed to the - * context can be closed out by calling , - * which also calculates the final MD5 result. - * - * Don't forget to free an allocated context structure when - * you've finished using it. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ -{ - ctx->len = 0; - ctx->b_used = 0; + /* ------------------------------------------------------------------------ ** + * Initialize an MD5 context. + * + * Input: ctx - A pointer to the MD5 context structure to be initialized. + * Contexts are typically created thusly: + * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); + * + * Output: A pointer to the initialized context (same as ). + * + * Notes: The purpose of the context is to make it possible to generate + * an MD5 Message Digest in stages, rather than having to pass a + * single large block to a single MD5 function. The context + * structure keeps track of various bits of state information. + * + * Once the context is initialized, the blocks of message data + * are passed to the function. Once the + * final bit of data has been handed to the + * context can be closed out by calling , + * which also calculates the final MD5 result. + * + * Don't forget to free an allocated context structure when + * you've finished using it. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ + { + ctx->len = 0; + ctx->b_used = 0; - ctx->ABCD[0] = 0x67452301; /* The array ABCD[] contains the four 4-byte */ - ctx->ABCD[1] = 0xefcdab89; /* "registers" that are manipulated to */ - ctx->ABCD[2] = 0x98badcfe; /* produce the MD5 digest. The input acts */ - ctx->ABCD[3] = 0x10325476; /* upon the registers, not the other way */ - /* 'round. The initial values are those */ - /* given in RFC 1321 (pg. 4). Note, however, that RFC 1321 */ - /* provides these values as bytes, not as longwords, and the */ - /* bytes are arranged in little-endian order as if they were */ - /* the bytes of (little endian) 32-bit ints. That's */ - /* confusing as all getout (to me, anyway). The values given */ - /* here are provided as 32-bit values in C language format, */ - /* so they are endian-agnostic. */ - return( ctx ); -} /* auth_md5InitCtx */ + ctx->ABCD[0] = 0x67452301; /* The array ABCD[] contains the four 4-byte */ + ctx->ABCD[1] = 0xefcdab89; /* "registers" that are manipulated to */ + ctx->ABCD[2] = 0x98badcfe; /* produce the MD5 digest. The input acts */ + ctx->ABCD[3] = 0x10325476; /* upon the registers, not the other way */ + /* 'round. The initial values are those */ + /* given in RFC 1321 (pg. 4). Note, however, that RFC 1321 */ + /* provides these values as bytes, not as longwords, and the */ + /* bytes are arranged in little-endian order as if they were */ + /* the bytes of (little endian) 32-bit ints. That's */ + /* confusing as all getout (to me, anyway). The values given */ + /* here are provided as 32-bit values in C language format, */ + /* so they are endian-agnostic. */ + return( ctx ); + } /* auth_md5InitCtx */ auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, const unsigned char *src, const int len ) -/* ------------------------------------------------------------------------ ** - * Build an MD5 Message Digest within the given context. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * src - A chunk of source data. This will be used to drive - * the MD5 algorithm. - * len - The number of bytes in . - * - * Output: A pointer to the updated context (same as ). - * - * See Also: , , - * - * ------------------------------------------------------------------------ ** - */ -{ - int i; + /* ------------------------------------------------------------------------ ** + * Build an MD5 Message Digest within the given context. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * src - A chunk of source data. This will be used to drive + * the MD5 algorithm. + * len - The number of bytes in . + * + * Output: A pointer to the updated context (same as ). + * + * See Also: , , + * + * ------------------------------------------------------------------------ ** + */ + { + int i; - /* Add the new block's length to the total length. - */ - ctx->len += (uint32_t)len; + /* Add the new block's length to the total length. + */ + ctx->len += (uint32_t)len; - /* Copy the new block's data into the context block. - * Call the Permute() function whenever the context block is full. - */ - for ( i = 0; i < len; i++ ) { - ctx->block[ ctx->b_used ] = src[i]; - (ctx->b_used)++; - if ( 64 == ctx->b_used ) { - Permute( ctx->ABCD, ctx->block ); - ctx->b_used = 0; - } + /* Copy the new block's data into the context block. + * Call the Permute() function whenever the context block is full. + */ + for( i = 0; i < len; i++ ) + { + ctx->block[ ctx->b_used ] = src[i]; + (ctx->b_used)++; + if( 64 == ctx->b_used ) + { + Permute( ctx->ABCD, ctx->block ); + ctx->b_used = 0; + } } - /* Return the updated context. - */ - return( ctx ); -} /* auth_md5SumCtx */ + /* Return the updated context. + */ + return( ctx ); + } /* auth_md5SumCtx */ auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ) -/* ------------------------------------------------------------------------ ** - * Close an MD5 Message Digest context and generate the final MD5 sum. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * dst - A pointer to at least 16 bytes of memory, which will - * receive the finished MD5 sum. - * - * Output: A pointer to the closed context (same as ). - * You might use this to free a malloc'd context structure. :) - * - * Notes: The context () is returned in an undefined state. - * It must be re-initialized before re-use. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ -{ - int i; - uint32_t l; + /* ------------------------------------------------------------------------ ** + * Close an MD5 Message Digest context and generate the final MD5 sum. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * dst - A pointer to at least 16 bytes of memory, which will + * receive the finished MD5 sum. + * + * Output: A pointer to the closed context (same as ). + * You might use this to free a malloc'd context structure. :) + * + * Notes: The context () is returned in an undefined state. + * It must be re-initialized before re-use. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ + { + int i; + uint32_t l; - /* Add the required 0x80 padding initiator byte. - * The auth_md5SumCtx() function always permutes and resets the context - * block when it gets full, so we know that there must be at least one - * free byte in the context block. - */ - ctx->block[ctx->b_used] = 0x80; - (ctx->b_used)++; + /* Add the required 0x80 padding initiator byte. + * The auth_md5SumCtx() function always permutes and resets the context + * block when it gets full, so we know that there must be at least one + * free byte in the context block. + */ + ctx->block[ctx->b_used] = 0x80; + (ctx->b_used)++; - /* Zero out any remaining free bytes in the context block. - */ - for ( i = ctx->b_used; i < 64; i++ ) - ctx->block[i] = 0; + /* Zero out any remaining free bytes in the context block. + */ + for( i = ctx->b_used; i < 64; i++ ) + ctx->block[i] = 0; - /* We need 8 bytes to store the length field. - * If we don't have 8, call Permute() and reset the context block. - */ - if ( 56 < ctx->b_used ) { - Permute( ctx->ABCD, ctx->block ); - for ( i = 0; i < 64; i++ ) - ctx->block[i] = 0; - } - - /* Add the total length and perform the final perumation. - * Note: The 60'th byte is read from the *original* len> value - * and shifted to the correct position. This neatly avoids - * any MAXINT numeric overflow issues. - */ - l = ctx->len << 3; - for ( i = 0; i < 4; i++ ) - ctx->block[56+i] |= GetLongByte( l, i ); - ctx->block[60] = ((GetLongByte( ctx->len, 3 ) & 0xE0) >> 5); /* See Above! */ + /* We need 8 bytes to store the length field. + * If we don't have 8, call Permute() and reset the context block. + */ + if( 56 < ctx->b_used ) + { Permute( ctx->ABCD, ctx->block ); - - /* Now copy the result into the output buffer and we're done. - */ - for ( i = 0; i < 4; i++ ) { - dst[ 0+i] = GetLongByte( ctx->ABCD[0], i ); - dst[ 4+i] = GetLongByte( ctx->ABCD[1], i ); - dst[ 8+i] = GetLongByte( ctx->ABCD[2], i ); - dst[12+i] = GetLongByte( ctx->ABCD[3], i ); + for( i = 0; i < 64; i++ ) + ctx->block[i] = 0; } - /* Return the context. - * This is done for compatibility with the other auth_md5*Ctx() functions. - */ - return( ctx ); -} /* auth_md5CloseCtx */ + /* Add the total length and perform the final perumation. + * Note: The 60'th byte is read from the *original* len> value + * and shifted to the correct position. This neatly avoids + * any MAXINT numeric overflow issues. + */ + l = ctx->len << 3; + for( i = 0; i < 4; i++ ) + ctx->block[56+i] |= GetLongByte( l, i ); + ctx->block[60] = ((GetLongByte( ctx->len, 3 ) & 0xE0) >> 5); /* See Above! */ + Permute( ctx->ABCD, ctx->block ); + + /* Now copy the result into the output buffer and we're done. + */ + for( i = 0; i < 4; i++ ) + { + dst[ 0+i] = GetLongByte( ctx->ABCD[0], i ); + dst[ 4+i] = GetLongByte( ctx->ABCD[1], i ); + dst[ 8+i] = GetLongByte( ctx->ABCD[2], i ); + dst[12+i] = GetLongByte( ctx->ABCD[3], i ); + } + + /* Return the context. + * This is done for compatibility with the other auth_md5*Ctx() functions. + */ + return( ctx ); + } /* auth_md5CloseCtx */ unsigned char * MD5(unsigned char *dst, const unsigned char *src, const int len ) -/* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - Source data block to be MD5'd. - * len - The length, in bytes, of the source block. - * (Note that the length is given in bytes, not bits.) - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ -{ - auth_md5Ctx ctx[1]; - - (void)auth_md5InitCtx( ctx ); /* Open a context. */ - (void)auth_md5SumCtx( ctx, src, len ); /* Pass only one block. */ - (void)auth_md5CloseCtx( ctx, dst ); /* Close the context. */ - - return( dst ); /* Makes life easy. */ -} /* auth_md5Sum */ - + /* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - Source data block to be MD5'd. + * len - The length, in bytes, of the source block. + * (Note that the length is given in bytes, not bits.) + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ + { + auth_md5Ctx ctx[1]; + (void)auth_md5InitCtx( ctx ); /* Open a context. */ + (void)auth_md5SumCtx( ctx, src, len ); /* Pass only one block. */ + (void)auth_md5CloseCtx( ctx, dst ); /* Close the context. */ + return( dst ); /* Makes life easy. */ + } /* auth_md5Sum */ + + + unsigned char * MD5fromFile(unsigned char *dst, const char *src) -/* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - filepath of the file to be checked - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ -{ - auth_md5Ctx ctx[1]; - - FILE * file; - unsigned int blksize = 0; - unsigned int read = 0; - + /* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - filepath of the file to be checked + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ + { + auth_md5Ctx ctx[1]; + + FILE * file; + unsigned int blksize = 0; + unsigned int read = 0; + file = fopen(src, "rb"); - if (file==NULL) { + if (file==NULL){ return NULL; } - (void)auth_md5InitCtx( ctx ); /* Open a context. */ - - fseek (file , 0 , SEEK_END); - unsigned long long filesize = ftell(file); - rewind (file); - - if (filesize < 1048576) //1MB cache for files bigger than 1 MB - blksize = filesize; - else - blksize = 1048576; - + (void)auth_md5InitCtx( ctx ); /* Open a context. */ + + fseek (file , 0 , SEEK_END); + unsigned long long filesize = ftell(file); + rewind (file); + + if(filesize < 1048576) //1MB cache for files bigger than 1 MB + blksize = filesize; + else + blksize = 1048576; + unsigned char * buffer = malloc(blksize); - - if (buffer == NULL) { - //no memory - fclose(file); - return NULL; - } - - do { - read = fread(buffer, 1, blksize, file); - (void)auth_md5SumCtx( ctx, buffer, read ); /* Pass only one block. */ - - } while (read > 0); - - fclose(file); - free(buffer); + + if(buffer == NULL){ + //no memory + fclose(file); + return NULL; + } + + do + { + read = fread(buffer, 1, blksize, file); + (void)auth_md5SumCtx( ctx, buffer, read ); /* Pass only one block. */ + + } while(read > 0); + + fclose(file); + free(buffer); (void)auth_md5CloseCtx( ctx, dst ); /* Close the context. */ return( dst ); /* Makes life easy. */ -} /* auth_md5Sum */ - - -const char * MD5ToString(const unsigned char * hash, char * dst) { - char hexchar[3]; - short i = 0, n = 0; - - for (i = 0; i < 16; i++) { - sprintf(hexchar, "%02X", hash[i]); - - dst[n++] = hexchar[0]; - dst[n++] = hexchar[1]; - } - - dst[n] = 0x00; - - return dst; -} - -unsigned char * StringToMD5(const char * hash, unsigned char * dst) { - char hexchar[2]; - short i = 0, n = 0; - - for (i = 0; i < 16; i++) { - hexchar[0] = hash[n++]; - hexchar[1] = hash[n++]; - - dst[i] = STR2HEX(hexchar[0]); - dst[i] <<= 4; - dst[i] += STR2HEX(hexchar[1]); - } - - return dst; + } /* auth_md5Sum */ + + +const char * MD5ToString(const unsigned char * hash, char * dst) +{ + char hexchar[3]; + short i = 0, n = 0; + + for (i = 0; i < 16; i++) + { + sprintf(hexchar, "%02X", hash[i]); + + dst[n++] = hexchar[0]; + dst[n++] = hexchar[1]; + } + + dst[n] = 0x00; + + return dst; +} + +unsigned char * StringToMD5(const char * hash, unsigned char * dst) +{ + char hexchar[2]; + short i = 0, n = 0; + + for (i = 0; i < 16; i++) + { + hexchar[0] = hash[n++]; + hexchar[1] = hash[n++]; + + dst[i] = STR2HEX(hexchar[0]); + dst[i] <<= 4; + dst[i] += STR2HEX(hexchar[1]); + } + + return dst; } diff --git a/source/banner/MD5.h b/source/banner/MD5.h index 67ea4a41..fb67ab25 100644 --- a/source/banner/MD5.h +++ b/source/banner/MD5.h @@ -1,244 +1,246 @@ -#ifndef MD5_H +#ifndef MD5_H #define MD5_H #ifdef __cplusplus -extern "C" { -#endif - /* ========================================================================== ** - * - * MD5.h - * - * Copyright: - * Copyright (C) 2003-2005 by Christopher R. Hertel - * - * Email: crh@ubiqx.mn.org - * - * $Id: MD5.h,v 0.6 2005/06/08 18:35:59 crh Exp $ - * - * Modifications and additions by dimok - * - * -------------------------------------------------------------------------- ** - * - * Description: - * Implements the MD5 hash algorithm, as described in RFC 1321. - * - * -------------------------------------------------------------------------- ** - * - * License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * -------------------------------------------------------------------------- ** - * - * Notes: - * - * None of this will make any sense unless you're studying RFC 1321 as you - * read the code. - * - * MD5 is described in RFC 1321. - * The MD*4* algorithm is described in RFC 1320 (that's 1321 - 1). - * MD5 is very similar to MD4, but not quite similar enough to justify - * putting the two into a single module. Besides, I wanted to add a few - * extra functions to this one to expand its usability. - * - * There are three primary motivations for this particular implementation. - * 1) Programmer's pride. I wanted to be able to say I'd done it, and I - * wanted to learn from the experience. - * 2) Portability. I wanted an implementation that I knew to be portable - * to a reasonable number of platforms. In particular, the algorithm is - * designed with little-endian platforms in mind, but I wanted an - * endian-agnostic implementation. - * 3) Compactness. While not an overriding goal, I thought it worth-while - * to see if I could reduce the overall size of the result. This is in - * keeping with my hopes that this library will be suitable for use in - * some embedded environments. - * Beyond that, cleanliness and clarity are always worth pursuing. - * - * As mentioned above, the code really only makes sense if you are familiar - * with the MD5 algorithm or are using RFC 1321 as a guide. This code is - * quirky, however, so you'll want to be reading carefully. - * - * Yeah...most of the comments are cut-and-paste from my MD4 implementation. - * - * -------------------------------------------------------------------------- ** - * - * References: - * IETF RFC 1321: The MD5 Message-Digest Algorithm - * Ron Rivest. IETF, April, 1992 - * - * ========================================================================== ** - */ - /* -------------------------------------------------------------------------- ** - * Typedefs: - */ +extern "C" +{ +#endif +/* ========================================================================== ** + * + * MD5.h + * + * Copyright: + * Copyright (C) 2003-2005 by Christopher R. Hertel + * + * Email: crh@ubiqx.mn.org + * + * $Id: MD5.h,v 0.6 2005/06/08 18:35:59 crh Exp $ + * + * Modifications and additions by dimok + * + * -------------------------------------------------------------------------- ** + * + * Description: + * Implements the MD5 hash algorithm, as described in RFC 1321. + * + * -------------------------------------------------------------------------- ** + * + * License: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- ** + * + * Notes: + * + * None of this will make any sense unless you're studying RFC 1321 as you + * read the code. + * + * MD5 is described in RFC 1321. + * The MD*4* algorithm is described in RFC 1320 (that's 1321 - 1). + * MD5 is very similar to MD4, but not quite similar enough to justify + * putting the two into a single module. Besides, I wanted to add a few + * extra functions to this one to expand its usability. + * + * There are three primary motivations for this particular implementation. + * 1) Programmer's pride. I wanted to be able to say I'd done it, and I + * wanted to learn from the experience. + * 2) Portability. I wanted an implementation that I knew to be portable + * to a reasonable number of platforms. In particular, the algorithm is + * designed with little-endian platforms in mind, but I wanted an + * endian-agnostic implementation. + * 3) Compactness. While not an overriding goal, I thought it worth-while + * to see if I could reduce the overall size of the result. This is in + * keeping with my hopes that this library will be suitable for use in + * some embedded environments. + * Beyond that, cleanliness and clarity are always worth pursuing. + * + * As mentioned above, the code really only makes sense if you are familiar + * with the MD5 algorithm or are using RFC 1321 as a guide. This code is + * quirky, however, so you'll want to be reading carefully. + * + * Yeah...most of the comments are cut-and-paste from my MD4 implementation. + * + * -------------------------------------------------------------------------- ** + * + * References: + * IETF RFC 1321: The MD5 Message-Digest Algorithm + * Ron Rivest. IETF, April, 1992 + * + * ========================================================================== ** + */ +/* -------------------------------------------------------------------------- ** + * Typedefs: + */ - typedef struct { - unsigned int len; - unsigned int ABCD[4]; - int b_used; - unsigned char block[64]; - } auth_md5Ctx; +typedef struct + { + unsigned int len; + unsigned int ABCD[4]; + int b_used; + unsigned char block[64]; + } auth_md5Ctx; - /* -------------------------------------------------------------------------- ** - * Functions: - */ +/* -------------------------------------------------------------------------- ** + * Functions: + */ - auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ); - /* ------------------------------------------------------------------------ ** - * Initialize an MD5 context. - * - * Input: ctx - A pointer to the MD5 context structure to be initialized. - * Contexts are typically created thusly: - * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); - * - * Output: A pointer to the initialized context (same as ). - * - * Notes: The purpose of the context is to make it possible to generate - * an MD5 Message Digest in stages, rather than having to pass a - * single large block to a single MD5 function. The context - * structure keeps track of various bits of state information. - * - * Once the context is initialized, the blocks of message data - * are passed to the function. Once the - * final bit of data has been handed to the - * context can be closed out by calling , - * which also calculates the final MD5 result. - * - * Don't forget to free an allocated context structure when - * you've finished using it. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ +auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ); + /* ------------------------------------------------------------------------ ** + * Initialize an MD5 context. + * + * Input: ctx - A pointer to the MD5 context structure to be initialized. + * Contexts are typically created thusly: + * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); + * + * Output: A pointer to the initialized context (same as ). + * + * Notes: The purpose of the context is to make it possible to generate + * an MD5 Message Digest in stages, rather than having to pass a + * single large block to a single MD5 function. The context + * structure keeps track of various bits of state information. + * + * Once the context is initialized, the blocks of message data + * are passed to the function. Once the + * final bit of data has been handed to the + * context can be closed out by calling , + * which also calculates the final MD5 result. + * + * Don't forget to free an allocated context structure when + * you've finished using it. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ - auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, - const unsigned char *src, - const int len ); - /* ------------------------------------------------------------------------ ** - * Build an MD5 Message Digest within the given context. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * src - A chunk of source data. This will be used to drive - * the MD5 algorithm. - * len - The number of bytes in . - * - * Output: A pointer to the updated context (same as ). - * - * See Also: , , - * - * ------------------------------------------------------------------------ ** - */ +auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, + const unsigned char *src, + const int len ); + /* ------------------------------------------------------------------------ ** + * Build an MD5 Message Digest within the given context. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * src - A chunk of source data. This will be used to drive + * the MD5 algorithm. + * len - The number of bytes in . + * + * Output: A pointer to the updated context (same as ). + * + * See Also: , , + * + * ------------------------------------------------------------------------ ** + */ - auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ); - /* ------------------------------------------------------------------------ ** - * Close an MD5 Message Digest context and generate the final MD5 sum. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * dst - A pointer to at least 16 bytes of memory, which will - * receive the finished MD5 sum. - * - * Output: A pointer to the closed context (same as ). - * You might use this to free a malloc'd context structure. :) - * - * Notes: The context () is returned in an undefined state. - * It must be re-initialized before re-use. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ +auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ); + /* ------------------------------------------------------------------------ ** + * Close an MD5 Message Digest context and generate the final MD5 sum. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * dst - A pointer to at least 16 bytes of memory, which will + * receive the finished MD5 sum. + * + * Output: A pointer to the closed context (same as ). + * You might use this to free a malloc'd context structure. :) + * + * Notes: The context () is returned in an undefined state. + * It must be re-initialized before re-use. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ - unsigned char * MD5(unsigned char * hash, const unsigned char *src, const int len ); - /* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - Source data block to be MD5'd. - * len - The length, in bytes, of the source block. - * (Note that the length is given in bytes, not bits.) - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ +unsigned char * MD5(unsigned char * hash, const unsigned char *src, const int len ); + /* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - Source data block to be MD5'd. + * len - The length, in bytes, of the source block. + * (Note that the length is given in bytes, not bits.) + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ - unsigned char * MD5fromFile(unsigned char *dst, const char *src); - /* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - filepath to the file to be MD5'd. - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ +unsigned char * MD5fromFile(unsigned char *dst, const char *src); + /* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - filepath to the file to be MD5'd. + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ - const char * MD5ToString(const unsigned char *hash, char *dst); - unsigned char * StringToMD5(const char * hash, unsigned char * dst); +const char * MD5ToString(const unsigned char *hash, char *dst); +unsigned char * StringToMD5(const char * hash, unsigned char * dst); - /* ========================================================================== */ - -#ifdef __cplusplus -} +/* ========================================================================== */ + +#ifdef __cplusplus +} #endif #endif /* AUTH_MD5_H */ diff --git a/source/banner/banner.c b/source/banner/banner.c index 1ceb8dcd..62340b83 100644 --- a/source/banner/banner.c +++ b/source/banner/banner.c @@ -22,98 +22,106 @@ #include "patches/fst.h" #include "usbloader/fstfile.h" -s32 dump_banner(const u8* discid,const char * dest) { - // Mount the disc - //Disc_SetWBFS(1, (u8*)discid); - Disc_SetUSB(discid); +s32 dump_banner(const u8* discid,const char * dest) +{ + // Mount the disc + //Disc_SetWBFS(1, (u8*)discid); + Disc_SetUSB(discid); - Disc_Open(); + Disc_Open(); - u64 offset; - s32 ret; + u64 offset; + s32 ret; - ret = __Disc_FindPartition(&offset); - if (ret < 0) - return ret; + ret = __Disc_FindPartition(&offset); + if (ret < 0) + return ret; - ret = WDVD_OpenPartition(offset); + ret = WDVD_OpenPartition(offset); - if (ret < 0) { - //printf("ERROR: OpenPartition(0x%llx) %d\n", offset, ret); - return ret; - } + if (ret < 0) { + //printf("ERROR: OpenPartition(0x%llx) %d\n", offset, ret); + return ret; + } - // Read where to find the fst.bin - u32 *buffer = memalign(32, 0x20); + // Read where to find the fst.bin + u32 *buffer = memalign(32, 0x20); - if (buffer == NULL) { - //Out of memory - return -1; - } + if (buffer == NULL) + { + //Out of memory + return -1; + } - ret = WDVD_Read(buffer, 0x20, 0x420); - if (ret < 0) - return ret; + ret = WDVD_Read(buffer, 0x20, 0x420); + if (ret < 0) + return ret; - // Read fst.bin - void *fstbuffer = memalign(32, buffer[2]*4); - FST_ENTRY *fst = (FST_ENTRY *)fstbuffer; + // Read fst.bin + void *fstbuffer = memalign(32, buffer[2]*4); + FST_ENTRY *fst = (FST_ENTRY *)fstbuffer; - if (fst == NULL) { - //Out of memory - free(buffer); - return -1; - } + if (fst == NULL) + { + //Out of memory + free(buffer); + return -1; + } - ret = WDVD_Read(fstbuffer, buffer[2]*4, buffer[1]*4); - if (ret < 0) - return ret; + ret = WDVD_Read(fstbuffer, buffer[2]*4, buffer[1]*4); + if (ret < 0) + return ret; - free(buffer); + free(buffer); - // Search the fst.bin - u32 count = fst[0].filelen; - int i; - u32 index = 0; + // Search the fst.bin + u32 count = fst[0].filelen; + int i; + u32 index = 0; - for (i=1;iIsVisible()) - return; - - float currScale = this->GetScale(); + } +} + +void GuiBanner::Draw() +{ + LOCK(this); + if(!filecheck ||!this->IsVisible()) + return; + + float currScale = this->GetScale(); Menu_DrawTPLImg(this->GetLeft(), this->GetTop(), 0, width, height, &texObj, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1,yy1,xx2,yy2,xx3,yy3,xx4,yy4); - - this->UpdateEffects(); -} + + this->UpdateEffects(); +} diff --git a/source/banner/gui_banner.h b/source/banner/gui_banner.h index c4dab13e..d372baaf 100644 --- a/source/banner/gui_banner.h +++ b/source/banner/gui_banner.h @@ -10,24 +10,25 @@ #include "libwiigui/gui.h" -class GuiBanner : public GuiImage { +class GuiBanner : public GuiImage +{ public: //!Constructor //!\param tplfilepath Path of the tpl file - GuiBanner(const char *tplfilepath); + GuiBanner(const char *tplfilepath); //!Constructor //!\param mem Memory of the loaded tpl //!\param len Filesize of the tpl //!\param w Width of the tpl //!\param h Height of the tpl - GuiBanner(void *mem, u32 len, int w, int h); + GuiBanner(void *mem, u32 len, int w, int h); //!Destructor - ~GuiBanner(); - void Draw(); + ~GuiBanner(); + void Draw(); protected: void * memory; - bool filecheck; - u32 tplfilesize; + bool filecheck; + u32 tplfilesize; GXTexObj texObj; }; diff --git a/source/banner/openingbnr.c b/source/banner/openingbnr.c index 2220b472..26b502d6 100644 --- a/source/banner/openingbnr.c +++ b/source/banner/openingbnr.c @@ -28,39 +28,47 @@ #include "../ramdisk/ramdisk.h" #include "../listfiles.h" -u16 be16(const u8 *p) { - return (p[0] << 8) | p[1]; +u16 be16(const u8 *p) +{ + return (p[0] << 8) | p[1]; } -u32 be32(const u8 *p) { - return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; +u32 be32(const u8 *p) +{ + return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; } -u64 be64(const u8 *p) { - return ((u64)be32(p) << 32) | be32(p + 4); +u64 be64(const u8 *p) +{ + return ((u64)be32(p) << 32) | be32(p + 4); } -u64 be34(const u8 *p) { - return 4 * (u64)be32(p); +u64 be34(const u8 *p) +{ + return 4 * (u64)be32(p); } -void wbe16(u8 *p, u16 x) { - p[0] = x >> 8; - p[1] = x; +void wbe16(u8 *p, u16 x) +{ + p[0] = x >> 8; + p[1] = x; } -void wbe32(u8 *p, u32 x) { - wbe16(p, x >> 16); - wbe16(p + 2, x); +void wbe32(u8 *p, u32 x) +{ + wbe16(p, x >> 16); + wbe16(p + 2, x); } -void wbe64(u8 *p, u64 x) { - wbe32(p, x >> 32); - wbe32(p + 4, x); +void wbe64(u8 *p, u64 x) +{ + wbe32(p, x >> 32); + wbe32(p + 4, x); } -void md5(u8 *data, u32 len, u8 *hash) { - MD5(hash, data, len); +void md5(u8 *data, u32 len, u8 *hash) +{ + MD5(hash, data, len); } @@ -82,416 +90,440 @@ typedef struct { } imet_data_t; typedef struct { - u32 imd5_tag; // 0x494D4435 "IMD5"; - u32 size; // size of the rest of part B, starting from next field. - u8 zeroes[8]; - u8 md5[16]; - u32 payload_tag; // 0x4C5A3737 "LZ77" if this is lz77 - u32 payload_data; + u32 imd5_tag; // 0x494D4435 "IMD5"; + u32 size; // size of the rest of part B, starting from next field. + u8 zeroes[8]; + u8 md5[16]; + u32 payload_tag; // 0x4C5A3737 "LZ77" if this is lz77 + u32 payload_data; } imd5_header_t; -typedef struct { - u16 type; - u16 name_offset; - u32 data_offset; // == absolut offset från U.8- headerns början - u32 size; // last included file num for directories +typedef struct +{ + u16 type; + u16 name_offset; + u32 data_offset; // == absolut offset från U.8- headerns början + u32 size; // last included file num for directories } U8_node; -typedef struct { - u32 tag; // 0x55AA382D "U.8-" - u32 rootnode_offset; // offset to root_node, always 0x20. - u32 header_size; // size of header from root_node to end of string table. - u32 data_offset; // offset to data -- this is rootnode_offset + header_size, aligned to 0x40. - u8 zeroes[16]; +typedef struct +{ + u32 tag; // 0x55AA382D "U.8-" + u32 rootnode_offset; // offset to root_node, always 0x20. + u32 header_size; // size of header from root_node to end of string table. + u32 data_offset; // offset to data -- this is rootnode_offset + header_size, aligned to 0x40. + u8 zeroes[16]; } U8_archive_header; -static int write_file(void* data, size_t size, char* name) { - size_t written=0; - FILE *out; - out = fopen(name, "wb"); - if (out) { - written = fwrite(data, 1, size, out); - fclose(out); - } - return (written == size) ? 1 : -1; +static int write_file(void* data, size_t size, char* name) +{ + size_t written=0; + FILE *out; + out = fopen(name, "wb"); + if(out) + { + written = fwrite(data, 1, size, out); + fclose(out); + } + return (written == size) ? 1 : -1; } -u8* decompress_lz77(u8 *data, size_t data_size, size_t* decompressed_size) { - u8 *data_end; - u8 *decompressed_data; - size_t unpacked_size; - u8 *in_ptr; - u8 *out_ptr; - u8 *out_end; +u8* decompress_lz77(u8 *data, size_t data_size, size_t* decompressed_size) +{ + u8 *data_end; + u8 *decompressed_data; + size_t unpacked_size; + u8 *in_ptr; + u8 *out_ptr; + u8 *out_end; - in_ptr = data; - data_end = data + data_size; + in_ptr = data; + data_end = data + data_size; - // Assume this for now and grow when needed - unpacked_size = data_size; + // Assume this for now and grow when needed + unpacked_size = data_size; - decompressed_data = malloc(unpacked_size); - out_end = decompressed_data + unpacked_size; + decompressed_data = malloc(unpacked_size); + out_end = decompressed_data + unpacked_size; - out_ptr = decompressed_data; + out_ptr = decompressed_data; - while (in_ptr < data_end) { - int bit; - u8 bitmask = *in_ptr; + while (in_ptr < data_end) { + int bit; + u8 bitmask = *in_ptr; - in_ptr++; - for (bit = 0x80; bit != 0; bit >>= 1) { - if (bitmask & bit) { - // Next section is compressed - u8 rep_length; - u16 rep_offset; + in_ptr++; + for (bit = 0x80; bit != 0; bit >>= 1) { + if (bitmask & bit) { + // Next section is compressed + u8 rep_length; + u16 rep_offset; - rep_length = (*in_ptr >> 4) + 3; - rep_offset = *in_ptr & 0x0f; - in_ptr++; - rep_offset = *in_ptr | (rep_offset << 8); - in_ptr++; - if (out_ptr-decompressed_data < rep_offset) { - return NULL; - } + rep_length = (*in_ptr >> 4) + 3; + rep_offset = *in_ptr & 0x0f; + in_ptr++; + rep_offset = *in_ptr | (rep_offset << 8); + in_ptr++; + if (out_ptr-decompressed_data < rep_offset) { + return NULL; + } - for ( ; rep_length > 0; rep_length--) { - *out_ptr = out_ptr[-rep_offset-1]; - out_ptr++; - if (out_ptr >= out_end) { - // Need to grow buffer - decompressed_data = realloc(decompressed_data, unpacked_size*2); - out_ptr = decompressed_data + unpacked_size; - unpacked_size *= 2; - out_end = decompressed_data + unpacked_size; - } - } - } else { - // Just copy byte - *out_ptr = *in_ptr; - out_ptr++; - if (out_ptr >= out_end) { - // Need to grow buffer - decompressed_data = realloc(decompressed_data, unpacked_size*2); - out_ptr = decompressed_data + unpacked_size; - unpacked_size *= 2; - out_end = decompressed_data + unpacked_size; - } - in_ptr++; - } + for ( ; rep_length > 0; rep_length--) { + *out_ptr = out_ptr[-rep_offset-1]; + out_ptr++; + if (out_ptr >= out_end) { + // Need to grow buffer + decompressed_data = realloc(decompressed_data, unpacked_size*2); + out_ptr = decompressed_data + unpacked_size; + unpacked_size *= 2; + out_end = decompressed_data + unpacked_size; + } } - } + } else { + // Just copy byte + *out_ptr = *in_ptr; + out_ptr++; + if (out_ptr >= out_end) { + // Need to grow buffer + decompressed_data = realloc(decompressed_data, unpacked_size*2); + out_ptr = decompressed_data + unpacked_size; + unpacked_size *= 2; + out_end = decompressed_data + unpacked_size; + } + in_ptr++; + } + } + } - *decompressed_size = (out_ptr - decompressed_data); - return decompressed_data; + *decompressed_size = (out_ptr - decompressed_data); + return decompressed_data; } -static int write_imd5_lz77(u8* data, size_t size, char* outname) { - imd5_header_t* header = (imd5_header_t*) data; - u32 tag; - u32 size_in_imd5; +static int write_imd5_lz77(u8* data, size_t size, char* outname) +{ + imd5_header_t* header = (imd5_header_t*) data; + u32 tag; + u32 size_in_imd5; u8 md5_calc[16]; - u8 *decompressed_data; - size_t decompressed_size; + u8 *decompressed_data; + size_t decompressed_size; - tag = be32((u8*) &header->imd5_tag); - if (tag != 0x494D4435) { - return -4; - } + tag = be32((u8*) &header->imd5_tag); + if (tag != 0x494D4435) { + return -4; + } - md5(data+32, size-32, md5_calc); - if (memcmp(&header->md5, md5_calc, 0x10)) { - return -5; - } + md5(data+32, size-32, md5_calc); + if (memcmp(&header->md5, md5_calc, 0x10)) { + return -5; + } - size_in_imd5 = be32((u8*) &header->size); - if (size_in_imd5 != size - 32) { - return -6; - } + size_in_imd5 = be32((u8*) &header->size); + if (size_in_imd5 != size - 32) { + return -6; + } - tag = be32((u8*) &header->payload_tag); - if (tag == 0x4C5A3737) { - // "LZ77" - uncompress - decompressed_data = decompress_lz77(data + sizeof(imd5_header_t), size - sizeof(imd5_header_t), &decompressed_size); - if (decompressed_data == NULL) - return -7; - write_file(decompressed_data, decompressed_size, outname); - //printf(", uncompressed %d bytes, md5 ok", decompressed_size); + tag = be32((u8*) &header->payload_tag); + if (tag == 0x4C5A3737) { + // "LZ77" - uncompress + decompressed_data = decompress_lz77(data + sizeof(imd5_header_t), size - sizeof(imd5_header_t), &decompressed_size); + if(decompressed_data == NULL) + return -7; + write_file(decompressed_data, decompressed_size, outname); + //printf(", uncompressed %d bytes, md5 ok", decompressed_size); - free(decompressed_data); - } else { - write_file(&header->payload_tag, size-32, outname); - //printf(", md5 ok"); - } - return 0; + free(decompressed_data); + } else { + write_file(&header->payload_tag, size-32, outname); + //printf(", md5 ok"); + } + return 0; } -static int do_U8_archive(FILE *fp) { - U8_archive_header header; - U8_node root_node; - u32 tag; - u32 num_nodes; - U8_node* nodes; - u8* string_table; - size_t rest_size; - unsigned int i; - u32 data_offset; - u32 current_offset; - u16 dir_stack[16]; - int dir_index = 0; +static int do_U8_archive(FILE *fp) +{ + U8_archive_header header; + U8_node root_node; + u32 tag; + u32 num_nodes; + U8_node* nodes; + u8* string_table; + size_t rest_size; + unsigned int i; + u32 data_offset; + u32 current_offset; + u16 dir_stack[16]; + int dir_index = 0; - fread(&header, 1, sizeof header, fp); - tag = be32((u8*) &header.tag); - if (tag != 0x55AA382D) { - return -1; - } + fread(&header, 1, sizeof header, fp); + tag = be32((u8*) &header.tag); + if (tag != 0x55AA382D) { + return -1; + } - fread(&root_node, 1, sizeof(root_node), fp); - num_nodes = be32((u8*) &root_node.size) - 1; - //printf("Number of files: %d\n", num_nodes); + fread(&root_node, 1, sizeof(root_node), fp); + num_nodes = be32((u8*) &root_node.size) - 1; + //printf("Number of files: %d\n", num_nodes); - nodes = malloc(sizeof(U8_node) * (num_nodes)); - fread(nodes, 1, num_nodes * sizeof(U8_node), fp); + nodes = malloc(sizeof(U8_node) * (num_nodes)); + fread(nodes, 1, num_nodes * sizeof(U8_node), fp); - data_offset = be32((u8*) &header.data_offset); - rest_size = data_offset - sizeof(header) - (num_nodes+1)*sizeof(U8_node); + data_offset = be32((u8*) &header.data_offset); + rest_size = data_offset - sizeof(header) - (num_nodes+1)*sizeof(U8_node); - string_table = malloc(rest_size); - fread(string_table, 1, rest_size, fp); + string_table = malloc(rest_size); + fread(string_table, 1, rest_size, fp); current_offset = data_offset; - for (i = 0; i < num_nodes; i++) { - U8_node* node = &nodes[i]; - u16 type = be16((u8*)&node->type); - u16 name_offset = be16((u8*)&node->name_offset); - u32 my_data_offset = be32((u8*)&node->data_offset); - u32 size = be32((u8*)&node->size); - char* name = (char*) &string_table[name_offset]; - u8* file_data; + for (i = 0; i < num_nodes; i++) { + U8_node* node = &nodes[i]; + u16 type = be16((u8*)&node->type); + u16 name_offset = be16((u8*)&node->name_offset); + u32 my_data_offset = be32((u8*)&node->data_offset); + u32 size = be32((u8*)&node->size); + char* name = (char*) &string_table[name_offset]; + u8* file_data; - if (type == 0x0100) { - // Directory - mkdir(name, 0777); - chdir(name); - dir_stack[++dir_index] = size; - //printf("%*s%s/\n", dir_index, "", name); - } else { - // Normal file - u8 padding[32]; + if (type == 0x0100) { + // Directory + mkdir(name, 0777); + chdir(name); + dir_stack[++dir_index] = size; + //printf("%*s%s/\n", dir_index, "", name); + } else { + // Normal file + u8 padding[32]; - if (type != 0x0000) { - free(string_table); - return -2; - } + if (type != 0x0000) { + free(string_table); + return -2; + } - if (current_offset < my_data_offset) { - int diff = my_data_offset - current_offset; + if (current_offset < my_data_offset) { + int diff = my_data_offset - current_offset; - if (diff > 32) { - free(string_table); - return -3; - } - fread(padding, 1, diff, fp); - current_offset += diff; - } - - file_data = malloc(size); - fread(file_data, 1, size, fp); - //printf("%*s %s (%d bytes", dir_index, "", name, size); - int result; - result = write_imd5_lz77(file_data, size, name); - if (result < 0) { - free(string_table); - return result; - } - //printf(")\n"); - current_offset += size; + if (diff > 32) { + free(string_table); + return -3; } + fread(padding, 1, diff, fp); + current_offset += diff; + } - while (dir_stack[dir_index] == i+2 && dir_index > 0) { - chdir(".."); - dir_index--; - } - } - free(string_table); - return 0; -} - -static void do_imet_header(FILE *fp) { - imet_data_t header; - - fread(&header, 1, sizeof header, fp); - - write_file(&header, sizeof(header), "header.imet"); -} - -void do_U8_archivebanner(FILE *fp) { - U8_archive_header header; - U8_node root_node; - u32 tag; - u32 num_nodes; - U8_node* nodes; - u8* string_table; - size_t rest_size; - unsigned int i; - u32 data_offset; - u16 dir_stack[16]; - int dir_index = 0; - - fread(&header, 1, sizeof header, fp); - tag = be32((u8*) &header.tag); - if (tag != 0x55AA382D) { - //printf("No U8 tag"); - exit(0); + file_data = malloc(size); + fread(file_data, 1, size, fp); + //printf("%*s %s (%d bytes", dir_index, "", name, size); + int result; + result = write_imd5_lz77(file_data, size, name); + if(result < 0) + {free(string_table); + return result; + } + //printf(")\n"); + current_offset += size; } - fread(&root_node, 1, sizeof(root_node), fp); - num_nodes = be32((u8*) &root_node.size) - 1; - printf("Number of files: %d\n", num_nodes); - - nodes = malloc(sizeof(U8_node) * (num_nodes)); - fread(nodes, 1, num_nodes * sizeof(U8_node), fp); - - data_offset = be32((u8*) &header.data_offset); - rest_size = data_offset - sizeof(header) - (num_nodes+1)*sizeof(U8_node); - - string_table = malloc(rest_size); - fread(string_table, 1, rest_size, fp); - - for (i = 0; i < num_nodes; i++) { - U8_node* node = &nodes[i]; - u16 type = be16((u8*)&node->type); - u16 name_offset = be16((u8*)&node->name_offset); - u32 my_data_offset = be32((u8*)&node->data_offset); - u32 size = be32((u8*)&node->size); - char* name = (char*) &string_table[name_offset]; - u8* file_data; - - if (type == 0x0100) { - // Directory - mkdir(name, 0777); - chdir(name); - dir_stack[++dir_index] = size; - //printf("%*s%s/\n", dir_index, "", name); - } else { - // Normal file - - if (type != 0x0000) { - printf("Unknown type"); - exit(0); - } - - fseek(fp, my_data_offset, SEEK_SET); - file_data = malloc(size); - fread(file_data, 1, size, fp); - write_file(file_data, size, name); - free(file_data); - //printf("%*s %s (%d bytes)\n", dir_index, "", name, size); - } - - while (dir_stack[dir_index] == i+2 && dir_index > 0) { - chdir(".."); - dir_index--; - } + while (dir_stack[dir_index] == i+2 && dir_index > 0) { + chdir(".."); + dir_index--; } - free(string_table); + } + free(string_table); + return 0; } -int extractbnrfile(const char * filepath, const char * destpath) { +static void do_imet_header(FILE *fp) +{ + imet_data_t header; + + fread(&header, 1, sizeof header, fp); + + write_file(&header, sizeof(header), "header.imet"); +} + +void do_U8_archivebanner(FILE *fp) +{ + U8_archive_header header; + U8_node root_node; + u32 tag; + u32 num_nodes; + U8_node* nodes; + u8* string_table; + size_t rest_size; + unsigned int i; + u32 data_offset; + u16 dir_stack[16]; + int dir_index = 0; + + fread(&header, 1, sizeof header, fp); + tag = be32((u8*) &header.tag); + if (tag != 0x55AA382D) { + //printf("No U8 tag"); + exit(0); + } + + fread(&root_node, 1, sizeof(root_node), fp); + num_nodes = be32((u8*) &root_node.size) - 1; + printf("Number of files: %d\n", num_nodes); + + nodes = malloc(sizeof(U8_node) * (num_nodes)); + fread(nodes, 1, num_nodes * sizeof(U8_node), fp); + + data_offset = be32((u8*) &header.data_offset); + rest_size = data_offset - sizeof(header) - (num_nodes+1)*sizeof(U8_node); + + string_table = malloc(rest_size); + fread(string_table, 1, rest_size, fp); + + for (i = 0; i < num_nodes; i++) { + U8_node* node = &nodes[i]; + u16 type = be16((u8*)&node->type); + u16 name_offset = be16((u8*)&node->name_offset); + u32 my_data_offset = be32((u8*)&node->data_offset); + u32 size = be32((u8*)&node->size); + char* name = (char*) &string_table[name_offset]; + u8* file_data; + + if (type == 0x0100) { + // Directory + mkdir(name, 0777); + chdir(name); + dir_stack[++dir_index] = size; + //printf("%*s%s/\n", dir_index, "", name); + } else { + // Normal file + + if (type != 0x0000) { + printf("Unknown type"); + exit(0); + } + + fseek(fp, my_data_offset, SEEK_SET); + file_data = malloc(size); + fread(file_data, 1, size, fp); + write_file(file_data, size, name); + free(file_data); + //printf("%*s %s (%d bytes)\n", dir_index, "", name, size); + } + + while (dir_stack[dir_index] == i+2 && dir_index > 0) { + chdir(".."); + dir_index--; + } + } + free(string_table); +} + +int extractbnrfile(const char * filepath, const char * destpath) +{ int ret = -1; - FILE *fp = fopen(filepath, "rb"); - if (fp) { - subfoldercreate(destpath); - chdir(destpath); + FILE *fp = fopen(filepath, "rb"); + if(fp) + { + subfoldercreate(destpath); + chdir(destpath); - do_imet_header(fp); - ret = do_U8_archive(fp); + do_imet_header(fp); + ret = do_U8_archive(fp); - fclose(fp); - } - return ret; + fclose(fp); + } + return ret; } -int unpackBin(const char * filename,const char * outdir) { - FILE *fp = fopen(filename,"rb");; - if (fp) { - subfoldercreate(outdir); - chdir(outdir); +int unpackBin(const char * filename,const char * outdir) +{ + FILE *fp = fopen(filename,"rb");; + if(fp) + { + subfoldercreate(outdir); + chdir(outdir); - do_U8_archivebanner(fp); - fclose(fp); - return 1; - } - return 0; + do_U8_archivebanner(fp); + fclose(fp); + return 1; + } + return 0; } #define TMP_PATH(s) "BANNER:/dump"s //#define TMP_PATH(s) "SD:/dump"s -int unpackBanner(const u8 *gameid, int what, const char *outdir) { +int unpackBanner(const u8 *gameid, int what, const char *outdir) +{ - char path[256]; - if (!ramdiskMount("BANNER", NULL)) return -1; + char path[256]; + if(!ramdiskMount("BANNER", NULL)) return -1; - subfoldercreate(TMP_PATH("/")); - s32 ret = dump_banner(gameid, TMP_PATH("/opening.bnr")); - if (ret != 1) { - ret = -1; - goto error2; - } + subfoldercreate(TMP_PATH("/")); + s32 ret = dump_banner(gameid, TMP_PATH("/opening.bnr")); + if (ret != 1) + { + ret = -1; + goto error2; + } - ret = extractbnrfile(TMP_PATH("/opening.bnr"), TMP_PATH("/")); - if (ret != 0) { - ret = -1; - goto error2; - } + ret = extractbnrfile(TMP_PATH("/opening.bnr"), TMP_PATH("/")); + if (ret != 0) + { + ret = -1; + goto error2; + } - if (what & UNPACK_BANNER_BIN) { - snprintf(path, sizeof(path),"%sbanner/", outdir); - ret = unpackBin(TMP_PATH("/meta/banner.bin"), path); - if (ret != 1) { - ret = -1; - goto error2; - } - } - if (what & UNPACK_ICON_BIN) { - snprintf(path, sizeof(path),"%sicon/", outdir); - ret = unpackBin(TMP_PATH("/meta/icon.bin"), path); - if (ret != 1) { - ret = -1; - goto error2; - } - } - if (what & UNPACK_SOUND_BIN) { - snprintf(path, sizeof(path),"%ssound.bin", outdir); - FILE *fp = fopen(TMP_PATH("/meta/sound.bin"), "rb"); - if (fp) { - size_t size; - u8 *data; - fseek(fp, 0, SEEK_END); - size = ftell(fp); - if (!size) { - ret = -1; - goto error; - } - fseek(fp, 0, SEEK_SET); - data = (u8 *)malloc(size); - if (!data) { - ret = -1; - goto error; - } - if (fread(data, 1, size, fp) != size) { - ret = -1; - goto error; - } - ret = write_file(data, size, path); - } -error: - fclose(fp); - } - ramdiskUnmount("BANNER"); + if(what & UNPACK_BANNER_BIN) + { + snprintf(path, sizeof(path),"%sbanner/", outdir); + ret = unpackBin(TMP_PATH("/meta/banner.bin"), path); + if (ret != 1) + { + ret = -1; + goto error2; + } + } + if(what & UNPACK_ICON_BIN) + { + snprintf(path, sizeof(path),"%sicon/", outdir); + ret = unpackBin(TMP_PATH("/meta/icon.bin"), path); + if (ret != 1) + { + ret = -1; + goto error2; + } + } + if(what & UNPACK_SOUND_BIN) + { + snprintf(path, sizeof(path),"%ssound.bin", outdir); + FILE *fp = fopen(TMP_PATH("/meta/sound.bin"), "rb"); + if(fp) + { + size_t size; + u8 *data; + fseek(fp, 0, SEEK_END); + size = ftell(fp); + if(!size) + { + ret = -1; + goto error; + } + fseek(fp, 0, SEEK_SET); + data = (u8 *)malloc(size); + if(!data) + { + ret = -1; + goto error; + } + if(fread(data, 1, size, fp) != size) + { + ret = -1; + goto error; + } + ret = write_file(data, size, path); + } +error: fclose(fp); + } + ramdiskUnmount("BANNER"); error2: - if (ret < 0) - return ret; - return 1; + if(ret < 0) + return ret; + return 1; } diff --git a/source/banner/openingbnr.h b/source/banner/openingbnr.h index 0650250f..3142fba0 100644 --- a/source/banner/openingbnr.h +++ b/source/banner/openingbnr.h @@ -9,35 +9,36 @@ #define _OPENINGBNR_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - /*********************************************************** - * Error description: - * 0 Successfully extracted - * -1 No U8 tag - * -2 Unknown type - * -3 Archive inconsistency, too much padding - * -4 No IMD5 tag - * -5 MD5 mismatch - * -6 Size mismatch - * -7 Inconsistency in LZ77 encoding - ************************************************************/ +/*********************************************************** +* Error description: +* 0 Successfully extracted +* -1 No U8 tag +* -2 Unknown type +* -3 Archive inconsistency, too much padding +* -4 No IMD5 tag +* -5 MD5 mismatch +* -6 Size mismatch +* -7 Inconsistency in LZ77 encoding +************************************************************/ //! Extract opening.bnr from filepath to destpath //! Files extracted: banner.bin icon.bin and sound.bin - int extractbnrfile(const char * filepath, const char * destpath); - int unpackBin(const char * filename,const char * outdir); +int extractbnrfile(const char * filepath, const char * destpath); +int unpackBin(const char * filename,const char * outdir); #define UNPACK_BANNER_BIN 1 /* extract banner.bin to outdir/banner/ */ #define UNPACK_ICON_BIN 2 /* extract icon.bin to outdir/icon/ */ #define UNPACK_SOUND_BIN 4 /* copies sound.bin to outdir/sound.bin */ #define UNPACK_ALL (UNPACK_SOUND_BIN | UNPACK_ICON_BIN | UNPACK_BANNER_BIN) - int unpackBanner(const u8 * gameid, int what, const char *outdir); +int unpackBanner(const u8 * gameid, int what, const char *outdir); //! Extract the lz77 compressed banner, icon and sound .bin - u8* decompress_lz77(u8 *data, size_t data_size, size_t* decompressed_size); +u8* decompress_lz77(u8 *data, size_t data_size, size_t* decompressed_size); - u16 be16(const u8 *p); - u32 be32(const u8 *p); +u16 be16(const u8 *p); +u32 be32(const u8 *p); #ifdef __cplusplus } diff --git a/source/bannersound.cpp b/source/bannersound.cpp index fd693cf3..3abe5f0f 100644 --- a/source/bannersound.cpp +++ b/source/bannersound.cpp @@ -11,177 +11,199 @@ #include "bannersound.h" -struct IMD5Header { - u32 fcc; - u32 filesize; - u8 zeroes[8]; - u8 crypto[16]; +struct IMD5Header +{ + u32 fcc; + u32 filesize; + u8 zeroes[8]; + u8 crypto[16]; } __attribute__((packed)); -struct IMETHeader { - u8 zeroes[64]; - u32 fcc; - u8 unk[8]; - u32 iconSize; - u32 bannerSize; - u32 soundSize; - u32 flag1; - u8 names[7][84]; - u8 zeroes_2[0x348]; - u8 crypto[16]; +struct IMETHeader +{ + u8 zeroes[64]; + u32 fcc; + u8 unk[8]; + u32 iconSize; + u32 bannerSize; + u32 soundSize; + u32 flag1; + u8 names[7][84]; + u8 zeroes_2[0x348]; + u8 crypto[16]; } __attribute__((packed)); -struct U8Header { - u32 fcc; - u32 rootNodeOffset; - u32 headerSize; - u32 dataOffset; - u8 zeroes[16]; +struct U8Header +{ + u32 fcc; + u32 rootNodeOffset; + u32 headerSize; + u32 dataOffset; + u8 zeroes[16]; } __attribute__((packed)); -struct U8Entry { - struct { -u32 fileType : - 8; -u32 nameOffset : - 24; - }; - u32 fileOffset; - union { - u32 fileLength; - u32 numEntries; - }; +struct U8Entry +{ + struct + { + u32 fileType : 8; + u32 nameOffset : 24; + }; + u32 fileOffset; + union + { + u32 fileLength; + u32 numEntries; + }; } __attribute__((packed)); -struct LZ77Info { -u16 length : - 4; -u16 offset : - 12; +struct LZ77Info +{ + u16 length : 4; + u16 offset : 12; } __attribute__((packed)); -static char *u8Filename(const U8Entry *fst, int i) { - return (char *)(fst + fst[0].numEntries) + fst[i].nameOffset; +static char *u8Filename(const U8Entry *fst, int i) +{ + return (char *)(fst + fst[0].numEntries) + fst[i].nameOffset; } -inline u32 le32(u32 i) { - return ((i & 0xFF) << 24) | ((i & 0xFF00) << 8) | ((i & 0xFF0000) >> 8) | ((i & 0xFF000000) >> 24); +inline u32 le32(u32 i) +{ + return ((i & 0xFF) << 24) | ((i & 0xFF00) << 8) | ((i & 0xFF0000) >> 8) | ((i & 0xFF000000) >> 24); } -inline u16 le16(u16 i) { - return ((i & 0xFF) << 8) | ((i & 0xFF00) >> 8); +inline u16 le16(u16 i) +{ + return ((i & 0xFF) << 8) | ((i & 0xFF00) >> 8); } -static u8 *uncompressLZ77(const u8 *inBuf, u32 inLength, u32 &size) { - u8 *buffer = NULL; - if (inLength <= 0x8 || *((const u32 *)inBuf) != 0x4C5A3737 /*"LZ77"*/ || inBuf[4] != 0x10) - return NULL; - u32 uncSize = le32(((const u32 *)inBuf)[1] << 8); +static u8 *uncompressLZ77(const u8 *inBuf, u32 inLength, u32 &size) +{ + u8 *buffer = NULL; + if (inLength <= 0x8 || *((const u32 *)inBuf) != 0x4C5A3737 /*"LZ77"*/ || inBuf[4] != 0x10) + return NULL; + u32 uncSize = le32(((const u32 *)inBuf)[1] << 8); - const u8 *inBufEnd = inBuf + inLength; - inBuf += 8; - buffer = new(std::nothrow) u8[uncSize]; - if (!buffer) - return buffer; + const u8 *inBufEnd = inBuf + inLength; + inBuf += 8; + buffer = new(std::nothrow) u8[uncSize]; + if (!buffer) + return buffer; - u8 *bufCur = buffer; - u8 *bufEnd = buffer + uncSize; + u8 *bufCur = buffer; + u8 *bufEnd = buffer + uncSize; - while (bufCur < bufEnd && inBuf < inBufEnd) { - u8 flags = *inBuf; - ++inBuf; - for (int i = 0; i < 8 && bufCur < bufEnd && inBuf < inBufEnd; ++i) { - if ((flags & 0x80) != 0) { - const LZ77Info &info = *(const LZ77Info *)inBuf; - inBuf += sizeof (LZ77Info); - int length = info.length + 3; - if (bufCur - info.offset - 1 < buffer || bufCur + length > bufEnd) - return buffer; - memcpy(bufCur, bufCur - info.offset - 1, length); - bufCur += length; - } else { - *bufCur = *inBuf; - ++inBuf; - ++bufCur; - } - flags <<= 1; - } - } - size = uncSize; - return buffer; + while (bufCur < bufEnd && inBuf < inBufEnd) + { + u8 flags = *inBuf; + ++inBuf; + for (int i = 0; i < 8 && bufCur < bufEnd && inBuf < inBufEnd; ++i) + { + if ((flags & 0x80) != 0) + { + const LZ77Info &info = *(const LZ77Info *)inBuf; + inBuf += sizeof (LZ77Info); + int length = info.length + 3; + if (bufCur - info.offset - 1 < buffer || bufCur + length > bufEnd) + return buffer; + memcpy(bufCur, bufCur - info.offset - 1, length); + bufCur += length; + } + else + { + *bufCur = *inBuf; + ++inBuf; + ++bufCur; + } + flags <<= 1; + } + } + size = uncSize; + return buffer; } -const u8 *LoadBannerSound(const u8 *discid, u32 *size) { - if (!discid) +const u8 *LoadBannerSound(const u8 *discid, u32 *size) +{ + if(!discid) return NULL; - Disc_SetUSB(NULL); - wbfs_disc_t *disc = WBFS_OpenDisc((u8 *) discid); - if (!disc) { - // WindowPrompt(tr("Can't find disc"), 0, tr("OK")); + Disc_SetUSB(NULL); + wbfs_disc_t *disc = WBFS_OpenDisc((u8 *) discid); + if(!disc) + { + // WindowPrompt(tr("Can't find disc"), 0, tr("OK")); return NULL; - } - wiidisc_t *wdisc = wd_open_disc((int (*)(void *, u32, u32, void *))wbfs_disc_read, disc); - if (!wdisc) { - //WindowPrompt(tr("Could not open Disc"), 0, tr("OK")); + } + wiidisc_t *wdisc = wd_open_disc((int (*)(void *, u32, u32, void *))wbfs_disc_read, disc); + if(!wdisc) + { + //WindowPrompt(tr("Could not open Disc"), 0, tr("OK")); return NULL; - } - u8 * opening_bnr = wd_extract_file(wdisc, ALL_PARTITIONS, (char *) "opening.bnr"); - if (!opening_bnr) { - //WindowPrompt(tr("ERROR"), tr("Failed to extract opening.bnr"), tr("OK")); + } + u8 * opening_bnr = wd_extract_file(wdisc, ALL_PARTITIONS, (char *) "opening.bnr"); + if(!opening_bnr) + { + //WindowPrompt(tr("ERROR"), tr("Failed to extract opening.bnr"), tr("OK")); return NULL; - } + } - wd_close_disc(wdisc); - WBFS_CloseDisc(disc); + wd_close_disc(wdisc); + WBFS_CloseDisc(disc); - const U8Entry *fst; + const U8Entry *fst; - const IMETHeader *imetHdr = (IMETHeader *)opening_bnr; - if ( imetHdr->fcc != 0x494D4554 /*"IMET"*/ ) { - // WindowPrompt(tr("IMET Header wrong."), 0, tr("OK")); - free(opening_bnr); + const IMETHeader *imetHdr = (IMETHeader *)opening_bnr; + if ( imetHdr->fcc != 0x494D4554 /*"IMET"*/ ) + { + // WindowPrompt(tr("IMET Header wrong."), 0, tr("OK")); + free(opening_bnr); return NULL; - } - const U8Header *bnrArcHdr = (U8Header *)(imetHdr + 1); + } + const U8Header *bnrArcHdr = (U8Header *)(imetHdr + 1); - fst = (const U8Entry *)( ((const u8 *)bnrArcHdr) + bnrArcHdr->rootNodeOffset); - u32 i; - for (i = 1; i < fst[0].numEntries; ++i) - if (fst[i].fileType == 0 && strcasecmp(u8Filename(fst, i), "sound.bin") == 0) - break; - if (i >= fst[0].numEntries) { - /* Not all games have a sound.bin and this message is annoying **/ - //WindowPrompt(tr("sound.bin not found."), 0, tr("OK")); - free(opening_bnr); + fst = (const U8Entry *)( ((const u8 *)bnrArcHdr) + bnrArcHdr->rootNodeOffset); + u32 i; + for (i = 1; i < fst[0].numEntries; ++i) + if (fst[i].fileType == 0 && strcasecmp(u8Filename(fst, i), "sound.bin") == 0) + break; + if (i >= fst[0].numEntries) + { + /* Not all games have a sound.bin and this message is annoying **/ + //WindowPrompt(tr("sound.bin not found."), 0, tr("OK")); + free(opening_bnr); return NULL; - } - const u8 *sound_bin = ((const u8 *)bnrArcHdr) + fst[i].fileOffset; - if ( ((IMD5Header *)sound_bin)->fcc != 0x494D4435 /*"IMD5"*/ ) { - // WindowPrompt(tr("IMD5 Header not right."), 0, tr("OK")); - free(opening_bnr); + } + const u8 *sound_bin = ((const u8 *)bnrArcHdr) + fst[i].fileOffset; + if ( ((IMD5Header *)sound_bin)->fcc != 0x494D4435 /*"IMD5"*/ ) + { + // WindowPrompt(tr("IMD5 Header not right."), 0, tr("OK")); + free(opening_bnr); return NULL; - } - const u8 *soundChunk = sound_bin + sizeof (IMD5Header);; - u32 soundChunkSize = fst[i].fileLength - sizeof (IMD5Header); + } + const u8 *soundChunk = sound_bin + sizeof (IMD5Header);; + u32 soundChunkSize = fst[i].fileLength - sizeof (IMD5Header); - if ( *((u32*)soundChunk) == 0x4C5A3737 /*"LZ77"*/ ) { - u32 uncSize = NULL; - u8 * uncompressed_data = uncompressLZ77(soundChunk, soundChunkSize, uncSize); - if (!uncompressed_data) { - // WindowPrompt(tr("Can't decompress LZ77"), 0, tr("OK")); - free(opening_bnr); - return NULL; - } - if (size) *size=uncSize; - free(opening_bnr); - return uncompressed_data; - } - u8 *out = new(std::nothrow) u8[soundChunkSize]; - if (out) { - memcpy(out, soundChunk, soundChunkSize); - if (size) *size=soundChunkSize; - } - free(opening_bnr); - return out; + if ( *((u32*)soundChunk) == 0x4C5A3737 /*"LZ77"*/ ) + { + u32 uncSize = NULL; + u8 * uncompressed_data = uncompressLZ77(soundChunk, soundChunkSize, uncSize); + if (!uncompressed_data) + { + // WindowPrompt(tr("Can't decompress LZ77"), 0, tr("OK")); + free(opening_bnr); + return NULL; + } + if(size) *size=uncSize; + free(opening_bnr); + return uncompressed_data; + } + u8 *out = new(std::nothrow) u8[soundChunkSize]; + if(out) + { + memcpy(out, soundChunk, soundChunkSize); + if(size) *size=soundChunkSize; + } + free(opening_bnr); + return out; } diff --git a/source/cheats/cheatmenu.cpp b/source/cheats/cheatmenu.cpp index b274c477..3e751079 100644 --- a/source/cheats/cheatmenu.cpp +++ b/source/cheats/cheatmenu.cpp @@ -24,140 +24,142 @@ extern GuiWindow * mainWindow; * CheatMenu ***************************************************************************/ int CheatMenu(const char * gameID) { - int choice = 0; - bool exit = false; - int ret = 1; + int choice = 0; + bool exit = false; + int ret = 1; - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); - GuiImage settingsbackground(&settingsbg); + char imgPath[100]; + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); + GuiImage settingsbackground(&settingsbg); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + GuiTrigger trigA; + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); - backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage backBtnImg(&btnOutline); - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -140, 400, &trigA, NULL, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); + GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); + GuiImage backBtnImg(&btnOutline); + GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -140, 400, &trigA, NULL, btnClick2,1); + backBtn.SetLabel(&backBtnTxt); + backBtn.SetTrigger(&trigB); - GuiText createBtnTxt(tr("Create") , 22, THEME.prompttext); - createBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage createBtnImg(&btnOutline); - GuiButton createBtn(&createBtnImg,&createBtnImg, 2, 3, 160, 400, &trigA, NULL, btnClick2,1); - createBtn.SetLabel(&createBtnTxt); + GuiText createBtnTxt(tr("Create") , 22, THEME.prompttext); + createBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); + GuiImage createBtnImg(&btnOutline); + GuiButton createBtn(&createBtnImg,&createBtnImg, 2, 3, 160, 400, &trigA, NULL, btnClick2,1); + createBtn.SetLabel(&createBtnTxt); - char txtfilename[55]; - snprintf(txtfilename,sizeof(txtfilename),"%s%s.txt",Settings.TxtCheatcodespath,gameID); + char txtfilename[55]; + snprintf(txtfilename,sizeof(txtfilename),"%s%s.txt",Settings.TxtCheatcodespath,gameID); - GCTCheats c; - int check = c.openTxtfile(txtfilename); + GCTCheats c; + int check = c.openTxtfile(txtfilename); - int download =0; + int download =0; - switch (check) { - case -1: - WindowPrompt(tr("Error"),tr("Cheatfile is blank"),tr("OK")); - break; - case 0: - download = WindowPrompt(tr("Error"),tr("No Cheatfile found"),tr("Download Now"),tr("Cancel")); - if (download==1) { - download = CodeDownload(gameID); - if (download < 0 || c.openTxtfile(txtfilename) != 1) - break; - } else - break; - case 1: - int cntcheats = c.getCnt(); - customOptionList cheatslst(cntcheats); - GuiCustomOptionBrowser chtBrowser(400, 280, &cheatslst, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 1, 90); - chtBrowser.SetPosition(0, 90); - chtBrowser.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - chtBrowser.SetClickable(true); + switch (check) { + case -1: + WindowPrompt(tr("Error"),tr("Cheatfile is blank"),tr("OK")); + break; + case 0: + download = WindowPrompt(tr("Error"),tr("No Cheatfile found"),tr("Download Now"),tr("Cancel")); + if (download==1) + { + download = CodeDownload(gameID); + if(download < 0 || c.openTxtfile(txtfilename) != 1) + break; + } + else + break; + case 1: + int cntcheats = c.getCnt(); + customOptionList cheatslst(cntcheats); + GuiCustomOptionBrowser chtBrowser(400, 280, &cheatslst, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 1, 90); + chtBrowser.SetPosition(0, 90); + chtBrowser.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + chtBrowser.SetClickable(true); - GuiText titleTxt(c.getGameName().c_str(), 28, (GXColor) {0, 0, 0, 255}); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetMaxWidth(350, GuiText::SCROLL); - titleTxt.SetPosition(12,40); + GuiText titleTxt(c.getGameName().c_str(), 28, (GXColor) {0, 0, 0, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetMaxWidth(350, GuiText::SCROLL); + titleTxt.SetPosition(12,40); - for (int i = 0; i <= cntcheats; i++) { + for (int i = 0; i <= cntcheats; i++) { cheatslst.SetValue(i, "%s",c.getCheatName(i).c_str()); cheatslst.SetName(i, "OFF"); } - HaltGui(); - GuiWindow w(screenwidth, screenheight); - w.Append(&settingsbackground); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&createBtn); - w.Append(&chtBrowser); - mainWindow->SetState(STATE_DISABLED); - mainWindow->ChangeFocus(&w); - mainWindow->Append(&w); - ResumeGui(); + HaltGui(); + GuiWindow w(screenwidth, screenheight); + w.Append(&settingsbackground); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&createBtn); + w.Append(&chtBrowser); + mainWindow->SetState(STATE_DISABLED); + mainWindow->ChangeFocus(&w); + mainWindow->Append(&w); + ResumeGui(); - while (!exit) { - VIDEO_WaitVSync (); + while (!exit) { + VIDEO_WaitVSync (); - ret = chtBrowser.GetClickedOption(); - if (ret != -1) { - const char *strCheck = cheatslst.GetName(ret); - if (strncmp(strCheck,"ON",2) == 0) { - cheatslst.SetName(ret,"%s","OFF"); - } else if (strncmp(strCheck,"OFF",3) == 0) { - cheatslst.SetName(ret,"%s","ON"); - } - } + ret = chtBrowser.GetClickedOption(); + if (ret != -1) { + const char *strCheck = cheatslst.GetName(ret); + if (strncmp(strCheck,"ON",2) == 0) { + cheatslst.SetName(ret,"%s","OFF"); + } else if (strncmp(strCheck,"OFF",3) == 0) { + cheatslst.SetName(ret,"%s","ON"); + } + } - if (createBtn.GetState() == STATE_CLICKED) { - createBtn.ResetState(); - if (cntcheats > 0) { - int selectednrs[30]; - int x = 0; - for (int i = 0; i <= cntcheats; i++) { - const char *strCheck = cheatslst.GetName(i); - if (strncmp(strCheck,"ON",2) == 0) { - selectednrs[x] = i; - x++; - } - } - if (x == 0) { - WindowPrompt(tr("Error"),tr("No cheats were selected"),tr("OK")); - } else { - subfoldercreate(Settings.Cheatcodespath); - string chtpath = Settings.Cheatcodespath; - string gctfname = chtpath + c.getGameID() + ".gct"; - c.createGCT(selectednrs,x,gctfname.c_str()); - WindowPrompt(tr("GCT File created"),NULL,tr("OK")); - exit = true; - break; - } - } else WindowPrompt(tr("Error"),tr("Could not create GCT file"),tr("OK")); - } + if (createBtn.GetState() == STATE_CLICKED) { + createBtn.ResetState(); + if (cntcheats > 0) { + int selectednrs[30]; + int x = 0; + for (int i = 0; i <= cntcheats; i++) { + const char *strCheck = cheatslst.GetName(i); + if (strncmp(strCheck,"ON",2) == 0) { + selectednrs[x] = i; + x++; + } + } + if (x == 0) { + WindowPrompt(tr("Error"),tr("No cheats were selected"),tr("OK")); + } else { + subfoldercreate(Settings.Cheatcodespath); + string chtpath = Settings.Cheatcodespath; + string gctfname = chtpath + c.getGameID() + ".gct"; + c.createGCT(selectednrs,x,gctfname.c_str()); + WindowPrompt(tr("GCT File created"),NULL,tr("OK")); + exit = true; + break; + } + } else WindowPrompt(tr("Error"),tr("Could not create GCT file"),tr("OK")); + } - if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } - } - HaltGui(); - mainWindow->SetState(STATE_DEFAULT); - mainWindow->Remove(&w); - ResumeGui(); - break; - } + if (backBtn.GetState() == STATE_CLICKED) { + backBtn.ResetState(); + exit = true; + break; + } + } + HaltGui(); + mainWindow->SetState(STATE_DEFAULT); + mainWindow->Remove(&w); + ResumeGui(); + break; + } - return choice; + return choice; } diff --git a/source/cheats/gct.cpp b/source/cheats/gct.cpp index 41a74f13..064cbf4e 100644 --- a/source/cheats/gct.cpp +++ b/source/cheats/gct.cpp @@ -63,8 +63,8 @@ string GCTCheats::getCheatComment(int nr) { int GCTCheats::createGCT(int nr,const char * filename) { - if (nr == 0) - return 0; + if (nr == 0) + return 0; ofstream filestr; filestr.open(filename); @@ -132,8 +132,8 @@ int GCTCheats::createGCT(const char * chtbuffer,const char * filename) { int GCTCheats::createGCT(int nr[],int cnt,const char * filename) { - if (cnt == 0) - return 0; + if (cnt == 0) + return 0; ofstream filestr; filestr.open(filename); @@ -185,54 +185,54 @@ int GCTCheats::openTxtfile(const char * filename) { filestr.seekg(0,ios_base::beg); getline(filestr,sGameID); - if (sGameID[sGameID.length() - 1] == '\r') - sGameID.erase(sGameID.length() - 1); - + if (sGameID[sGameID.length() - 1] == '\r') + sGameID.erase(sGameID.length() - 1); + getline(filestr,sGameTitle); - if (sGameTitle[sGameTitle.length() - 1] == '\r') - sGameTitle.erase(sGameTitle.length() - 1); - + if (sGameTitle[sGameTitle.length() - 1] == '\r') + sGameTitle.erase(sGameTitle.length() - 1); + getline(filestr,sCheatName[i]); // skip first line if file uses CRLF - if (!sGameTitle[sGameTitle.length() - 1] == '\r') - filestr.seekg(0,ios_base::beg); + if (!sGameTitle[sGameTitle.length() - 1] == '\r') + filestr.seekg(0,ios_base::beg); while (!filestr.eof()) { getline(filestr,sCheatName[i]); // '\n' delimiter by default - if (sCheatName[i][sCheatName[i].length() - 1] == '\r') - sCheatName[i].erase(sCheatName[i].length() - 1); + if (sCheatName[i][sCheatName[i].length() - 1] == '\r') + sCheatName[i].erase(sCheatName[i].length() - 1); string cheatdata; bool emptyline = false; do { - getline(filestr,str); - if (str[str.length() - 1] == '\r') - str.erase(str.length() - 1); - + getline(filestr,str); + if (str[str.length() - 1] == '\r') + str.erase(str.length() - 1); + if (str == "" || str[0] == '\r' || str[0] == '\n') { emptyline = true; break; } if (IsCode(str)) { - // remove any garbage (comment) after code - while (str.size() > 17) { - str.erase(str.length() - 1); - } - cheatdata.append(str); + // remove any garbage (comment) after code + while (str.size() > 17) { + str.erase(str.length() - 1); + } + cheatdata.append(str); size_t found=cheatdata.find(' '); cheatdata.replace(found,1,""); - } else { + } else { //printf("%i",str.size()); sCheatComment[i] = str; } - if (filestr.eof()) break; - + if (filestr.eof()) break; + } while (!emptyline); sCheats[i] = cheatdata; - i++; - if (i == MAXCHEATS) break; + i++; + if (i == MAXCHEATS) break; } iCntCheats = i; filestr.close(); @@ -240,15 +240,15 @@ int GCTCheats::openTxtfile(const char * filename) { } bool GCTCheats::IsCode(const std::string& str) { - if (str[8] == ' ' && str.size() >= 17) { - // accept strings longer than 17 in case there is a comment on the same line as the code - char part1[9]; - char part2[9]; - snprintf(part1,sizeof(part1),"%c%c%c%c%c%c%c%c",str[0],str[1],str[2],str[3],str[4],str[5],str[6],str[7]); - snprintf(part1,sizeof(part2),"%c%c%c%c%c%c%c%c",str[9],str[10],str[11],str[12],str[13],str[14],str[15],str[16]); - if ((strtok(part1,"0123456789ABCDEFabcdef") == NULL) && (strtok(part2,"0123456789ABCDEFabcdef") == NULL)) { - return true; - } - } - return false; + if (str[8] == ' ' && str.size() >= 17) { + // accept strings longer than 17 in case there is a comment on the same line as the code + char part1[9]; + char part2[9]; + snprintf(part1,sizeof(part1),"%c%c%c%c%c%c%c%c",str[0],str[1],str[2],str[3],str[4],str[5],str[6],str[7]); + snprintf(part1,sizeof(part2),"%c%c%c%c%c%c%c%c",str[9],str[10],str[11],str[12],str[13],str[14],str[15],str[16]); + if ((strtok(part1,"0123456789ABCDEFabcdef") == NULL) && (strtok(part2,"0123456789ABCDEFabcdef") == NULL)) { + return true; + } + } + return false; } diff --git a/source/cheats/gct.h b/source/cheats/gct.h index 559fd432..3dca78ae 100644 --- a/source/cheats/gct.h +++ b/source/cheats/gct.h @@ -1,7 +1,7 @@ /* * gct.h * Class to handle Ocarina TXT Cheatfiles - * + * */ #ifndef _GCT_H @@ -66,9 +66,9 @@ public: //!Gets Cheat Comment //!\return Cheat Comment string getCheatComment(int nr); - //!Check if string is a code + //!Check if string is a code //!\return true/false - bool IsCode(const std::string& s); + bool IsCode(const std::string& s); }; #endif /* _GCT_H */ diff --git a/source/data1 b/source/data1 index 3a03c7c1..0a7d2210 100644 Binary files a/source/data1 and b/source/data1 differ diff --git a/source/fatmounter.c b/source/fatmounter.c index a3986908..a9fb0754 100644 --- a/source/fatmounter.c +++ b/source/fatmounter.c @@ -43,34 +43,34 @@ int fs_ntfs_mount = 0; sec_t fs_ntfs_sec = 0; int USBDevice_Init() { - gprintf("\nUSBDevice_Init()"); + gprintf("\nUSBDevice_Init()"); - //closing all open Files write back the cache and then shutdown em! + //closing all open Files write back the cache and then shutdown em! fatUnmount("USB:/"); //right now mounts first FAT-partition - //try first mount with cIOS + //try first mount with cIOS if (!fatMount("USB", &__io_wiiums, 0, CACHE, SECTORS)) { - //try now mount with libogc - if (!fatMount("USB", &__io_usbstorage, 0, CACHE, SECTORS)) { - gprintf(":-1"); - return -1; - } - } - - fat_usb_mount = 1; - fat_usb_sec = _FAT_startSector; - gprintf(":0"); - return 0; + //try now mount with libogc + if (!fatMount("USB", &__io_usbstorage, 0, CACHE, SECTORS)) { + gprintf(":-1"); + return -1; + } + } + + fat_usb_mount = 1; + fat_usb_sec = _FAT_startSector; + gprintf(":0"); + return 0; } void USBDevice_deInit() { - gprintf("\nUSBDevice_deInit()"); + gprintf("\nUSBDevice_deInit()"); //closing all open Files write back the cache and then shutdown em! fatUnmount("USB:/"); - fat_usb_mount = 0; - fat_usb_sec = 0; + fat_usb_mount = 0; + fat_usb_sec = 0; } int WBFSDevice_Init(u32 sector) { @@ -78,29 +78,29 @@ int WBFSDevice_Init(u32 sector) { fatUnmount("WBFS:/"); //right now mounts first FAT-partition - //try first mount with cIOS - if (!fatMount("WBFS", &__io_wiiums, 0, CACHE, SECTORS)) { - //try now mount with libogc - if (!fatMount("WBFS", &__io_usbstorage, 0, CACHE, SECTORS)) { - return -1; - } - } + //try first mount with cIOS + if (!fatMount("WBFS", &__io_wiiums, 0, CACHE, SECTORS)) { + //try now mount with libogc + if (!fatMount("WBFS", &__io_usbstorage, 0, CACHE, SECTORS)) { + return -1; + } + } - fat_wbfs_mount = 1; - fat_wbfs_sec = _FAT_startSector; - if (sector && fat_wbfs_sec != sector) { - // This is an error situation...actually, but is ignored in Config loader also - // Should ask Oggzee about it... - } - return 0; + fat_wbfs_mount = 1; + fat_wbfs_sec = _FAT_startSector; + if (sector && fat_wbfs_sec != sector) { + // This is an error situation...actually, but is ignored in Config loader also + // Should ask Oggzee about it... + } + return 0; } void WBFSDevice_deInit() { //closing all open Files write back the cache and then shutdown em! fatUnmount("WBFS:/"); - fat_wbfs_mount = 0; - fat_wbfs_sec = 0; + fat_wbfs_mount = 0; + fat_wbfs_sec = 0; } int isInserted(const char *path) { @@ -111,118 +111,128 @@ int isInserted(const char *path) { } int SDCard_Init() { - gprintf("\nSDCard_Init()"); +gprintf("\nSDCard_Init()"); //closing all open Files write back the cache and then shutdown em! fatUnmount("SD:/"); //right now mounts first FAT-partition - if (fatMount("SD", &__io_wiisd, 0, CACHE, SECTORS)) { - fat_sd_mount = MOUNT_SD; - fat_sd_sec = _FAT_startSector; - gprintf(":1"); - return 1; - } else if (fatMount("SD", &__io_sdhc, 0, CACHE, SDHC_SECTOR_SIZE)) { - fat_sd_mount = MOUNT_SDHC; - fat_sd_sec = _FAT_startSector; - gprintf(":1"); - return 1; - } - gprintf(":-1"); + if (fatMount("SD", &__io_wiisd, 0, CACHE, SECTORS)) { + fat_sd_mount = MOUNT_SD; + fat_sd_sec = _FAT_startSector; + gprintf(":1"); + return 1; + } + else if (fatMount("SD", &__io_sdhc, 0, CACHE, SDHC_SECTOR_SIZE)) { + fat_sd_mount = MOUNT_SDHC; + fat_sd_sec = _FAT_startSector; + gprintf(":1"); + return 1; + } + gprintf(":-1"); return -1; } void SDCard_deInit() { - gprintf("\nSDCard_deInit()"); +gprintf("\nSDCard_deInit()"); //closing all open Files write back the cache and then shutdown em! fatUnmount("SD:/"); - fat_sd_mount = MOUNT_NONE; - fat_sd_sec = 0; + fat_sd_mount = MOUNT_NONE; + fat_sd_sec = 0; } void ntfsInit(); -s32 MountNTFS(u32 sector) { - s32 ret; +s32 MountNTFS(u32 sector) +{ + s32 ret; - if (fs_ntfs_mount) return 0; - //printf("mounting NTFS\n"); - //Wpad_WaitButtons(); - _FAT_mem_init(); + if (fs_ntfs_mount) return 0; + //printf("mounting NTFS\n"); + //Wpad_WaitButtons(); + _FAT_mem_init(); - ntfsInit(); // Call ntfs init here, to prevent locale resets + ntfsInit(); // Call ntfs init here, to prevent locale resets + + // ntfsInit resets locale settings + // which breaks unicode in console + // so we change it back to C-UTF-8 + setlocale(LC_CTYPE, "C-UTF-8"); + setlocale(LC_MESSAGES, "C-UTF-8"); - // ntfsInit resets locale settings - // which breaks unicode in console - // so we change it back to C-UTF-8 - setlocale(LC_CTYPE, "C-UTF-8"); - setlocale(LC_MESSAGES, "C-UTF-8"); + if (wbfsDev == WBFS_DEVICE_USB) { + /* Initialize WBFS interface */ + if (!__io_wiiums.startup()) { + ret = __io_usbstorage.startup(); + if (!ret) { + return -1; + } + } + /* Mount device */ + if (!ntfsMount("NTFS", &__io_wiiums, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER)) { + ret = ntfsMount("NTFS", &__io_usbstorage, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); + if (!ret) { + return -2; + } + } + } else if (wbfsDev == WBFS_DEVICE_SDHC) { + if (sdhc_mode_sd == 0) { + ret = ntfsMount("NTFS", &__io_sdhc, 0, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); + } else { + ret = ntfsMount("NTFS", &__io_sdhc, 0, CACHE, SECTORS_SD, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); + } + if (!ret) { + return -5; + } + } - if (wbfsDev == WBFS_DEVICE_USB) { - /* Initialize WBFS interface */ - if (!__io_wiiums.startup()) { - ret = __io_usbstorage.startup(); - if (!ret) { - return -1; - } - } - /* Mount device */ - if (!ntfsMount("NTFS", &__io_wiiums, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER)) { - ret = ntfsMount("NTFS", &__io_usbstorage, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); - if (!ret) { - return -2; - } - } - } else if (wbfsDev == WBFS_DEVICE_SDHC) { - if (sdhc_mode_sd == 0) { - ret = ntfsMount("NTFS", &__io_sdhc, 0, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); - } else { - ret = ntfsMount("NTFS", &__io_sdhc, 0, CACHE, SECTORS_SD, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); - } - if (!ret) { - return -5; - } - } - - fs_ntfs_mount = 1; - fs_ntfs_sec = sector; //_FAT_startSector; - - return 0; + fs_ntfs_mount = 1; + fs_ntfs_sec = sector; //_FAT_startSector; + + return 0; } -s32 UnmountNTFS(void) { - /* Unmount device */ - ntfsUnmount("NTFS:/", true); +s32 UnmountNTFS(void) +{ + /* Unmount device */ + ntfsUnmount("NTFS:/", true); - fs_ntfs_mount = 0; - fs_ntfs_sec = 0; + fs_ntfs_mount = 0; + fs_ntfs_sec = 0; - return 0; + return 0; } -void _FAT_mem_init() { +void _FAT_mem_init() +{ } -void* _FAT_mem_allocate(size_t size) { - return malloc(size); +void* _FAT_mem_allocate(size_t size) +{ + return malloc(size); } -void* _FAT_mem_align(size_t size) { - return memalign(32, size); +void* _FAT_mem_align(size_t size) +{ + return memalign(32, size); } -void _FAT_mem_free(void *mem) { - free(mem); +void _FAT_mem_free(void *mem) +{ + free(mem); } -void* ntfs_alloc (size_t size) { - return _FAT_mem_allocate(size); +void* ntfs_alloc (size_t size) +{ + return _FAT_mem_allocate(size); } -void* ntfs_align (size_t size) { - return _FAT_mem_align(size); +void* ntfs_align (size_t size) +{ + return _FAT_mem_align(size); } -void ntfs_free (void* mem) { - _FAT_mem_free(mem); +void ntfs_free (void* mem) +{ + _FAT_mem_free(mem); } diff --git a/source/fatmounter.h b/source/fatmounter.h index 67f849b2..e9ac30ba 100644 --- a/source/fatmounter.h +++ b/source/fatmounter.h @@ -5,12 +5,12 @@ extern "C" { #endif - extern int fat_sd_mount; - extern sec_t fat_sd_sec; - extern int fat_usb_mount; - extern sec_t fat_usb_sec; - extern int fat_wbfs_mount; - extern sec_t fat_wbfs_sec; + extern int fat_sd_mount; + extern sec_t fat_sd_sec; + extern int fat_usb_mount; + extern sec_t fat_usb_sec; + extern int fat_wbfs_mount; + extern sec_t fat_wbfs_sec; int USBDevice_Init(); void USBDevice_deInit(); @@ -19,16 +19,16 @@ extern "C" { int isInserted(const char *path); int SDCard_Init(); void SDCard_deInit(); + + s32 MountNTFS(u32 sector); + s32 UnmountNTFS(void); - s32 MountNTFS(u32 sector); - s32 UnmountNTFS(void); - - extern int fat_usb_mount; - extern sec_t fat_usb_sec; - extern int fat_wbfs_mount; - extern sec_t fat_wbfs_sec; - extern int fs_ntfs_mount; - extern sec_t fs_ntfs_sec; + extern int fat_usb_mount; + extern sec_t fat_usb_sec; + extern int fat_wbfs_mount; + extern sec_t fat_wbfs_sec; + extern int fs_ntfs_mount; + extern sec_t fs_ntfs_sec; #ifdef __cplusplus } diff --git a/source/fonts/clock.ttf b/source/fonts/clock.ttf index eaf949a5..5a252b2b 100644 Binary files a/source/fonts/clock.ttf and b/source/fonts/clock.ttf differ diff --git a/source/fonts/font.ttf b/source/fonts/font.ttf index c79e8545..01ce5816 100644 Binary files a/source/fonts/font.ttf and b/source/fonts/font.ttf differ diff --git a/source/gecko.c b/source/gecko.c index fddc84f1..676a2b04 100644 --- a/source/gecko.c +++ b/source/gecko.c @@ -10,27 +10,31 @@ bool textVideoInit = false; #include //using the gprintf from crediar because it is smaller than mine -void gprintf( const char *str, ... ) { - if (!(geckoinit))return; +void gprintf( const char *str, ... ) +{ + if (!(geckoinit))return; - char astr[4096]; + char astr[4096]; - va_list ap; - va_start(ap,str); + va_list ap; + va_start(ap,str); - vsprintf( astr, str, ap ); + vsprintf( astr, str, ap ); - va_end(ap); + va_end(ap); - usb_sendbuffer_safe( 1, astr, strlen(astr) ); -} + usb_sendbuffer_safe( 1, astr, strlen(astr) ); +} -bool InitGecko() { - u32 geckoattached = usb_isgeckoalive(EXI_CHANNEL_1); - if (geckoattached) { - usb_flush(EXI_CHANNEL_1); - return true; - } else return false; +bool InitGecko() +{ + u32 geckoattached = usb_isgeckoalive(EXI_CHANNEL_1); + if (geckoattached) + { + usb_flush(EXI_CHANNEL_1); + return true; + } + else return false; } diff --git a/source/gecko.h b/source/gecko.h index 6b31ae35..83b55311 100644 --- a/source/gecko.h +++ b/source/gecko.h @@ -8,12 +8,12 @@ extern "C" { #endif #ifndef NO_DEBUG - //use this just like printf(); - void gprintf(const char *str, ...); - bool InitGecko(); + //use this just like printf(); + void gprintf(const char *str, ...); + bool InitGecko(); #else -#define gprintf(...) -#define InitGecko() false + #define gprintf(...) + #define InitGecko() false #endif /* NO_DEBUG */ diff --git a/source/homebrewboot/BootHomebrew.c b/source/homebrewboot/BootHomebrew.c index 5d40bf6f..8e5d1e12 100644 --- a/source/homebrewboot/BootHomebrew.c +++ b/source/homebrewboot/BootHomebrew.c @@ -37,9 +37,9 @@ void CopyHomebrewMemory(u32 read, u8 *temp, u32 len) { } int BootHomebrew(char * path) { - loadStub(); - if (Set_Stub_Split(0x00010001,"UNEO")<0) - Set_Stub_Split(0x00010001,"ULNR"); + loadStub(); + if (Set_Stub_Split(0x00010001,"UNEO")<0) + Set_Stub_Split(0x00010001,"ULNR"); void *buffer = NULL; u32 filesize = 0; entrypoint entry; @@ -106,9 +106,9 @@ int BootHomebrew(char * path) { } int BootHomebrewFromMem() { - loadStub(); - if (Set_Stub_Split(0x00010001,"UNEO")<0) - Set_Stub_Split(0x00010001,"ULNR"); + loadStub(); + if (Set_Stub_Split(0x00010001,"UNEO")<0) + Set_Stub_Split(0x00010001,"ULNR"); entrypoint entry; u32 cpu_isr; diff --git a/source/homebrewboot/HomebrewBrowse.cpp b/source/homebrewboot/HomebrewBrowse.cpp index 45776f86..ea3bb3b4 100644 --- a/source/homebrewboot/HomebrewBrowse.cpp +++ b/source/homebrewboot/HomebrewBrowse.cpp @@ -86,9 +86,9 @@ int MenuHomebrewBrowse() { /*** Sound Variables ***/ GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); /*** Image Variables ***/ @@ -219,11 +219,11 @@ int MenuHomebrewBrowse() { GuiImage MainButton2Img(&MainButtonImgData); GuiImage MainButton2ImgOver(&MainButtonImgOverData); - GuiText MainButton2Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255}); + GuiText MainButton2Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255 }); MainButton2Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton2Txt.SetPosition(148, -12); MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()-150, GuiText::DOTTED); - GuiText MainButton2DescTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255}); + GuiText MainButton2DescTxt(MainButtonText, 18, (GXColor) { 0, 0, 0, 255}); MainButton2DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton2DescTxt.SetPosition(148, 15); MainButton2DescTxt.SetMaxWidth(MainButton2Img.GetWidth()-150, GuiText::DOTTED); @@ -250,11 +250,11 @@ int MenuHomebrewBrowse() { MainButton3Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton3Txt.SetPosition(148, -12); MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()-150, GuiText::DOTTED); - GuiText MainButton3DescTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255}); + GuiText MainButton3DescTxt(MainButtonText, 18, (GXColor) { 0, 0, 0, 255}); MainButton3DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton3DescTxt.SetPosition(148, 15); MainButton3DescTxt.SetMaxWidth(MainButton3Img.GetWidth()-150, GuiText::DOTTED); - GuiText MainButton3DescOverTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255}); + GuiText MainButton3DescOverTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255 }); MainButton3DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton3DescOverTxt.SetPosition(148, 15); MainButton3DescOverTxt.SetMaxWidth(MainButton3Img.GetWidth()-150, GuiText::SCROLL); @@ -273,7 +273,7 @@ int MenuHomebrewBrowse() { GuiImage MainButton4Img(&MainButtonImgData); GuiImage MainButton4ImgOver(&MainButtonImgOverData); - GuiText MainButton4Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255}); + GuiText MainButton4Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255} ); MainButton4Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton4Txt.SetPosition(148, -12); MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()-150, GuiText::DOTTED); @@ -281,7 +281,7 @@ int MenuHomebrewBrowse() { MainButton4DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton4DescTxt.SetPosition(148, 15); MainButton4DescTxt.SetMaxWidth(MainButton4Img.GetWidth()-150, GuiText::DOTTED); - GuiText MainButton4DescOverTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255}); + GuiText MainButton4DescOverTxt(MainButtonText, 18, (GXColor) { 0, 0, 0, 255}); MainButton4DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); MainButton4DescOverTxt.SetPosition(148, 15); MainButton4DescOverTxt.SetMaxWidth(MainButton4Img.GetWidth()-150, GuiText::SCROLL); @@ -808,8 +808,8 @@ int MenuHomebrewBrowse() { int len = NETWORKBLOCKSIZE; temp = (u8 *) malloc(infilesize); - bool error = false; - u8 *ptr = temp; + bool error = false; + u8 *ptr = temp; while (read < infilesize) { ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true); @@ -823,73 +823,74 @@ int MenuHomebrewBrowse() { if (result < 0) { WindowPrompt(tr("Error while transfering data."), 0, tr("OK")); - error = true; + error = true; break; } if (!result) { break; - } + } - ptr += result; + ptr += result; read += result; } + + char filename[101]; + if (!error) { + + network_read((u8*) &filename, 100); + + // Do we need to unzip this thing? + if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) { - char filename[101]; - if (!error) { - - network_read((u8*) &filename, 100); - - // Do we need to unzip this thing? - if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) { - - // We need to unzip... - if (temp[0] == 'P' && temp[1] == 'K' && temp[2] == 0x03 && temp[3] == 0x04) { - // It's a zip file, unzip to the apps directory - - // Zip archive, ask for permission to install the zip - char zippath[255]; - sprintf((char *) &zippath, "%s%s", Settings.homebrewapps_path, filename); - - FILE *fp = fopen(zippath, "wb"); - if (fp != NULL) { - fwrite(temp, 1, infilesize, fp); - fclose(fp); - - // Now unzip the zip file... - unzFile uf = unzOpen(zippath); - if (uf==NULL) { - error = true; - } else { - extractZip(uf,0,1,0, Settings.homebrewapps_path); - unzCloseCurrentFile(uf); - - remove(zippath); - - // Reload this menu here... - menu = MENU_HOMEBREWBROWSE; - break; - } - } else { - error = true; - } - } else if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed - // It's compressed, uncompress - u8 *unc = (u8 *) malloc(uncfilesize); - uLongf f = uncfilesize; - error = uncompress(unc, &f, temp, infilesize) != Z_OK; - uncfilesize = f; - - free(temp); - temp = unc; - } - } - - if (!error && strstr(filename,".zip") == NULL) { - innetbuffer = temp; - } - } - + // We need to unzip... + if (temp[0] == 'P' && temp[1] == 'K' && temp[2] == 0x03 && temp[3] == 0x04) { + // It's a zip file, unzip to the apps directory + + // Zip archive, ask for permission to install the zip + char zippath[255]; + sprintf((char *) &zippath, "%s%s", Settings.homebrewapps_path, filename); + + FILE *fp = fopen(zippath, "wb"); + if (fp != NULL) + { + fwrite(temp, 1, infilesize, fp); + fclose(fp); + + // Now unzip the zip file... + unzFile uf = unzOpen(zippath); + if (uf==NULL) { + error = true; + } else { + extractZip(uf,0,1,0, Settings.homebrewapps_path); + unzCloseCurrentFile(uf); + + remove(zippath); + + // Reload this menu here... + menu = MENU_HOMEBREWBROWSE; + break; + } + } else { + error = true; + } + } else if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed + // It's compressed, uncompress + u8 *unc = (u8 *) malloc(uncfilesize); + uLongf f = uncfilesize; + error = uncompress(unc, &f, temp, infilesize) != Z_OK; + uncfilesize = f; + + free(temp); + temp = unc; + } + } + + if (!error && strstr(filename,".zip") == NULL) { + innetbuffer = temp; + } + } + ProgressStop(); if (error || read != infilesize) { @@ -897,18 +898,18 @@ int MenuHomebrewBrowse() { FreeHomebrewBuffer(); } else { if (strstr(filename,".dol") || strstr(filename,".DOL") - || strstr(filename,".elf") || strstr(filename,".ELF")) { + || strstr(filename,".elf") || strstr(filename,".ELF")) { boothomebrew = 2; menu = MENU_EXIT; CloseConnection(); break; } else if (strstr(filename,".zip")) { WindowPrompt(tr("Success:"), tr("Uploaded ZIP file installed to homebrew directory."), tr("OK")); - CloseConnection(); + CloseConnection(); } else { FreeHomebrewBuffer(); WindowPrompt(tr("ERROR:"), tr("Not a DOL/ELF file."), tr("OK")); - } + } } } } diff --git a/source/images/Channel_btn.png b/source/images/Channel_btn.png index 8044fe83..dc46e47e 100644 Binary files a/source/images/Channel_btn.png and b/source/images/Channel_btn.png differ diff --git a/source/images/Wifi_btn.png b/source/images/Wifi_btn.png index c0842ad0..24411088 100644 Binary files a/source/images/Wifi_btn.png and b/source/images/Wifi_btn.png differ diff --git a/source/images/Wiimote1.png b/source/images/Wiimote1.png index 96ae5f60..173ab5ee 100644 Binary files a/source/images/Wiimote1.png and b/source/images/Wiimote1.png differ diff --git a/source/images/Wiimote2.png b/source/images/Wiimote2.png index e3e2714e..3a7462ea 100644 Binary files a/source/images/Wiimote2.png and b/source/images/Wiimote2.png differ diff --git a/source/images/Wiimote3.png b/source/images/Wiimote3.png index 2938d913..bea80557 100644 Binary files a/source/images/Wiimote3.png and b/source/images/Wiimote3.png differ diff --git a/source/images/Wiimote4.png b/source/images/Wiimote4.png index 26fae4e1..582cb50e 100644 Binary files a/source/images/Wiimote4.png and b/source/images/Wiimote4.png differ diff --git a/source/images/abcIcon.png b/source/images/abcIcon.png index 1f67617e..19b39e01 100644 Binary files a/source/images/abcIcon.png and b/source/images/abcIcon.png differ diff --git a/source/images/addressbar_textbox.png b/source/images/addressbar_textbox.png index b82b9d89..77007f5b 100644 Binary files a/source/images/addressbar_textbox.png and b/source/images/addressbar_textbox.png differ diff --git a/source/images/arrangeCarousel.png b/source/images/arrangeCarousel.png index 3b5476fd..b8162cff 100644 Binary files a/source/images/arrangeCarousel.png and b/source/images/arrangeCarousel.png differ diff --git a/source/images/arrangeGrid.png b/source/images/arrangeGrid.png index 12c5641c..1b1be841 100644 Binary files a/source/images/arrangeGrid.png and b/source/images/arrangeGrid.png differ diff --git a/source/images/arrangeList.png b/source/images/arrangeList.png index 065042eb..9a116087 100644 Binary files a/source/images/arrangeList.png and b/source/images/arrangeList.png differ diff --git a/source/images/arrow_next.png b/source/images/arrow_next.png index f03f086d..3a814fde 100644 Binary files a/source/images/arrow_next.png and b/source/images/arrow_next.png differ diff --git a/source/images/arrow_previous.png b/source/images/arrow_previous.png index bcd0ca27..20eb8a55 100644 Binary files a/source/images/arrow_previous.png and b/source/images/arrow_previous.png differ diff --git a/source/images/background.png b/source/images/background.png index 22e66f91..1a482c7c 100644 Binary files a/source/images/background.png and b/source/images/background.png differ diff --git a/source/images/balanceboard.png b/source/images/balanceboard.png index 892a4bac..d713380b 100644 Binary files a/source/images/balanceboard.png and b/source/images/balanceboard.png differ diff --git a/source/images/balanceboardR.png b/source/images/balanceboardR.png index 97c75faf..ee2de742 100644 Binary files a/source/images/balanceboardR.png and b/source/images/balanceboardR.png differ diff --git a/source/images/battery.png b/source/images/battery.png index 80122437..9a4c9afb 100644 Binary files a/source/images/battery.png and b/source/images/battery.png differ diff --git a/source/images/battery_bar.png b/source/images/battery_bar.png index eb8ca38e..3aff7411 100644 Binary files a/source/images/battery_bar.png and b/source/images/battery_bar.png differ diff --git a/source/images/battery_bar_red.png b/source/images/battery_bar_red.png index eb79f768..bc09b4c3 100644 Binary files a/source/images/battery_bar_red.png and b/source/images/battery_bar_red.png differ diff --git a/source/images/battery_bar_white.png b/source/images/battery_bar_white.png index bf3da6f7..528b3405 100644 Binary files a/source/images/battery_bar_white.png and b/source/images/battery_bar_white.png differ diff --git a/source/images/battery_red.png b/source/images/battery_red.png index 56aede06..458b7364 100644 Binary files a/source/images/battery_red.png and b/source/images/battery_red.png differ diff --git a/source/images/battery_white.png b/source/images/battery_white.png index 7d39374c..a2812c5a 100644 Binary files a/source/images/battery_white.png and b/source/images/battery_white.png differ diff --git a/source/images/bg_browser.png b/source/images/bg_browser.png index bb277b76..a2c03f38 100644 Binary files a/source/images/bg_browser.png and b/source/images/bg_browser.png differ diff --git a/source/images/bg_browser_selection.png b/source/images/bg_browser_selection.png index ddc912a7..2bdc02db 100644 Binary files a/source/images/bg_browser_selection.png and b/source/images/bg_browser_selection.png differ diff --git a/source/images/bg_options.png b/source/images/bg_options.png index 419a8686..389cfa1d 100644 Binary files a/source/images/bg_options.png and b/source/images/bg_options.png differ diff --git a/source/images/bg_options_entry.png b/source/images/bg_options_entry.png index 4904043c..db4e2472 100644 Binary files a/source/images/bg_options_entry.png and b/source/images/bg_options_entry.png differ diff --git a/source/images/bg_options_settings.png b/source/images/bg_options_settings.png index ed5fc876..49ca299a 100644 Binary files a/source/images/bg_options_settings.png and b/source/images/bg_options_settings.png differ diff --git a/source/images/browser.png b/source/images/browser.png index 53febc12..f6400cd5 100644 Binary files a/source/images/browser.png and b/source/images/browser.png differ diff --git a/source/images/browser_over.png b/source/images/browser_over.png index 016b7870..59b15471 100644 Binary files a/source/images/browser_over.png and b/source/images/browser_over.png differ diff --git a/source/images/button_dialogue_box.png b/source/images/button_dialogue_box.png index 8d38e017..23d2b2e6 100644 Binary files a/source/images/button_dialogue_box.png and b/source/images/button_dialogue_box.png differ diff --git a/source/images/button_install.png b/source/images/button_install.png index ac0b063b..69737337 100644 Binary files a/source/images/button_install.png and b/source/images/button_install.png differ diff --git a/source/images/button_install_over.png b/source/images/button_install_over.png index cda95b78..9ffc0f55 100644 Binary files a/source/images/button_install_over.png and b/source/images/button_install_over.png differ diff --git a/source/images/cero_a.png b/source/images/cero_a.png index 020a4767..31d989fa 100644 Binary files a/source/images/cero_a.png and b/source/images/cero_a.png differ diff --git a/source/images/cero_b.png b/source/images/cero_b.png index 27abaee0..3358e0aa 100644 Binary files a/source/images/cero_b.png and b/source/images/cero_b.png differ diff --git a/source/images/cero_c.png b/source/images/cero_c.png index f1d8a38e..b0248697 100644 Binary files a/source/images/cero_c.png and b/source/images/cero_c.png differ diff --git a/source/images/cero_d.png b/source/images/cero_d.png index 6dfff67a..6eb1b4b3 100644 Binary files a/source/images/cero_d.png and b/source/images/cero_d.png differ diff --git a/source/images/cero_z.png b/source/images/cero_z.png index 312c5945..6b5a48cd 100644 Binary files a/source/images/cero_z.png and b/source/images/cero_z.png differ diff --git a/source/images/classiccontroller.png b/source/images/classiccontroller.png index 8dd487a6..92f81dfe 100644 Binary files a/source/images/classiccontroller.png and b/source/images/classiccontroller.png differ diff --git a/source/images/classiccontrollerR.png b/source/images/classiccontrollerR.png index 65fb4600..e3d051d0 100644 Binary files a/source/images/classiccontrollerR.png and b/source/images/classiccontrollerR.png differ diff --git a/source/images/closebutton.png b/source/images/closebutton.png index 2618f821..b2100d98 100644 Binary files a/source/images/closebutton.png and b/source/images/closebutton.png differ diff --git a/source/images/credits_bg.png b/source/images/credits_bg.png index 898e3dbc..3ce92fd3 100644 Binary files a/source/images/credits_bg.png and b/source/images/credits_bg.png differ diff --git a/source/images/credits_button.png b/source/images/credits_button.png index de833e49..510df769 100644 Binary files a/source/images/credits_button.png and b/source/images/credits_button.png differ diff --git a/source/images/credits_button_over.png b/source/images/credits_button_over.png index 5e806a21..92bb0b79 100644 Binary files a/source/images/credits_button_over.png and b/source/images/credits_button_over.png differ diff --git a/source/images/dancepad.png b/source/images/dancepad.png index 0ee84770..55191440 100644 Binary files a/source/images/dancepad.png and b/source/images/dancepad.png differ diff --git a/source/images/dancepadR.png b/source/images/dancepadR.png index 8ca3b173..1b3ae1ce 100644 Binary files a/source/images/dancepadR.png and b/source/images/dancepadR.png differ diff --git a/source/images/dialogue_box.png b/source/images/dialogue_box.png index af30bd4b..d16b96cc 100644 Binary files a/source/images/dialogue_box.png and b/source/images/dialogue_box.png differ diff --git a/source/images/dialogue_box_install.png b/source/images/dialogue_box_install.png index 6db10c8a..0bfaa26e 100644 Binary files a/source/images/dialogue_box_install.png and b/source/images/dialogue_box_install.png differ diff --git a/source/images/dialogue_box_startgame.png b/source/images/dialogue_box_startgame.png index 4ae285e0..bd684298 100644 Binary files a/source/images/dialogue_box_startgame.png and b/source/images/dialogue_box_startgame.png differ diff --git a/source/images/drums.png b/source/images/drums.png index f626f87c..ee2e000b 100644 Binary files a/source/images/drums.png and b/source/images/drums.png differ diff --git a/source/images/drumsR.png b/source/images/drumsR.png index 483ffed0..01836925 100644 Binary files a/source/images/drumsR.png and b/source/images/drumsR.png differ diff --git a/source/images/dvd.png b/source/images/dvd.png index e5a49c6a..43d71b52 100644 Binary files a/source/images/dvd.png and b/source/images/dvd.png differ diff --git a/source/images/esrb_ao.png b/source/images/esrb_ao.png index e1735970..5004a5ce 100644 Binary files a/source/images/esrb_ao.png and b/source/images/esrb_ao.png differ diff --git a/source/images/esrb_e.png b/source/images/esrb_e.png index 78d2597d..a13af0ca 100644 Binary files a/source/images/esrb_e.png and b/source/images/esrb_e.png differ diff --git a/source/images/esrb_ec.png b/source/images/esrb_ec.png index 1466b413..3d15720b 100644 Binary files a/source/images/esrb_ec.png and b/source/images/esrb_ec.png differ diff --git a/source/images/esrb_eten.png b/source/images/esrb_eten.png index d471fe5f..4defe777 100644 Binary files a/source/images/esrb_eten.png and b/source/images/esrb_eten.png differ diff --git a/source/images/esrb_m.png b/source/images/esrb_m.png index 4ed4da5c..a5d29daf 100644 Binary files a/source/images/esrb_m.png and b/source/images/esrb_m.png differ diff --git a/source/images/esrb_t.png b/source/images/esrb_t.png index be986f3d..b9549ba2 100644 Binary files a/source/images/esrb_t.png and b/source/images/esrb_t.png differ diff --git a/source/images/exit_bottom.png b/source/images/exit_bottom.png index 5029a33a..5f957415 100644 Binary files a/source/images/exit_bottom.png and b/source/images/exit_bottom.png differ diff --git a/source/images/exit_bottom_over.png b/source/images/exit_bottom_over.png index 2e7c3576..38992823 100644 Binary files a/source/images/exit_bottom_over.png and b/source/images/exit_bottom_over.png differ diff --git a/source/images/exit_button.png b/source/images/exit_button.png index 0a563c23..1c9fb09b 100644 Binary files a/source/images/exit_button.png and b/source/images/exit_button.png differ diff --git a/source/images/exit_top.png b/source/images/exit_top.png index 965eb39d..759264fc 100644 Binary files a/source/images/exit_top.png and b/source/images/exit_top.png differ diff --git a/source/images/exit_top_over.png b/source/images/exit_top_over.png index 8ba2db24..4f60dbcd 100644 Binary files a/source/images/exit_top_over.png and b/source/images/exit_top_over.png differ diff --git a/source/images/favIcon.png b/source/images/favIcon.png index 5d09c628..1b1314b9 100644 Binary files a/source/images/favIcon.png and b/source/images/favIcon.png differ diff --git a/source/images/favorite.png b/source/images/favorite.png index 844249ac..b8eeefe7 100644 Binary files a/source/images/favorite.png and b/source/images/favorite.png differ diff --git a/source/images/gameinfo1.png b/source/images/gameinfo1.png index eb5c5b21..7dbfea60 100644 Binary files a/source/images/gameinfo1.png and b/source/images/gameinfo1.png differ diff --git a/source/images/gameinfo1a.png b/source/images/gameinfo1a.png index 1af56d7e..528824dd 100644 Binary files a/source/images/gameinfo1a.png and b/source/images/gameinfo1a.png differ diff --git a/source/images/gameinfo2.png b/source/images/gameinfo2.png index a8273860..35ac092f 100644 Binary files a/source/images/gameinfo2.png and b/source/images/gameinfo2.png differ diff --git a/source/images/gameinfo2a.png b/source/images/gameinfo2a.png index 33417df2..3a81238f 100644 Binary files a/source/images/gameinfo2a.png and b/source/images/gameinfo2a.png differ diff --git a/source/images/gcncontroller.png b/source/images/gcncontroller.png index ae645fb5..244bb56b 100644 Binary files a/source/images/gcncontroller.png and b/source/images/gcncontroller.png differ diff --git a/source/images/gcncontrollerR.png b/source/images/gcncontrollerR.png index 2a5e8bd4..b8213715 100644 Binary files a/source/images/gcncontrollerR.png and b/source/images/gcncontrollerR.png differ diff --git a/source/images/guitar.png b/source/images/guitar.png index a9b73b25..cbb9a836 100644 Binary files a/source/images/guitar.png and b/source/images/guitar.png differ diff --git a/source/images/guitarR.png b/source/images/guitarR.png index d18fa8ea..7d763b5f 100644 Binary files a/source/images/guitarR.png and b/source/images/guitarR.png differ diff --git a/source/images/gxlogo.png b/source/images/gxlogo.png index 912600a8..dadd5cb6 100644 Binary files a/source/images/gxlogo.png and b/source/images/gxlogo.png differ diff --git a/source/images/icon_folder.png b/source/images/icon_folder.png index a804ae11..269b5ca8 100644 Binary files a/source/images/icon_folder.png and b/source/images/icon_folder.png differ diff --git a/source/images/keyboard_backspace_over.png b/source/images/keyboard_backspace_over.png index d965d5e9..419a2e6c 100644 Binary files a/source/images/keyboard_backspace_over.png and b/source/images/keyboard_backspace_over.png differ diff --git a/source/images/keyboard_clear_over.png b/source/images/keyboard_clear_over.png index 9da52536..11fbb962 100644 Binary files a/source/images/keyboard_clear_over.png and b/source/images/keyboard_clear_over.png differ diff --git a/source/images/keyboard_key.png b/source/images/keyboard_key.png index c55ec8ff..50061ba9 100644 Binary files a/source/images/keyboard_key.png and b/source/images/keyboard_key.png differ diff --git a/source/images/keyboard_key_over.png b/source/images/keyboard_key_over.png index 5ec99dac..15e352db 100644 Binary files a/source/images/keyboard_key_over.png and b/source/images/keyboard_key_over.png differ diff --git a/source/images/keyboard_largekey_over.png b/source/images/keyboard_largekey_over.png index e525a870..bac10741 100644 Binary files a/source/images/keyboard_largekey_over.png and b/source/images/keyboard_largekey_over.png differ diff --git a/source/images/keyboard_mediumkey_over.png b/source/images/keyboard_mediumkey_over.png index da45eb27..f2c821cb 100644 Binary files a/source/images/keyboard_mediumkey_over.png and b/source/images/keyboard_mediumkey_over.png differ diff --git a/source/images/keyboard_textbox.png b/source/images/keyboard_textbox.png index 7197466c..caeef7ee 100644 Binary files a/source/images/keyboard_textbox.png and b/source/images/keyboard_textbox.png differ diff --git a/source/images/little_star.png b/source/images/little_star.png index 44e364f0..de0da22c 100644 Binary files a/source/images/little_star.png and b/source/images/little_star.png differ diff --git a/source/images/lock.png b/source/images/lock.png index 504378fc..fc613766 100644 Binary files a/source/images/lock.png and b/source/images/lock.png differ diff --git a/source/images/menu_button.png b/source/images/menu_button.png index 5fb0d20c..008ae4a5 100644 Binary files a/source/images/menu_button.png and b/source/images/menu_button.png differ diff --git a/source/images/menu_button_over.png b/source/images/menu_button_over.png index 8f5637b1..4f0780e7 100644 Binary files a/source/images/menu_button_over.png and b/source/images/menu_button_over.png differ diff --git a/source/images/microphone.png b/source/images/microphone.png index 13d34231..d1e6b641 100644 Binary files a/source/images/microphone.png and b/source/images/microphone.png differ diff --git a/source/images/microphoneR.png b/source/images/microphoneR.png index 4eb6f7e5..892f8339 100644 Binary files a/source/images/microphoneR.png and b/source/images/microphoneR.png differ diff --git a/source/images/motionplus.png b/source/images/motionplus.png index 1a4a4fff..c3e34505 100644 Binary files a/source/images/motionplus.png and b/source/images/motionplus.png differ diff --git a/source/images/motionplusR.png b/source/images/motionplusR.png index 589f021c..98576248 100644 Binary files a/source/images/motionplusR.png and b/source/images/motionplusR.png differ diff --git a/source/images/mp3_pause.png b/source/images/mp3_pause.png index e50e0aee..f0b5903a 100644 Binary files a/source/images/mp3_pause.png and b/source/images/mp3_pause.png differ diff --git a/source/images/mp3_stop.png b/source/images/mp3_stop.png index 5945772e..2762881a 100644 Binary files a/source/images/mp3_stop.png and b/source/images/mp3_stop.png differ diff --git a/source/images/new.png b/source/images/new.png index 763cc1eb..167cce95 100644 Binary files a/source/images/new.png and b/source/images/new.png differ diff --git a/source/images/nintendods.png b/source/images/nintendods.png index 88eb7722..c22cf42a 100644 Binary files a/source/images/nintendods.png and b/source/images/nintendods.png differ diff --git a/source/images/nintendodsR.png b/source/images/nintendodsR.png index 8172e2e9..0cad10c7 100644 Binary files a/source/images/nintendodsR.png and b/source/images/nintendodsR.png differ diff --git a/source/images/nocover.png b/source/images/nocover.png index 6846966c..4be4143a 100644 Binary files a/source/images/nocover.png and b/source/images/nocover.png differ diff --git a/source/images/nocoverFlat.png b/source/images/nocoverFlat.png index 730a89d5..d44936a6 100644 Binary files a/source/images/nocoverFlat.png and b/source/images/nocoverFlat.png differ diff --git a/source/images/nodisc.png b/source/images/nodisc.png index f5cb3157..6bb61a7e 100644 Binary files a/source/images/nodisc.png and b/source/images/nodisc.png differ diff --git a/source/images/norating.png b/source/images/norating.png index a533118f..2b5248ee 100644 Binary files a/source/images/norating.png and b/source/images/norating.png differ diff --git a/source/images/not_favorite.png b/source/images/not_favorite.png index 4408659c..c9bd9df0 100644 Binary files a/source/images/not_favorite.png and b/source/images/not_favorite.png differ diff --git a/source/images/nunchuk.png b/source/images/nunchuk.png index 7331b7a2..1187cd65 100644 Binary files a/source/images/nunchuk.png and b/source/images/nunchuk.png differ diff --git a/source/images/nunchukR.png b/source/images/nunchukR.png index 7887c123..8e079079 100644 Binary files a/source/images/nunchukR.png and b/source/images/nunchukR.png differ diff --git a/source/images/pageindicator.png b/source/images/pageindicator.png index 59fd8892..28b0f8ee 100644 Binary files a/source/images/pageindicator.png and b/source/images/pageindicator.png differ diff --git a/source/images/pegi_12.png b/source/images/pegi_12.png index 4197aafc..5d199493 100644 Binary files a/source/images/pegi_12.png and b/source/images/pegi_12.png differ diff --git a/source/images/pegi_16.png b/source/images/pegi_16.png index b31f0b2e..039e4761 100644 Binary files a/source/images/pegi_16.png and b/source/images/pegi_16.png differ diff --git a/source/images/pegi_18.png b/source/images/pegi_18.png index c263355e..102102e5 100644 Binary files a/source/images/pegi_18.png and b/source/images/pegi_18.png differ diff --git a/source/images/pegi_3.png b/source/images/pegi_3.png index d72f14be..34c423f4 100644 Binary files a/source/images/pegi_3.png and b/source/images/pegi_3.png differ diff --git a/source/images/pegi_7.png b/source/images/pegi_7.png index 0fc7be96..b81e7514 100644 Binary files a/source/images/pegi_7.png and b/source/images/pegi_7.png differ diff --git a/source/images/playCountIcon.png b/source/images/playCountIcon.png index 60aee55b..14609fac 100644 Binary files a/source/images/playCountIcon.png and b/source/images/playCountIcon.png differ diff --git a/source/images/player1_point.png b/source/images/player1_point.png index c3d58cc7..c06c08c7 100644 Binary files a/source/images/player1_point.png and b/source/images/player1_point.png differ diff --git a/source/images/player2_point.png b/source/images/player2_point.png index 560f173e..6e952d24 100644 Binary files a/source/images/player2_point.png and b/source/images/player2_point.png differ diff --git a/source/images/player3_point.png b/source/images/player3_point.png index 05f40db4..704f84e0 100644 Binary files a/source/images/player3_point.png and b/source/images/player3_point.png differ diff --git a/source/images/player4_point.png b/source/images/player4_point.png index 3a1aa0ba..dd8f1ad3 100644 Binary files a/source/images/player4_point.png and b/source/images/player4_point.png differ diff --git a/source/images/progressbar.png b/source/images/progressbar.png index 7dd74337..747f6a4d 100644 Binary files a/source/images/progressbar.png and b/source/images/progressbar.png differ diff --git a/source/images/progressbar_outline.png b/source/images/progressbar_outline.png index ad1cff66..6b665457 100644 Binary files a/source/images/progressbar_outline.png and b/source/images/progressbar_outline.png differ diff --git a/source/images/rankIcon.png b/source/images/rankIcon.png index 10fa259c..b8dfcbdb 100644 Binary files a/source/images/rankIcon.png and b/source/images/rankIcon.png differ diff --git a/source/images/rplayer1_point.png b/source/images/rplayer1_point.png index 2b77b5be..eabd11bb 100644 Binary files a/source/images/rplayer1_point.png and b/source/images/rplayer1_point.png differ diff --git a/source/images/rplayer2_point.png b/source/images/rplayer2_point.png index 55f831db..f12a5c50 100644 Binary files a/source/images/rplayer2_point.png and b/source/images/rplayer2_point.png differ diff --git a/source/images/rplayer3_point.png b/source/images/rplayer3_point.png index ebf44f74..d67c019c 100644 Binary files a/source/images/rplayer3_point.png and b/source/images/rplayer3_point.png differ diff --git a/source/images/rplayer4_point.png b/source/images/rplayer4_point.png index 6ced54a6..d63ccd77 100644 Binary files a/source/images/rplayer4_point.png and b/source/images/rplayer4_point.png differ diff --git a/source/images/scrollbar.png b/source/images/scrollbar.png index e37daf35..032074db 100644 Binary files a/source/images/scrollbar.png and b/source/images/scrollbar.png differ diff --git a/source/images/scrollbar_arrowdown.png b/source/images/scrollbar_arrowdown.png index 57719119..ebd748c6 100644 Binary files a/source/images/scrollbar_arrowdown.png and b/source/images/scrollbar_arrowdown.png differ diff --git a/source/images/scrollbar_arrowup.png b/source/images/scrollbar_arrowup.png index 5b0d5857..6cef2fa0 100644 Binary files a/source/images/scrollbar_arrowup.png and b/source/images/scrollbar_arrowup.png differ diff --git a/source/images/scrollbar_box.png b/source/images/scrollbar_box.png index 0f06e0e1..9b568f3e 100644 Binary files a/source/images/scrollbar_box.png and b/source/images/scrollbar_box.png differ diff --git a/source/images/sdcard.png b/source/images/sdcard.png index ac373790..b3b247d9 100644 Binary files a/source/images/sdcard.png and b/source/images/sdcard.png differ diff --git a/source/images/sdcard_over.png b/source/images/sdcard_over.png index 81e21e45..636d3afd 100644 Binary files a/source/images/sdcard_over.png and b/source/images/sdcard_over.png differ diff --git a/source/images/searchIcon.png b/source/images/searchIcon.png index ccdc0f95..2885af56 100644 Binary files a/source/images/searchIcon.png and b/source/images/searchIcon.png differ diff --git a/source/images/settings_background.png b/source/images/settings_background.png index 9005917a..02ed90db 100644 Binary files a/source/images/settings_background.png and b/source/images/settings_background.png differ diff --git a/source/images/settings_button.png b/source/images/settings_button.png index 625a7dc9..77ce4d3f 100644 Binary files a/source/images/settings_button.png and b/source/images/settings_button.png differ diff --git a/source/images/settings_button_over.png b/source/images/settings_button_over.png index bb750cbe..0dba63d3 100644 Binary files a/source/images/settings_button_over.png and b/source/images/settings_button_over.png differ diff --git a/source/images/settings_menu_button.png b/source/images/settings_menu_button.png index e0d141ac..4a782e42 100644 Binary files a/source/images/settings_menu_button.png and b/source/images/settings_menu_button.png differ diff --git a/source/images/settings_title.png b/source/images/settings_title.png index cede9fc4..48de5083 100644 Binary files a/source/images/settings_title.png and b/source/images/settings_title.png differ diff --git a/source/images/settings_title_over.png b/source/images/settings_title_over.png index 366237cc..2111ad28 100644 Binary files a/source/images/settings_title_over.png and b/source/images/settings_title_over.png differ diff --git a/source/images/startgame_arrow_left.png b/source/images/startgame_arrow_left.png index fd35db17..4ed6e29e 100644 Binary files a/source/images/startgame_arrow_left.png and b/source/images/startgame_arrow_left.png differ diff --git a/source/images/startgame_arrow_right.png b/source/images/startgame_arrow_right.png index 029d9097..0ed3d0fa 100644 Binary files a/source/images/startgame_arrow_right.png and b/source/images/startgame_arrow_right.png differ diff --git a/source/images/theme_box.png b/source/images/theme_box.png index 3dad37a8..174b7b52 100644 Binary files a/source/images/theme_box.png and b/source/images/theme_box.png differ diff --git a/source/images/theme_dialogue_box.png b/source/images/theme_dialogue_box.png index 419a8686..389cfa1d 100644 Binary files a/source/images/theme_dialogue_box.png and b/source/images/theme_dialogue_box.png differ diff --git a/source/images/tooltip_left.png b/source/images/tooltip_left.png index 0e620f43..b1114ee1 100644 Binary files a/source/images/tooltip_left.png and b/source/images/tooltip_left.png differ diff --git a/source/images/tooltip_right.png b/source/images/tooltip_right.png index 9d68e9ba..86bd7ed5 100644 Binary files a/source/images/tooltip_right.png and b/source/images/tooltip_right.png differ diff --git a/source/images/unlock.png b/source/images/unlock.png index 8f605018..241f1b37 100644 Binary files a/source/images/unlock.png and b/source/images/unlock.png differ diff --git a/source/images/usbport.png b/source/images/usbport.png index e224523c..78de06a8 100644 Binary files a/source/images/usbport.png and b/source/images/usbport.png differ diff --git a/source/images/wbackground.png b/source/images/wbackground.png index 26a3cc2a..4035f47b 100644 Binary files a/source/images/wbackground.png and b/source/images/wbackground.png differ diff --git a/source/images/wdialogue_box_startgame.png b/source/images/wdialogue_box_startgame.png index bec45b4c..033814d8 100644 Binary files a/source/images/wdialogue_box_startgame.png and b/source/images/wdialogue_box_startgame.png differ diff --git a/source/images/wheel.png b/source/images/wheel.png index 2d2d7a7b..e4e85fc8 100644 Binary files a/source/images/wheel.png and b/source/images/wheel.png differ diff --git a/source/images/wheelR.png b/source/images/wheelR.png index c51cd69b..b777b12d 100644 Binary files a/source/images/wheelR.png and b/source/images/wheelR.png differ diff --git a/source/images/wifi1.png b/source/images/wifi1.png index 3f18a71d..8190f676 100644 Binary files a/source/images/wifi1.png and b/source/images/wifi1.png differ diff --git a/source/images/wifi12.png b/source/images/wifi12.png index 5fe5b99d..455f2e12 100644 Binary files a/source/images/wifi12.png and b/source/images/wifi12.png differ diff --git a/source/images/wifi16.png b/source/images/wifi16.png index 74e65e0b..7f73c2c1 100644 Binary files a/source/images/wifi16.png and b/source/images/wifi16.png differ diff --git a/source/images/wifi2.png b/source/images/wifi2.png index 2e8a398f..07dd889b 100644 Binary files a/source/images/wifi2.png and b/source/images/wifi2.png differ diff --git a/source/images/wifi3.png b/source/images/wifi3.png index 8b4e85da..67204d8a 100644 Binary files a/source/images/wifi3.png and b/source/images/wifi3.png differ diff --git a/source/images/wifi32.png b/source/images/wifi32.png index 5c7ea9a2..5fb2eba8 100644 Binary files a/source/images/wifi32.png and b/source/images/wifi32.png differ diff --git a/source/images/wifi4.png b/source/images/wifi4.png index 8aa6d168..725219c6 100644 Binary files a/source/images/wifi4.png and b/source/images/wifi4.png differ diff --git a/source/images/wifi8.png b/source/images/wifi8.png index ad562e45..13502a11 100644 Binary files a/source/images/wifi8.png and b/source/images/wifi8.png differ diff --git a/source/images/wiimote.png b/source/images/wiimote.png index f985900a..a868c218 100644 Binary files a/source/images/wiimote.png and b/source/images/wiimote.png differ diff --git a/source/images/wiimote_poweroff.png b/source/images/wiimote_poweroff.png index 94fcd1b7..81f34462 100644 Binary files a/source/images/wiimote_poweroff.png and b/source/images/wiimote_poweroff.png differ diff --git a/source/images/wiimote_poweroff_over.png b/source/images/wiimote_poweroff_over.png index d21b81a9..037dd7fe 100644 Binary files a/source/images/wiimote_poweroff_over.png and b/source/images/wiimote_poweroff_over.png differ diff --git a/source/images/wiispeak.png b/source/images/wiispeak.png index 65190255..24a8e250 100644 Binary files a/source/images/wiispeak.png and b/source/images/wiispeak.png differ diff --git a/source/images/wiispeakR.png b/source/images/wiispeakR.png index 3ade0c1d..272eb49a 100644 Binary files a/source/images/wiispeakR.png and b/source/images/wiispeakR.png differ diff --git a/source/images/zapper.png b/source/images/zapper.png index f8863e4b..2a6ac6e8 100644 Binary files a/source/images/zapper.png and b/source/images/zapper.png differ diff --git a/source/images/zapperR.png b/source/images/zapperR.png index 73ce3297..504f802a 100644 Binary files a/source/images/zapperR.png and b/source/images/zapperR.png differ diff --git a/source/language/UpdateLanguage.cpp b/source/language/UpdateLanguage.cpp index 7a557638..5478a086 100644 --- a/source/language/UpdateLanguage.cpp +++ b/source/language/UpdateLanguage.cpp @@ -49,7 +49,7 @@ int updateLanguageFiles() { if (file.data != NULL) { FILE * pfile; pfile = fopen(savepath, "wb"); - if (pfile != NULL) { + if(pfile != NULL) { fwrite(file.data,1,file.size,pfile); fclose(pfile); free(file.data); diff --git a/source/libfat/bit_ops.h b/source/libfat/bit_ops.h index 0d95135f..8a5fb3e1 100644 --- a/source/libfat/bit_ops.h +++ b/source/libfat/bit_ops.h @@ -35,23 +35,23 @@ Functions to deal with little endian values stored in uint8_t arrays -----------------------------------------------------------------*/ static inline uint16_t u8array_to_u16 (const uint8_t* item, int offset) { - return ( item[offset] | (item[offset + 1] << 8)); + return ( item[offset] | (item[offset + 1] << 8)); } static inline uint32_t u8array_to_u32 (const uint8_t* item, int offset) { - return ( item[offset] | (item[offset + 1] << 8) | (item[offset + 2] << 16) | (item[offset + 3] << 24)); + return ( item[offset] | (item[offset + 1] << 8) | (item[offset + 2] << 16) | (item[offset + 3] << 24)); } static inline void u16_to_u8array (uint8_t* item, int offset, uint16_t value) { - item[offset] = (uint8_t) value; - item[offset + 1] = (uint8_t)(value >> 8); + item[offset] = (uint8_t) value; + item[offset + 1] = (uint8_t)(value >> 8); } static inline void u32_to_u8array (uint8_t* item, int offset, uint32_t value) { - item[offset] = (uint8_t) value; - item[offset + 1] = (uint8_t)(value >> 8); - item[offset + 2] = (uint8_t)(value >> 16); - item[offset + 3] = (uint8_t)(value >> 24); + item[offset] = (uint8_t) value; + item[offset + 1] = (uint8_t)(value >> 8); + item[offset + 2] = (uint8_t)(value >> 16); + item[offset + 3] = (uint8_t)(value >> 24); } #endif // _BIT_OPS_H diff --git a/source/libfat/directory.c b/source/libfat/directory.c index ea8c218b..279a361d 100644 --- a/source/libfat/directory.c +++ b/source/libfat/directory.c @@ -4,7 +4,7 @@ a FAT partition Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -52,26 +52,26 @@ typedef unsigned short ucs2_t; // Long file name directory entry enum LFN_offset { - LFN_offset_ordinal = 0x00, // Position within LFN - LFN_offset_char0 = 0x01, - LFN_offset_char1 = 0x03, - LFN_offset_char2 = 0x05, - LFN_offset_char3 = 0x07, - LFN_offset_char4 = 0x09, - LFN_offset_flag = 0x0B, // Should be equal to ATTRIB_LFN - LFN_offset_reserved1 = 0x0C, // Always 0x00 - LFN_offset_checkSum = 0x0D, // Checksum of short file name (alias) - LFN_offset_char5 = 0x0E, - LFN_offset_char6 = 0x10, - LFN_offset_char7 = 0x12, - LFN_offset_char8 = 0x14, - LFN_offset_char9 = 0x16, - LFN_offset_char10 = 0x18, - LFN_offset_reserved2 = 0x1A, // Always 0x0000 - LFN_offset_char11 = 0x1C, - LFN_offset_char12 = 0x1E + LFN_offset_ordinal = 0x00, // Position within LFN + LFN_offset_char0 = 0x01, + LFN_offset_char1 = 0x03, + LFN_offset_char2 = 0x05, + LFN_offset_char3 = 0x07, + LFN_offset_char4 = 0x09, + LFN_offset_flag = 0x0B, // Should be equal to ATTRIB_LFN + LFN_offset_reserved1 = 0x0C, // Always 0x00 + LFN_offset_checkSum = 0x0D, // Checksum of short file name (alias) + LFN_offset_char5 = 0x0E, + LFN_offset_char6 = 0x10, + LFN_offset_char7 = 0x12, + LFN_offset_char8 = 0x14, + LFN_offset_char9 = 0x16, + LFN_offset_char10 = 0x18, + LFN_offset_reserved2 = 0x1A, // Always 0x0000 + LFN_offset_char11 = 0x1C, + LFN_offset_char12 = 0x1E }; -static const int LFN_offset_table[13]={0x01,0x03,0x05,0x07,0x09,0x0E,0x10,0x12,0x14,0x16,0x18,0x1C,0x1E}; +static const int LFN_offset_table[13]={0x01,0x03,0x05,0x07,0x09,0x0E,0x10,0x12,0x14,0x16,0x18,0x1C,0x1E}; #define LFN_END 0x40 #define LFN_DEL 0x80 @@ -79,40 +79,40 @@ static const int LFN_offset_table[13]={0x01,0x03,0x05,0x07,0x09,0x0E,0x10,0x12,0 static const char ILLEGAL_ALIAS_CHARACTERS[] = "\\/:;*?\"<>|&+,=[] "; static const char ILLEGAL_LFN_CHARACTERS[] = "\\/:*?\"<>|"; -/* +/* Returns number of UCS-2 characters needed to encode an LFN Returns -1 if it is an invalid LFN */ #define ABOVE_UCS_RANGE 0xF0 static int _FAT_directory_lfnLength (const char* name) { - unsigned int i; - size_t nameLength; - int ucsLength; - const char* tempName = name; - - nameLength = strnlen(name, MAX_FILENAME_LENGTH); - // Make sure the name is short enough to be valid - if ( nameLength >= MAX_FILENAME_LENGTH) { - return -1; - } - // Make sure it doesn't contain any invalid characters - if (strpbrk (name, ILLEGAL_LFN_CHARACTERS) != NULL) { - return -1; - } - // Make sure the name doesn't contain any control codes or codes not representable in UCS-2 - for (i = 0; i < nameLength; i++) { - if (name[i] < 0x20 || name[i] >= ABOVE_UCS_RANGE) { - return -1; - } - } - // Convert to UCS-2 and get the resulting length - ucsLength = mbsrtowcs(NULL, &tempName, MAX_LFN_LENGTH, NULL); - if (ucsLength < 0 || ucsLength >= MAX_LFN_LENGTH) { - return -1; - } - - // Otherwise it is valid - return ucsLength; + unsigned int i; + size_t nameLength; + int ucsLength; + const char* tempName = name; + + nameLength = strnlen(name, MAX_FILENAME_LENGTH); + // Make sure the name is short enough to be valid + if ( nameLength >= MAX_FILENAME_LENGTH) { + return -1; + } + // Make sure it doesn't contain any invalid characters + if (strpbrk (name, ILLEGAL_LFN_CHARACTERS) != NULL) { + return -1; + } + // Make sure the name doesn't contain any control codes or codes not representable in UCS-2 + for (i = 0; i < nameLength; i++) { + if (name[i] < 0x20 || name[i] >= ABOVE_UCS_RANGE) { + return -1; + } + } + // Convert to UCS-2 and get the resulting length + ucsLength = mbsrtowcs(NULL, &tempName, MAX_LFN_LENGTH, NULL); + if (ucsLength < 0 || ucsLength >= MAX_LFN_LENGTH) { + return -1; + } + + // Otherwise it is valid + return ucsLength; } /* @@ -120,27 +120,27 @@ Convert a multibyte encoded string into a NUL-terminated UCS-2 string, storing a return number of characters stored */ static size_t _FAT_directory_mbstoucs2 (ucs2_t* dst, const char* src, size_t len) { - mbstate_t ps = {0}; - wchar_t tempChar; - int bytes; - size_t count = 0; + mbstate_t ps = {0}; + wchar_t tempChar; + int bytes; + size_t count = 0; - while (count < len-1 && src != '\0') { - bytes = mbrtowc (&tempChar, src, MB_CUR_MAX, &ps); - if (bytes > 0) { - *dst = (ucs2_t)tempChar; - src += bytes; - dst++; - count++; - } else if (bytes == 0) { - break; - } else { - return -1; - } - } - *dst = '\0'; + while (count < len-1 && src != '\0') { + bytes = mbrtowc (&tempChar, src, MB_CUR_MAX, &ps); + if (bytes > 0) { + *dst = (ucs2_t)tempChar; + src += bytes; + dst++; + count++; + } else if (bytes == 0) { + break; + } else { + return -1; + } + } + *dst = '\0'; - return count; + return count; } /* @@ -148,924 +148,928 @@ Convert a UCS-2 string into a NUL-terminated multibyte string, storing at most l return number of chars stored, or (size_t)-1 on error */ static size_t _FAT_directory_ucs2tombs (char* dst, const ucs2_t* src, size_t len) { - mbstate_t ps = {0}; - size_t count = 0; - int bytes; - char buff[MB_CUR_MAX]; - int i; - - while (count < len - 1 && *src != '\0') { - bytes = wcrtomb (buff, *src, &ps); - if (bytes < 0) { - return -1; - } - if (count + bytes < len && bytes > 0) { - for (i = 0; i < bytes; i++) { - *dst++ = buff[i]; - } - src++; - count += bytes; - } else { - break; - } - } - *dst = L'\0'; - - return count; + mbstate_t ps = {0}; + size_t count = 0; + int bytes; + char buff[MB_CUR_MAX]; + int i; + + while (count < len - 1 && *src != '\0') { + bytes = wcrtomb (buff, *src, &ps); + if (bytes < 0) { + return -1; + } + if (count + bytes < len && bytes > 0) { + for (i = 0; i < bytes; i++) { + *dst++ = buff[i]; + } + src++; + count += bytes; + } else { + break; + } + } + *dst = L'\0'; + + return count; } /* Case-independent comparison of two multibyte encoded strings */ static int _FAT_directory_mbsncasecmp (const char* s1, const char* s2, size_t len1) { - wchar_t wc1, wc2; - mbstate_t ps1 = {0}; - mbstate_t ps2 = {0}; - size_t b1 = 0; - size_t b2 = 0; - - if (len1 == 0) { - return 0; - } - - do { - s1 += b1; - s2 += b2; - b1 = mbrtowc(&wc1, s1, MB_CUR_MAX, &ps1); - b2 = mbrtowc(&wc2, s2, MB_CUR_MAX, &ps2); - if ((int)b1 < 0 || (int)b2 < 0) { - break; - } - len1 -= b1; - } while (len1 > 0 && towlower(wc1) == towlower(wc2) && wc1 != 0); - - return towlower(wc1) - towlower(wc2); + wchar_t wc1, wc2; + mbstate_t ps1 = {0}; + mbstate_t ps2 = {0}; + size_t b1 = 0; + size_t b2 = 0; + + if (len1 == 0) { + return 0; + } + + do { + s1 += b1; + s2 += b2; + b1 = mbrtowc(&wc1, s1, MB_CUR_MAX, &ps1); + b2 = mbrtowc(&wc2, s2, MB_CUR_MAX, &ps2); + if ((int)b1 < 0 || (int)b2 < 0) { + break; + } + len1 -= b1; + } while (len1 > 0 && towlower(wc1) == towlower(wc2) && wc1 != 0); + + return towlower(wc1) - towlower(wc2); } static bool _FAT_directory_entryGetAlias (const u8* entryData, char* destName) { - int i=0; - int j=0; + int i=0; + int j=0; - destName[0] = '\0'; - if (entryData[0] != DIR_ENTRY_FREE) { - if (entryData[0] == '.') { - destName[0] = '.'; - if (entryData[1] == '.') { - destName[1] = '.'; - destName[2] = '\0'; - } else { - destName[1] = '\0'; - } - } else { - // Copy the filename from the dirEntry to the string - for (i = 0; (i < 8) && (entryData[DIR_ENTRY_name + i] != ' '); i++) { - destName[i] = entryData[DIR_ENTRY_name + i]; - } - // Copy the extension from the dirEntry to the string - if (entryData[DIR_ENTRY_extension] != ' ') { - destName[i++] = '.'; - for ( j = 0; (j < 3) && (entryData[DIR_ENTRY_extension + j] != ' '); j++) { - destName[i++] = entryData[DIR_ENTRY_extension + j]; - } - } - destName[i] = '\0'; - } - } + destName[0] = '\0'; + if (entryData[0] != DIR_ENTRY_FREE) { + if (entryData[0] == '.') { + destName[0] = '.'; + if (entryData[1] == '.') { + destName[1] = '.'; + destName[2] = '\0'; + } else { + destName[1] = '\0'; + } + } else { + // Copy the filename from the dirEntry to the string + for (i = 0; (i < 8) && (entryData[DIR_ENTRY_name + i] != ' '); i++) { + destName[i] = entryData[DIR_ENTRY_name + i]; + } + // Copy the extension from the dirEntry to the string + if (entryData[DIR_ENTRY_extension] != ' ') { + destName[i++] = '.'; + for ( j = 0; (j < 3) && (entryData[DIR_ENTRY_extension + j] != ' '); j++) { + destName[i++] = entryData[DIR_ENTRY_extension + j]; + } + } + destName[i] = '\0'; + } + } - return (destName[0] != '\0'); + return (destName[0] != '\0'); } uint32_t _FAT_directory_entryGetCluster (PARTITION* partition, const uint8_t* entryData) { - if (partition->filesysType == FS_FAT32) { - // Only use high 16 bits of start cluster when we are certain they are correctly defined - return u8array_to_u16(entryData,DIR_ENTRY_cluster) | (u8array_to_u16(entryData, DIR_ENTRY_clusterHigh) << 16); - } else { - return u8array_to_u16(entryData,DIR_ENTRY_cluster); - } + if (partition->filesysType == FS_FAT32) { + // Only use high 16 bits of start cluster when we are certain they are correctly defined + return u8array_to_u16(entryData,DIR_ENTRY_cluster) | (u8array_to_u16(entryData, DIR_ENTRY_clusterHigh) << 16); + } else { + return u8array_to_u16(entryData,DIR_ENTRY_cluster); + } } static bool _FAT_directory_incrementDirEntryPosition (PARTITION* partition, DIR_ENTRY_POSITION* entryPosition, bool extendDirectory) { - DIR_ENTRY_POSITION position = *entryPosition; - uint32_t tempCluster; + DIR_ENTRY_POSITION position = *entryPosition; + uint32_t tempCluster; - // Increment offset, wrapping at the end of a sector - ++ position.offset; - if (position.offset == BYTES_PER_READ / DIR_ENTRY_DATA_SIZE) { - position.offset = 0; - // Increment sector when wrapping - ++ position.sector; - // But wrap at the end of a cluster - if ((position.sector == partition->sectorsPerCluster) && (position.cluster != FAT16_ROOT_DIR_CLUSTER)) { - position.sector = 0; - // Move onto the next cluster, making sure there is another cluster to go to - tempCluster = _FAT_fat_nextCluster(partition, position.cluster); - if (tempCluster == CLUSTER_EOF) { - if (extendDirectory) { - tempCluster = _FAT_fat_linkFreeClusterCleared (partition, position.cluster); - if (!_FAT_fat_isValidCluster(partition, tempCluster)) { - return false; // This will only happen if the disc is full - } - } else { - return false; // Got to the end of the directory, not extending it - } - } - position.cluster = tempCluster; - } else if ((position.cluster == FAT16_ROOT_DIR_CLUSTER) && (position.sector == (partition->dataStart - partition->rootDirStart))) { - return false; // Got to end of root directory, can't extend it - } - } - *entryPosition = position; - return true; + // Increment offset, wrapping at the end of a sector + ++ position.offset; + if (position.offset == BYTES_PER_READ / DIR_ENTRY_DATA_SIZE) { + position.offset = 0; + // Increment sector when wrapping + ++ position.sector; + // But wrap at the end of a cluster + if ((position.sector == partition->sectorsPerCluster) && (position.cluster != FAT16_ROOT_DIR_CLUSTER)) { + position.sector = 0; + // Move onto the next cluster, making sure there is another cluster to go to + tempCluster = _FAT_fat_nextCluster(partition, position.cluster); + if (tempCluster == CLUSTER_EOF) { + if (extendDirectory) { + tempCluster = _FAT_fat_linkFreeClusterCleared (partition, position.cluster); + if (!_FAT_fat_isValidCluster(partition, tempCluster)) { + return false; // This will only happen if the disc is full + } + } else { + return false; // Got to the end of the directory, not extending it + } + } + position.cluster = tempCluster; + } else if ((position.cluster == FAT16_ROOT_DIR_CLUSTER) && (position.sector == (partition->dataStart - partition->rootDirStart))) { + return false; // Got to end of root directory, can't extend it + } + } + *entryPosition = position; + return true; } bool _FAT_directory_getNextEntry (PARTITION* partition, DIR_ENTRY* entry) { - DIR_ENTRY_POSITION entryStart; - DIR_ENTRY_POSITION entryEnd; - uint8_t entryData[0x20]; - ucs2_t lfn[MAX_LFN_LENGTH]; - bool notFound, found; - int lfnPos; - uint8_t lfnChkSum, chkSum; - bool lfnExists; - int i; + DIR_ENTRY_POSITION entryStart; + DIR_ENTRY_POSITION entryEnd; + uint8_t entryData[0x20]; + ucs2_t lfn[MAX_LFN_LENGTH]; + bool notFound, found; + int lfnPos; + uint8_t lfnChkSum, chkSum; + bool lfnExists; + int i; - lfnChkSum = 0; + lfnChkSum = 0; - entryStart = entry->dataEnd; + entryStart = entry->dataEnd; - // Make sure we are using the correct root directory, in case of FAT32 - if (entryStart.cluster == FAT16_ROOT_DIR_CLUSTER) { - entryStart.cluster = partition->rootDirCluster; - } + // Make sure we are using the correct root directory, in case of FAT32 + if (entryStart.cluster == FAT16_ROOT_DIR_CLUSTER) { + entryStart.cluster = partition->rootDirCluster; + } - entryEnd = entryStart; + entryEnd = entryStart; - lfnExists = false; + lfnExists = false; - found = false; - notFound = false; + found = false; + notFound = false; - while (!found && !notFound) { - if (_FAT_directory_incrementDirEntryPosition (partition, &entryEnd, false) == false) { - notFound = true; - } + while (!found && !notFound) { + if (_FAT_directory_incrementDirEntryPosition (partition, &entryEnd, false) == false) { + notFound = true; + } - _FAT_cache_readPartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, entryEnd.cluster) + entryEnd.sector, - entryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + _FAT_cache_readPartialSector (partition->cache, entryData, + _FAT_fat_clusterToSector(partition, entryEnd.cluster) + entryEnd.sector, + entryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - if (entryData[DIR_ENTRY_attributes] == ATTRIB_LFN) { - // It's an LFN - if (entryData[LFN_offset_ordinal] & LFN_DEL) { - lfnExists = false; - } else if (entryData[LFN_offset_ordinal] & LFN_END) { - // Last part of LFN, make sure it isn't deleted using previous if(Thanks MoonLight) - entryStart = entryEnd; // This is the start of a directory entry - lfnExists = true; - lfnPos = (entryData[LFN_offset_ordinal] & ~LFN_END) * 13; - if (lfnPos > MAX_LFN_LENGTH - 1) { - lfnPos = MAX_LFN_LENGTH - 1; - } - lfn[lfnPos] = '\0'; // Set end of lfn to null character - lfnChkSum = entryData[LFN_offset_checkSum]; - } - if (lfnChkSum != entryData[LFN_offset_checkSum]) { - lfnExists = false; - } - if (lfnExists) { - lfnPos = ((entryData[LFN_offset_ordinal] & ~LFN_END) - 1) * 13; - if (lfnPos > LAST_LFN_POS) { - // Force it within the buffer. Will corrupt the filename but prevent buffer overflows - lfnPos = LAST_LFN_POS; - } - for (i = 0; i < 13; i++) { - lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i]+1] << 8); - } - } - } else if (entryData[DIR_ENTRY_attributes] & ATTRIB_VOL) { - // This is a volume name, don't bother with it - } else if (entryData[0] == DIR_ENTRY_LAST) { - notFound = true; - } else if ((entryData[0] != DIR_ENTRY_FREE) && (entryData[0] > 0x20) && !(entryData[DIR_ENTRY_attributes] & ATTRIB_VOL)) { - if (lfnExists) { - // Calculate file checksum - chkSum = 0; - for (i=0; i < 11; i++) { - // NOTE: The operation is an unsigned char rotate right - chkSum = ((chkSum & 1) ? 0x80 : 0) + (chkSum >> 1) + entryData[i]; - } - if (chkSum != lfnChkSum) { - lfnExists = false; - entry->filename[0] = '\0'; - } - } + if (entryData[DIR_ENTRY_attributes] == ATTRIB_LFN) { + // It's an LFN + if (entryData[LFN_offset_ordinal] & LFN_DEL) { + lfnExists = false; + } else if (entryData[LFN_offset_ordinal] & LFN_END) { + // Last part of LFN, make sure it isn't deleted using previous if(Thanks MoonLight) + entryStart = entryEnd; // This is the start of a directory entry + lfnExists = true; + lfnPos = (entryData[LFN_offset_ordinal] & ~LFN_END) * 13; + if (lfnPos > MAX_LFN_LENGTH - 1) { + lfnPos = MAX_LFN_LENGTH - 1; + } + lfn[lfnPos] = '\0'; // Set end of lfn to null character + lfnChkSum = entryData[LFN_offset_checkSum]; + } if (lfnChkSum != entryData[LFN_offset_checkSum]) { + lfnExists = false; + } + if (lfnExists) { + lfnPos = ((entryData[LFN_offset_ordinal] & ~LFN_END) - 1) * 13; + if (lfnPos > LAST_LFN_POS) { + // Force it within the buffer. Will corrupt the filename but prevent buffer overflows + lfnPos = LAST_LFN_POS; + } + for (i = 0; i < 13; i++) { + lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i]+1] << 8); + } + } + } else if (entryData[DIR_ENTRY_attributes] & ATTRIB_VOL) { + // This is a volume name, don't bother with it + } else if (entryData[0] == DIR_ENTRY_LAST) { + notFound = true; + } else if ((entryData[0] != DIR_ENTRY_FREE) && (entryData[0] > 0x20) && !(entryData[DIR_ENTRY_attributes] & ATTRIB_VOL)) { + if (lfnExists) { + // Calculate file checksum + chkSum = 0; + for (i=0; i < 11; i++) { + // NOTE: The operation is an unsigned char rotate right + chkSum = ((chkSum & 1) ? 0x80 : 0) + (chkSum >> 1) + entryData[i]; + } + if (chkSum != lfnChkSum) { + lfnExists = false; + entry->filename[0] = '\0'; + } + } + + if (lfnExists) { + if (_FAT_directory_ucs2tombs (entry->filename, lfn, MAX_FILENAME_LENGTH) == (size_t)-1) { + // Failed to convert the file name to UTF-8. Maybe the wrong locale is set? + return false; + } + } else { + entryStart = entryEnd; + _FAT_directory_entryGetAlias (entryData, entry->filename); + } + found = true; + } + } - if (lfnExists) { - if (_FAT_directory_ucs2tombs (entry->filename, lfn, MAX_FILENAME_LENGTH) == (size_t)-1) { - // Failed to convert the file name to UTF-8. Maybe the wrong locale is set? - return false; - } - } else { - entryStart = entryEnd; - _FAT_directory_entryGetAlias (entryData, entry->filename); - } - found = true; - } - } - - // If no file is found, return false - if (notFound) { - return false; - } else { - // Fill in the directory entry struct - entry->dataStart = entryStart; - entry->dataEnd = entryEnd; - memcpy (entry->entryData, entryData, DIR_ENTRY_DATA_SIZE); - return true; - } + // If no file is found, return false + if (notFound) { + return false; + } else { + // Fill in the directory entry struct + entry->dataStart = entryStart; + entry->dataEnd = entryEnd; + memcpy (entry->entryData, entryData, DIR_ENTRY_DATA_SIZE); + return true; + } } bool _FAT_directory_getFirstEntry (PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster) { - entry->dataStart.cluster = dirCluster; - entry->dataStart.sector = 0; - entry->dataStart.offset = -1; // Start before the beginning of the directory + entry->dataStart.cluster = dirCluster; + entry->dataStart.sector = 0; + entry->dataStart.offset = -1; // Start before the beginning of the directory - entry->dataEnd = entry->dataStart; + entry->dataEnd = entry->dataStart; - return _FAT_directory_getNextEntry (partition, entry); + return _FAT_directory_getNextEntry (partition, entry); } bool _FAT_directory_getRootEntry (PARTITION* partition, DIR_ENTRY* entry) { - entry->dataStart.cluster = 0; - entry->dataStart.sector = 0; - entry->dataStart.offset = 0; - - entry->dataEnd = entry->dataStart; - - memset (entry->filename, '\0', MAX_FILENAME_LENGTH); - entry->filename[0] = '.'; - - memset (entry->entryData, 0, DIR_ENTRY_DATA_SIZE); - memset (entry->entryData, ' ', 11); - entry->entryData[0] = '.'; - - entry->entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; - - u16_to_u8array (entry->entryData, DIR_ENTRY_cluster, partition->rootDirCluster); - u16_to_u8array (entry->entryData, DIR_ENTRY_clusterHigh, partition->rootDirCluster >> 16); - - return true; + entry->dataStart.cluster = 0; + entry->dataStart.sector = 0; + entry->dataStart.offset = 0; + + entry->dataEnd = entry->dataStart; + + memset (entry->filename, '\0', MAX_FILENAME_LENGTH); + entry->filename[0] = '.'; + + memset (entry->entryData, 0, DIR_ENTRY_DATA_SIZE); + memset (entry->entryData, ' ', 11); + entry->entryData[0] = '.'; + + entry->entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; + + u16_to_u8array (entry->entryData, DIR_ENTRY_cluster, partition->rootDirCluster); + u16_to_u8array (entry->entryData, DIR_ENTRY_clusterHigh, partition->rootDirCluster >> 16); + + return true; } bool _FAT_directory_entryFromPosition (PARTITION* partition, DIR_ENTRY* entry) { - DIR_ENTRY_POSITION entryStart = entry->dataStart; - DIR_ENTRY_POSITION entryEnd = entry->dataEnd; - bool entryStillValid; - bool finished; - ucs2_t lfn[MAX_LFN_LENGTH]; - int i; - int lfnPos; - uint8_t entryData[DIR_ENTRY_DATA_SIZE]; + DIR_ENTRY_POSITION entryStart = entry->dataStart; + DIR_ENTRY_POSITION entryEnd = entry->dataEnd; + bool entryStillValid; + bool finished; + ucs2_t lfn[MAX_LFN_LENGTH]; + int i; + int lfnPos; + uint8_t entryData[DIR_ENTRY_DATA_SIZE]; + + memset (entry->filename, '\0', MAX_FILENAME_LENGTH); - memset (entry->filename, '\0', MAX_FILENAME_LENGTH); + // Create an empty directory entry to overwrite the old ones with + for ( entryStillValid = true, finished = false; + entryStillValid && !finished; + entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &entryStart, false)) + { + _FAT_cache_readPartialSector (partition->cache, entryData, + _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, + entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + + if ((entryStart.cluster == entryEnd.cluster) + && (entryStart.sector == entryEnd.sector) + && (entryStart.offset == entryEnd.offset)) { + // Copy the entry data and stop, since this is the last section of the directory entry + memcpy (entry->entryData, entryData, DIR_ENTRY_DATA_SIZE); + finished = true; + } else { + // Copy the long file name data + lfnPos = ((entryData[LFN_offset_ordinal] & ~LFN_END) - 1) * 13; + if (lfnPos > LAST_LFN_POS) { + lfnPos = LAST_LFN_POS_CORRECTION; + } + for (i = 0; i < 13; i++) { + lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i]+1] << 8); + } + } + } - // Create an empty directory entry to overwrite the old ones with - for ( entryStillValid = true, finished = false; - entryStillValid && !finished; - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &entryStart, false)) { - _FAT_cache_readPartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, - entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - - if ((entryStart.cluster == entryEnd.cluster) - && (entryStart.sector == entryEnd.sector) - && (entryStart.offset == entryEnd.offset)) { - // Copy the entry data and stop, since this is the last section of the directory entry - memcpy (entry->entryData, entryData, DIR_ENTRY_DATA_SIZE); - finished = true; - } else { - // Copy the long file name data - lfnPos = ((entryData[LFN_offset_ordinal] & ~LFN_END) - 1) * 13; - if (lfnPos > LAST_LFN_POS) { - lfnPos = LAST_LFN_POS_CORRECTION; - } - for (i = 0; i < 13; i++) { - lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i]+1] << 8); - } - } - } - - if (!entryStillValid) { - return false; - } - - if ((entryStart.cluster == entryEnd.cluster) - && (entryStart.sector == entryEnd.sector) - && (entryStart.offset == entryEnd.offset)) { - // Since the entry doesn't have a long file name, extract the short filename - if (!_FAT_directory_entryGetAlias (entry->entryData, entry->filename)) { - return false; - } - } else { - // Encode the long file name into a multibyte string - if (_FAT_directory_ucs2tombs (entry->filename, lfn, MAX_FILENAME_LENGTH) == (size_t)-1) { - return false; - } - } - - return true; + if (!entryStillValid) { + return false; + } + + if ((entryStart.cluster == entryEnd.cluster) + && (entryStart.sector == entryEnd.sector) + && (entryStart.offset == entryEnd.offset)) { + // Since the entry doesn't have a long file name, extract the short filename + if (!_FAT_directory_entryGetAlias (entry->entryData, entry->filename)) { + return false; + } + } else { + // Encode the long file name into a multibyte string + if (_FAT_directory_ucs2tombs (entry->filename, lfn, MAX_FILENAME_LENGTH) == (size_t)-1) { + return false; + } + } + + return true; } bool _FAT_directory_entryFromPath (PARTITION* partition, DIR_ENTRY* entry, const char* path, const char* pathEnd) { - size_t dirnameLength; - const char* pathPosition; - const char* nextPathPosition; - uint32_t dirCluster; - bool foundFile; - char alias[MAX_ALIAS_LENGTH]; - bool found, notFound; + size_t dirnameLength; + const char* pathPosition; + const char* nextPathPosition; + uint32_t dirCluster; + bool foundFile; + char alias[MAX_ALIAS_LENGTH]; + bool found, notFound; - pathPosition = path; + pathPosition = path; + + found = false; + notFound = false; - found = false; - notFound = false; + if (pathEnd == NULL) { + // Set pathEnd to the end of the path string + pathEnd = strchr (path, '\0'); + } - if (pathEnd == NULL) { - // Set pathEnd to the end of the path string - pathEnd = strchr (path, '\0'); - } + if (pathPosition[0] == DIR_SEPARATOR) { + // Start at root directory + dirCluster = partition->rootDirCluster; + // Consume separator(s) + while (pathPosition[0] == DIR_SEPARATOR) { + pathPosition++; + } + // If the path is only specifying a directory in the form of "/" return it + if (pathPosition >= pathEnd) { + _FAT_directory_getRootEntry (partition, entry); + found = true; + } + } else { + // Start in current working directory + dirCluster = partition->cwdCluster; + } - if (pathPosition[0] == DIR_SEPARATOR) { - // Start at root directory - dirCluster = partition->rootDirCluster; - // Consume separator(s) - while (pathPosition[0] == DIR_SEPARATOR) { - pathPosition++; - } - // If the path is only specifying a directory in the form of "/" return it - if (pathPosition >= pathEnd) { - _FAT_directory_getRootEntry (partition, entry); - found = true; - } - } else { - // Start in current working directory - dirCluster = partition->cwdCluster; - } + // If the path is only specifying a directory in the form "." + // and this is the root directory, return it + if ((dirCluster == partition->rootDirCluster) && (strcmp(".", pathPosition) == 0)) { + _FAT_directory_getRootEntry (partition, entry); + found = true; + } + + while (!found && !notFound) { + // Get the name of the next required subdirectory within the path + nextPathPosition = strchr (pathPosition, DIR_SEPARATOR); + if (nextPathPosition != NULL) { + dirnameLength = nextPathPosition - pathPosition; + } else { + dirnameLength = strlen(pathPosition); + } - // If the path is only specifying a directory in the form "." - // and this is the root directory, return it - if ((dirCluster == partition->rootDirCluster) && (strcmp(".", pathPosition) == 0)) { - _FAT_directory_getRootEntry (partition, entry); - found = true; - } + if (dirnameLength > MAX_FILENAME_LENGTH) { + // The path is too long to bother with + return false; + } - while (!found && !notFound) { - // Get the name of the next required subdirectory within the path - nextPathPosition = strchr (pathPosition, DIR_SEPARATOR); - if (nextPathPosition != NULL) { - dirnameLength = nextPathPosition - pathPosition; - } else { - dirnameLength = strlen(pathPosition); - } + // Look for the directory within the path + foundFile = _FAT_directory_getFirstEntry (partition, entry, dirCluster); - if (dirnameLength > MAX_FILENAME_LENGTH) { - // The path is too long to bother with - return false; - } + while (foundFile && !found && !notFound) { // It hasn't already found the file + // Check if the filename matches + if ((dirnameLength == strnlen(entry->filename, MAX_FILENAME_LENGTH)) + && (_FAT_directory_mbsncasecmp(pathPosition, entry->filename, dirnameLength) == 0)) { + found = true; + } - // Look for the directory within the path - foundFile = _FAT_directory_getFirstEntry (partition, entry, dirCluster); + // Check if the alias matches + _FAT_directory_entryGetAlias (entry->entryData, alias); + if ((dirnameLength == strnlen(alias, MAX_ALIAS_LENGTH)) + && (strncasecmp(pathPosition, alias, dirnameLength) == 0)) { + found = true; + } - while (foundFile && !found && !notFound) { // It hasn't already found the file - // Check if the filename matches - if ((dirnameLength == strnlen(entry->filename, MAX_FILENAME_LENGTH)) - && (_FAT_directory_mbsncasecmp(pathPosition, entry->filename, dirnameLength) == 0)) { - found = true; - } + if (found && !(entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) && (nextPathPosition != NULL)) { + // Make sure that we aren't trying to follow a file instead of a directory in the path + found = false; + } - // Check if the alias matches - _FAT_directory_entryGetAlias (entry->entryData, alias); - if ((dirnameLength == strnlen(alias, MAX_ALIAS_LENGTH)) - && (strncasecmp(pathPosition, alias, dirnameLength) == 0)) { - found = true; - } + if (!found) { + foundFile = _FAT_directory_getNextEntry (partition, entry); + } + } - if (found && !(entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) && (nextPathPosition != NULL)) { - // Make sure that we aren't trying to follow a file instead of a directory in the path - found = false; - } + if (!foundFile) { + // Check that the search didn't get to the end of the directory + notFound = true; + found = false; + } else if ((nextPathPosition == NULL) || (nextPathPosition >= pathEnd)) { + // Check that we reached the end of the path + found = true; + } else if (entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) { + dirCluster = _FAT_directory_entryGetCluster (partition, entry->entryData); + pathPosition = nextPathPosition; + // Consume separator(s) + while (pathPosition[0] == DIR_SEPARATOR) { + pathPosition++; + } + // The requested directory was found + if (pathPosition >= pathEnd) { + found = true; + } else { + found = false; + } + } + } - if (!found) { - foundFile = _FAT_directory_getNextEntry (partition, entry); - } - } - - if (!foundFile) { - // Check that the search didn't get to the end of the directory - notFound = true; - found = false; - } else if ((nextPathPosition == NULL) || (nextPathPosition >= pathEnd)) { - // Check that we reached the end of the path - found = true; - } else if (entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) { - dirCluster = _FAT_directory_entryGetCluster (partition, entry->entryData); - pathPosition = nextPathPosition; - // Consume separator(s) - while (pathPosition[0] == DIR_SEPARATOR) { - pathPosition++; - } - // The requested directory was found - if (pathPosition >= pathEnd) { - found = true; - } else { - found = false; - } - } - } - - if (found && !notFound) { - if (partition->filesysType == FS_FAT32 && (entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) && - _FAT_directory_entryGetCluster (partition, entry->entryData) == CLUSTER_ROOT) { - // On FAT32 it should specify an actual cluster for the root entry, - // not cluster 0 as on FAT16 - _FAT_directory_getRootEntry (partition, entry); - } - return true; - } else { - return false; - } + if (found && !notFound) { + if (partition->filesysType == FS_FAT32 && (entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) && + _FAT_directory_entryGetCluster (partition, entry->entryData) == CLUSTER_ROOT) + { + // On FAT32 it should specify an actual cluster for the root entry, + // not cluster 0 as on FAT16 + _FAT_directory_getRootEntry (partition, entry); + } + return true; + } else { + return false; + } } bool _FAT_directory_removeEntry (PARTITION* partition, DIR_ENTRY* entry) { - DIR_ENTRY_POSITION entryStart = entry->dataStart; - DIR_ENTRY_POSITION entryEnd = entry->dataEnd; - bool entryStillValid; - bool finished; - uint8_t entryData[DIR_ENTRY_DATA_SIZE]; + DIR_ENTRY_POSITION entryStart = entry->dataStart; + DIR_ENTRY_POSITION entryEnd = entry->dataEnd; + bool entryStillValid; + bool finished; + uint8_t entryData[DIR_ENTRY_DATA_SIZE]; - // Create an empty directory entry to overwrite the old ones with - for ( entryStillValid = true, finished = false; - entryStillValid && !finished; - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &entryStart, false)) { - _FAT_cache_readPartialSector (partition->cache, entryData, _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - entryData[0] = DIR_ENTRY_FREE; - _FAT_cache_writePartialSector (partition->cache, entryData, _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - if ((entryStart.cluster == entryEnd.cluster) && (entryStart.sector == entryEnd.sector) && (entryStart.offset == entryEnd.offset)) { - finished = true; - } - } + // Create an empty directory entry to overwrite the old ones with + for ( entryStillValid = true, finished = false; + entryStillValid && !finished; + entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &entryStart, false)) + { + _FAT_cache_readPartialSector (partition->cache, entryData, _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + entryData[0] = DIR_ENTRY_FREE; + _FAT_cache_writePartialSector (partition->cache, entryData, _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + if ((entryStart.cluster == entryEnd.cluster) && (entryStart.sector == entryEnd.sector) && (entryStart.offset == entryEnd.offset)) { + finished = true; + } + } - if (!entryStillValid) { - return false; - } + if (!entryStillValid) { + return false; + } - return true; + return true; } static bool _FAT_directory_findEntryGap (PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster, size_t size) { - DIR_ENTRY_POSITION gapStart; - DIR_ENTRY_POSITION gapEnd; - uint8_t entryData[DIR_ENTRY_DATA_SIZE]; - size_t dirEntryRemain; - bool endOfDirectory, entryStillValid; + DIR_ENTRY_POSITION gapStart; + DIR_ENTRY_POSITION gapEnd; + uint8_t entryData[DIR_ENTRY_DATA_SIZE]; + size_t dirEntryRemain; + bool endOfDirectory, entryStillValid; - // Scan Dir for free entry - gapEnd.offset = 0; - gapEnd.sector = 0; - gapEnd.cluster = dirCluster; + // Scan Dir for free entry + gapEnd.offset = 0; + gapEnd.sector = 0; + gapEnd.cluster = dirCluster; - gapStart = gapEnd; + gapStart = gapEnd; - entryStillValid = true; - dirEntryRemain = size; - endOfDirectory = false; + entryStillValid = true; + dirEntryRemain = size; + endOfDirectory = false; + + while (entryStillValid && !endOfDirectory && (dirEntryRemain > 0)) { + _FAT_cache_readPartialSector (partition->cache, entryData, + _FAT_fat_clusterToSector(partition, gapEnd.cluster) + gapEnd.sector, + gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + if (entryData[0] == DIR_ENTRY_LAST) { + gapStart = gapEnd; + -- dirEntryRemain; + endOfDirectory = true; + } else if (entryData[0] == DIR_ENTRY_FREE) { + if (dirEntryRemain == size) { + gapStart = gapEnd; + } + -- dirEntryRemain; + } else { + dirEntryRemain = size; + } + + if (!endOfDirectory && (dirEntryRemain > 0)) { + entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &gapEnd, true); + } + } - while (entryStillValid && !endOfDirectory && (dirEntryRemain > 0)) { - _FAT_cache_readPartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, gapEnd.cluster) + gapEnd.sector, - gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - if (entryData[0] == DIR_ENTRY_LAST) { - gapStart = gapEnd; - -- dirEntryRemain; - endOfDirectory = true; - } else if (entryData[0] == DIR_ENTRY_FREE) { - if (dirEntryRemain == size) { - gapStart = gapEnd; - } - -- dirEntryRemain; - } else { - dirEntryRemain = size; - } + // Make sure the scanning didn't fail + if (!entryStillValid) { + return false; + } - if (!endOfDirectory && (dirEntryRemain > 0)) { - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &gapEnd, true); - } - } + // Save the start entry, since we know it is valid + entry->dataStart = gapStart; - // Make sure the scanning didn't fail - if (!entryStillValid) { - return false; - } + if (endOfDirectory) { + memset (entryData, DIR_ENTRY_LAST, DIR_ENTRY_DATA_SIZE); + dirEntryRemain += 1; // Increase by one to take account of End Of Directory Marker + while ((dirEntryRemain > 0) && entryStillValid) { + // Get the gapEnd before incrementing it, so the second to last one is saved + entry->dataEnd = gapEnd; + // Increment gapEnd, moving onto the next entry + entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &gapEnd, true); + -- dirEntryRemain; + // Fill the entry with blanks + _FAT_cache_writePartialSector (partition->cache, entryData, + _FAT_fat_clusterToSector(partition, gapEnd.cluster) + gapEnd.sector, + gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + } + if (!entryStillValid) { + return false; + } + } else { + entry->dataEnd = gapEnd; + } - // Save the start entry, since we know it is valid - entry->dataStart = gapStart; - - if (endOfDirectory) { - memset (entryData, DIR_ENTRY_LAST, DIR_ENTRY_DATA_SIZE); - dirEntryRemain += 1; // Increase by one to take account of End Of Directory Marker - while ((dirEntryRemain > 0) && entryStillValid) { - // Get the gapEnd before incrementing it, so the second to last one is saved - entry->dataEnd = gapEnd; - // Increment gapEnd, moving onto the next entry - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &gapEnd, true); - -- dirEntryRemain; - // Fill the entry with blanks - _FAT_cache_writePartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, gapEnd.cluster) + gapEnd.sector, - gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - } - if (!entryStillValid) { - return false; - } - } else { - entry->dataEnd = gapEnd; - } - - return true; + return true; } static bool _FAT_directory_entryExists (PARTITION* partition, const char* name, uint32_t dirCluster) { - DIR_ENTRY tempEntry; - bool foundFile; - char alias[MAX_ALIAS_LENGTH]; - size_t dirnameLength; + DIR_ENTRY tempEntry; + bool foundFile; + char alias[MAX_ALIAS_LENGTH]; + size_t dirnameLength; - dirnameLength = strnlen(name, MAX_FILENAME_LENGTH); + dirnameLength = strnlen(name, MAX_FILENAME_LENGTH); - if (dirnameLength >= MAX_FILENAME_LENGTH) { - return false; - } + if (dirnameLength >= MAX_FILENAME_LENGTH) { + return false; + } + + // Make sure the entry doesn't already exist + foundFile = _FAT_directory_getFirstEntry (partition, &tempEntry, dirCluster); - // Make sure the entry doesn't already exist - foundFile = _FAT_directory_getFirstEntry (partition, &tempEntry, dirCluster); + while (foundFile) { // It hasn't already found the file + // Check if the filename matches + if ((dirnameLength == strnlen(tempEntry.filename, MAX_FILENAME_LENGTH)) + && (_FAT_directory_mbsncasecmp(name, tempEntry.filename, dirnameLength) == 0)) { + return true; + } - while (foundFile) { // It hasn't already found the file - // Check if the filename matches - if ((dirnameLength == strnlen(tempEntry.filename, MAX_FILENAME_LENGTH)) - && (_FAT_directory_mbsncasecmp(name, tempEntry.filename, dirnameLength) == 0)) { - return true; - } - - // Check if the alias matches - _FAT_directory_entryGetAlias (tempEntry.entryData, alias); - if ((strncasecmp(name, alias, MAX_ALIAS_LENGTH) == 0)) { - return true; - } - foundFile = _FAT_directory_getNextEntry (partition, &tempEntry); - } - return false; + // Check if the alias matches + _FAT_directory_entryGetAlias (tempEntry.entryData, alias); + if ((strncasecmp(name, alias, MAX_ALIAS_LENGTH) == 0)) { + return true; + } + foundFile = _FAT_directory_getNextEntry (partition, &tempEntry); + } + return false; } -/* -Creates an alias for a long file name. If the alias is not an exact match for the -filename, it returns the number of characters in the alias. If the two names match, +/* +Creates an alias for a long file name. If the alias is not an exact match for the +filename, it returns the number of characters in the alias. If the two names match, it returns 0. If there was an error, it returns -1. */ static int _FAT_directory_createAlias (char* alias, const char* lfn) { - bool lossyConversion = false; // Set when the alias had to be modified to be valid - int lfnPos = 0; - int aliasPos = 0; - wchar_t lfnChar; - int oemChar; - mbstate_t ps = {0}; - int bytesUsed = 0; - const char* lfnExt; - int aliasExtLen; - - // Strip leading periods - while (lfn[lfnPos] == '.') { - lfnPos ++; - lossyConversion = true; - } - - // Primary portion of alias - while (aliasPos < 8 && lfn[lfnPos] != '.' && lfn[lfnPos] != '\0') { - bytesUsed = mbrtowc(&lfnChar, lfn + lfnPos, MAX_FILENAME_LENGTH - lfnPos, &ps); - if (bytesUsed < 0) { - return -1; - } - oemChar = wctob(towupper((wint_t)lfnChar)); - if (wctob((wint_t)lfnChar) != oemChar) { - // Case of letter was changed - lossyConversion = true; - } - if (oemChar == ' ') { - // Skip spaces in filename - lossyConversion = true; - lfnPos += bytesUsed; - continue; - } - if (oemChar == EOF) { - oemChar = '_'; // Replace unconvertable characters with underscores - lossyConversion = true; - } - if (strchr (ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { - // Invalid Alias character - oemChar = '_'; // Replace illegal characters with underscores - lossyConversion = true; - } - - alias[aliasPos] = (char)oemChar; - aliasPos++; - lfnPos += bytesUsed; - } - - if (lfn[lfnPos] != '.' && lfn[lfnPos] != '\0') { - // Name was more than 8 characters long - lossyConversion = true; - } - - // Alias extension - lfnExt = strrchr (lfn, '.'); - if (lfnExt != NULL && lfnExt != strchr (lfn, '.')) { - // More than one period in name - lossyConversion = true; - } - if (lfnExt != NULL && lfnExt[1] != '\0') { - lfnExt++; - alias[aliasPos] = '.'; - aliasPos++; - memset (&ps, 0, sizeof(ps)); - for (aliasExtLen = 0; aliasExtLen < MAX_ALIAS_EXT_LENGTH && *lfnExt != '\0'; aliasExtLen++) { - bytesUsed = mbrtowc(&lfnChar, lfnExt, MAX_FILENAME_LENGTH - lfnPos, &ps); - if (bytesUsed < 0) { - return -1; - } - oemChar = wctob(towupper((wint_t)lfnChar)); - if (wctob((wint_t)lfnChar) != oemChar) { - // Case of letter was changed - lossyConversion = true; - } - if (oemChar == ' ') { - // Skip spaces in alias - lossyConversion = true; - lfnExt += bytesUsed; - continue; - } - if (oemChar == EOF) { - oemChar = '_'; // Replace unconvertable characters with underscores - lossyConversion = true; - } - if (strchr (ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { - // Invalid Alias character - oemChar = '_'; // Replace illegal characters with underscores - lossyConversion = true; - } - - alias[aliasPos] = (char)oemChar; - aliasPos++; - lfnExt += bytesUsed; - } - if (*lfnExt != '\0') { - // Extension was more than 3 characters long - lossyConversion = true; - } - } - - alias[aliasPos] = '\0'; - if (lossyConversion) { - return aliasPos; - } else { - return 0; - } + bool lossyConversion = false; // Set when the alias had to be modified to be valid + int lfnPos = 0; + int aliasPos = 0; + wchar_t lfnChar; + int oemChar; + mbstate_t ps = {0}; + int bytesUsed = 0; + const char* lfnExt; + int aliasExtLen; + + // Strip leading periods + while (lfn[lfnPos] == '.') { + lfnPos ++; + lossyConversion = true; + } + + // Primary portion of alias + while (aliasPos < 8 && lfn[lfnPos] != '.' && lfn[lfnPos] != '\0') { + bytesUsed = mbrtowc(&lfnChar, lfn + lfnPos, MAX_FILENAME_LENGTH - lfnPos, &ps); + if (bytesUsed < 0) { + return -1; + } + oemChar = wctob(towupper((wint_t)lfnChar)); + if (wctob((wint_t)lfnChar) != oemChar) { + // Case of letter was changed + lossyConversion = true; + } + if (oemChar == ' ') { + // Skip spaces in filename + lossyConversion = true; + lfnPos += bytesUsed; + continue; + } + if (oemChar == EOF) { + oemChar = '_'; // Replace unconvertable characters with underscores + lossyConversion = true; + } + if (strchr (ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { + // Invalid Alias character + oemChar = '_'; // Replace illegal characters with underscores + lossyConversion = true; + } + + alias[aliasPos] = (char)oemChar; + aliasPos++; + lfnPos += bytesUsed; + } + + if (lfn[lfnPos] != '.' && lfn[lfnPos] != '\0') { + // Name was more than 8 characters long + lossyConversion = true; + } + + // Alias extension + lfnExt = strrchr (lfn, '.'); + if (lfnExt != NULL && lfnExt != strchr (lfn, '.')) { + // More than one period in name + lossyConversion = true; + } + if (lfnExt != NULL && lfnExt[1] != '\0') { + lfnExt++; + alias[aliasPos] = '.'; + aliasPos++; + memset (&ps, 0, sizeof(ps)); + for (aliasExtLen = 0; aliasExtLen < MAX_ALIAS_EXT_LENGTH && *lfnExt != '\0'; aliasExtLen++) { + bytesUsed = mbrtowc(&lfnChar, lfnExt, MAX_FILENAME_LENGTH - lfnPos, &ps); + if (bytesUsed < 0) { + return -1; + } + oemChar = wctob(towupper((wint_t)lfnChar)); + if (wctob((wint_t)lfnChar) != oemChar) { + // Case of letter was changed + lossyConversion = true; + } + if (oemChar == ' ') { + // Skip spaces in alias + lossyConversion = true; + lfnExt += bytesUsed; + continue; + } + if (oemChar == EOF) { + oemChar = '_'; // Replace unconvertable characters with underscores + lossyConversion = true; + } + if (strchr (ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { + // Invalid Alias character + oemChar = '_'; // Replace illegal characters with underscores + lossyConversion = true; + } + + alias[aliasPos] = (char)oemChar; + aliasPos++; + lfnExt += bytesUsed; + } + if (*lfnExt != '\0') { + // Extension was more than 3 characters long + lossyConversion = true; + } + } + + alias[aliasPos] = '\0'; + if (lossyConversion) { + return aliasPos; + } else { + return 0; + } } bool _FAT_directory_addEntry (PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster) { - size_t entrySize; - uint8_t lfnEntry[DIR_ENTRY_DATA_SIZE]; - int i,j; // Must be signed for use when decrementing in for loop - char *tmpCharPtr; - DIR_ENTRY_POSITION curEntryPos; - bool entryStillValid; - uint8_t aliasCheckSum = 0; - char alias [MAX_ALIAS_LENGTH]; - int aliasLen; - int lfnLen; + size_t entrySize; + uint8_t lfnEntry[DIR_ENTRY_DATA_SIZE]; + int i,j; // Must be signed for use when decrementing in for loop + char *tmpCharPtr; + DIR_ENTRY_POSITION curEntryPos; + bool entryStillValid; + uint8_t aliasCheckSum = 0; + char alias [MAX_ALIAS_LENGTH]; + int aliasLen; + int lfnLen; - // Make sure the filename is not 0 length - if (strnlen (entry->filename, MAX_FILENAME_LENGTH) < 1) { - return false; - } + // Make sure the filename is not 0 length + if (strnlen (entry->filename, MAX_FILENAME_LENGTH) < 1) { + return false; + } - // Make sure the filename is at least a valid LFN - lfnLen = _FAT_directory_lfnLength (entry->filename); - if (lfnLen < 0) { - return false; - } + // Make sure the filename is at least a valid LFN + lfnLen = _FAT_directory_lfnLength (entry->filename); + if (lfnLen < 0) { + return false; + } - // Remove trailing spaces - for (i = strlen (entry->filename) - 1; (i > 0) && (entry->filename[i] == ' '); --i) { - entry->filename[i] = '\0'; - } - // Remove leading spaces - for (i = 0; (i < (int)strlen (entry->filename)) && (entry->filename[i] == ' '); ++i) ; - if (i > 0) { - memmove (entry->filename, entry->filename + i, strlen (entry->filename + i)); - } + // Remove trailing spaces + for (i = strlen (entry->filename) - 1; (i > 0) && (entry->filename[i] == ' '); --i) { + entry->filename[i] = '\0'; + } + // Remove leading spaces + for (i = 0; (i < (int)strlen (entry->filename)) && (entry->filename[i] == ' '); ++i) ; + if (i > 0) { + memmove (entry->filename, entry->filename + i, strlen (entry->filename + i)); + } - // Remove junk in filename - i = strlen (entry->filename); - memset (entry->filename + i, '\0', MAX_FILENAME_LENGTH - i); + // Remove junk in filename + i = strlen (entry->filename); + memset (entry->filename + i, '\0', MAX_FILENAME_LENGTH - i); - // Make sure the entry doesn't already exist - if (_FAT_directory_entryExists (partition, entry->filename, dirCluster)) { - return false; - } + // Make sure the entry doesn't already exist + if (_FAT_directory_entryExists (partition, entry->filename, dirCluster)) { + return false; + } - // Clear out alias, so we can generate a new one - memset (entry->entryData, ' ', 11); + // Clear out alias, so we can generate a new one + memset (entry->entryData, ' ', 11); - if ( strncmp(entry->filename, ".", MAX_FILENAME_LENGTH) == 0) { - // "." entry - entry->entryData[0] = '.'; - entrySize = 1; - } else if ( strncmp(entry->filename, "..", MAX_FILENAME_LENGTH) == 0) { - // ".." entry - entry->entryData[0] = '.'; - entry->entryData[1] = '.'; - entrySize = 1; - } else { - // Normal file name - aliasLen = _FAT_directory_createAlias (alias, entry->filename); - if (aliasLen < 0) { - return false; - } else if (aliasLen == 0) { - // It's a normal short filename - entrySize = 1; - } else { - // It's a long filename with an alias - entrySize = ((lfnLen + LFN_ENTRY_LENGTH - 1) / LFN_ENTRY_LENGTH) + 1; + if ( strncmp(entry->filename, ".", MAX_FILENAME_LENGTH) == 0) { + // "." entry + entry->entryData[0] = '.'; + entrySize = 1; + } else if ( strncmp(entry->filename, "..", MAX_FILENAME_LENGTH) == 0) { + // ".." entry + entry->entryData[0] = '.'; + entry->entryData[1] = '.'; + entrySize = 1; + } else { + // Normal file name + aliasLen = _FAT_directory_createAlias (alias, entry->filename); + if (aliasLen < 0) { + return false; + } else if (aliasLen == 0) { + // It's a normal short filename + entrySize = 1; + } else { + // It's a long filename with an alias + entrySize = ((lfnLen + LFN_ENTRY_LENGTH - 1) / LFN_ENTRY_LENGTH) + 1; + + // Generate full alias for all cases except when the alias is simply an upper case version of the LFN + // and there isn't already a file with that name + if (strncasecmp (alias, entry->filename, MAX_ALIAS_LENGTH) != 0 || + _FAT_directory_entryExists (partition, alias, dirCluster)) + { + // expand primary part to 8 characters long by padding the end with underscores + i = MAX_ALIAS_PRI_LENGTH - 1; + // Move extension to last 3 characters + while (alias[i] != '.' && i > 0) i--; + if (i > 0) { + j = MAX_ALIAS_LENGTH - MAX_ALIAS_EXT_LENGTH - 2; // 1 char for '.', one for NUL, 3 for extension + memmove (alias + j, alias + i, strlen(alias) - i); + // Pad primary component + memset (alias + i, '_', j - i); + alias[MAX_ALIAS_LENGTH-1]=0; + } + + // Generate numeric tail + for (i = 1; i <= MAX_NUMERIC_TAIL; i++) { + j = i; + tmpCharPtr = alias + MAX_ALIAS_PRI_LENGTH - 1; + while (j > 0) { + *tmpCharPtr = '0' + (j % 10); // ASCII numeric value + tmpCharPtr--; + j /= 10; + } + *tmpCharPtr = '~'; + if (!_FAT_directory_entryExists (partition, alias, dirCluster)) { + break; + } + } + if (i > MAX_NUMERIC_TAIL) { + // Couldn't get a valid alias + return false; + } + } + } - // Generate full alias for all cases except when the alias is simply an upper case version of the LFN - // and there isn't already a file with that name - if (strncasecmp (alias, entry->filename, MAX_ALIAS_LENGTH) != 0 || - _FAT_directory_entryExists (partition, alias, dirCluster)) { - // expand primary part to 8 characters long by padding the end with underscores - i = MAX_ALIAS_PRI_LENGTH - 1; - // Move extension to last 3 characters - while (alias[i] != '.' && i > 0) i--; - if (i > 0) { - j = MAX_ALIAS_LENGTH - MAX_ALIAS_EXT_LENGTH - 2; // 1 char for '.', one for NUL, 3 for extension - memmove (alias + j, alias + i, strlen(alias) - i); - // Pad primary component - memset (alias + i, '_', j - i); - alias[MAX_ALIAS_LENGTH-1]=0; - } + // Copy alias or short file name into directory entry data + for (i = 0, j = 0; (j < 8) && (alias[i] != '.') && (alias[i] != '\0'); i++, j++) { + entry->entryData[j] = alias[i]; + } + while (j < 8) { + entry->entryData[j] = ' '; + ++ j; + } + if (alias[i] == '.') { + // Copy extension + ++ i; + while ((alias[i] != '\0') && (j < 11)) { + entry->entryData[j] = alias[i]; + ++ i; + ++ j; + } + } + while (j < 11) { + entry->entryData[j] = ' '; + ++ j; + } + + // Generate alias checksum + for (i=0; i < ALIAS_ENTRY_LENGTH; i++) { + // NOTE: The operation is an unsigned char rotate right + aliasCheckSum = ((aliasCheckSum & 1) ? 0x80 : 0) + (aliasCheckSum >> 1) + entry->entryData[i]; + } + } - // Generate numeric tail - for (i = 1; i <= MAX_NUMERIC_TAIL; i++) { - j = i; - tmpCharPtr = alias + MAX_ALIAS_PRI_LENGTH - 1; - while (j > 0) { - *tmpCharPtr = '0' + (j % 10); // ASCII numeric value - tmpCharPtr--; - j /= 10; - } - *tmpCharPtr = '~'; - if (!_FAT_directory_entryExists (partition, alias, dirCluster)) { - break; - } - } - if (i > MAX_NUMERIC_TAIL) { - // Couldn't get a valid alias - return false; - } - } - } + // Find or create space for the entry + if (_FAT_directory_findEntryGap (partition, entry, dirCluster, entrySize) == false) { + return false; + } - // Copy alias or short file name into directory entry data - for (i = 0, j = 0; (j < 8) && (alias[i] != '.') && (alias[i] != '\0'); i++, j++) { - entry->entryData[j] = alias[i]; - } - while (j < 8) { - entry->entryData[j] = ' '; - ++ j; - } - if (alias[i] == '.') { - // Copy extension - ++ i; - while ((alias[i] != '\0') && (j < 11)) { - entry->entryData[j] = alias[i]; - ++ i; - ++ j; - } - } - while (j < 11) { - entry->entryData[j] = ' '; - ++ j; - } + // Write out directory entry + curEntryPos = entry->dataStart; - // Generate alias checksum - for (i=0; i < ALIAS_ENTRY_LENGTH; i++) { - // NOTE: The operation is an unsigned char rotate right - aliasCheckSum = ((aliasCheckSum & 1) ? 0x80 : 0) + (aliasCheckSum >> 1) + entry->entryData[i]; - } - } + { + // lfn is only pushed onto the stack here, reducing overall stack usage + ucs2_t lfn[MAX_LFN_LENGTH] = {0}; + _FAT_directory_mbstoucs2 (lfn, entry->filename, MAX_LFN_LENGTH); - // Find or create space for the entry - if (_FAT_directory_findEntryGap (partition, entry, dirCluster, entrySize) == false) { - return false; - } + for (entryStillValid = true, i = entrySize; entryStillValid && i > 0; + entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &curEntryPos, false), -- i ) + { + if (i > 1) { + // Long filename entry + lfnEntry[LFN_offset_ordinal] = (i - 1) | ((size_t)i == entrySize ? LFN_END : 0); + for (j = 0; j < 13; j++) { + if (lfn [(i - 2) * 13 + j] == '\0') { + if ((j > 1) && (lfn [(i - 2) * 13 + (j-1)] == '\0')) { + u16_to_u8array (lfnEntry, LFN_offset_table[j], 0xffff); // Padding + } else { + u16_to_u8array (lfnEntry, LFN_offset_table[j], 0x0000); // Terminating null character + } + } else { + u16_to_u8array (lfnEntry, LFN_offset_table[j], lfn [(i - 2) * 13 + j]); + } + } - // Write out directory entry - curEntryPos = entry->dataStart; + lfnEntry[LFN_offset_checkSum] = aliasCheckSum; + lfnEntry[LFN_offset_flag] = ATTRIB_LFN; + lfnEntry[LFN_offset_reserved1] = 0; + u16_to_u8array (lfnEntry, LFN_offset_reserved2, 0); + _FAT_cache_writePartialSector (partition->cache, lfnEntry, _FAT_fat_clusterToSector(partition, curEntryPos.cluster) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + } else { + // Alias & file data + _FAT_cache_writePartialSector (partition->cache, entry->entryData, _FAT_fat_clusterToSector(partition, curEntryPos.cluster) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + } + } + } - { - // lfn is only pushed onto the stack here, reducing overall stack usage - ucs2_t lfn[MAX_LFN_LENGTH] = {0}; - _FAT_directory_mbstoucs2 (lfn, entry->filename, MAX_LFN_LENGTH); - - for (entryStillValid = true, i = entrySize; entryStillValid && i > 0; - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &curEntryPos, false), -- i ) { - if (i > 1) { - // Long filename entry - lfnEntry[LFN_offset_ordinal] = (i - 1) | ((size_t)i == entrySize ? LFN_END : 0); - for (j = 0; j < 13; j++) { - if (lfn [(i - 2) * 13 + j] == '\0') { - if ((j > 1) && (lfn [(i - 2) * 13 + (j-1)] == '\0')) { - u16_to_u8array (lfnEntry, LFN_offset_table[j], 0xffff); // Padding - } else { - u16_to_u8array (lfnEntry, LFN_offset_table[j], 0x0000); // Terminating null character - } - } else { - u16_to_u8array (lfnEntry, LFN_offset_table[j], lfn [(i - 2) * 13 + j]); - } - } - - lfnEntry[LFN_offset_checkSum] = aliasCheckSum; - lfnEntry[LFN_offset_flag] = ATTRIB_LFN; - lfnEntry[LFN_offset_reserved1] = 0; - u16_to_u8array (lfnEntry, LFN_offset_reserved2, 0); - _FAT_cache_writePartialSector (partition->cache, lfnEntry, _FAT_fat_clusterToSector(partition, curEntryPos.cluster) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - } else { - // Alias & file data - _FAT_cache_writePartialSector (partition->cache, entry->entryData, _FAT_fat_clusterToSector(partition, curEntryPos.cluster) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - } - } - } - - return true; + return true; } bool _FAT_directory_chdir (PARTITION* partition, const char* path) { - DIR_ENTRY entry; + DIR_ENTRY entry; - if (!_FAT_directory_entryFromPath (partition, &entry, path, NULL)) { - return false; - } + if (!_FAT_directory_entryFromPath (partition, &entry, path, NULL)) { + return false; + } - if (!(entry.entryData[DIR_ENTRY_attributes] & ATTRIB_DIR)) { - return false; - } + if (!(entry.entryData[DIR_ENTRY_attributes] & ATTRIB_DIR)) { + return false; + } - partition->cwdCluster = _FAT_directory_entryGetCluster (partition, entry.entryData); + partition->cwdCluster = _FAT_directory_entryGetCluster (partition, entry.entryData); - return true; + return true; } void _FAT_directory_entryStat (PARTITION* partition, DIR_ENTRY* entry, struct stat *st) { - // Fill in the stat struct - // Some of the values are faked for the sake of compatibility - st->st_dev = _FAT_disc_hostType(partition->disc); // The device is the 32bit ioType value - st->st_ino = (ino_t)(_FAT_directory_entryGetCluster(partition, entry->entryData)); // The file serial number is the start cluster - st->st_mode = (_FAT_directory_isDirectory(entry) ? S_IFDIR : S_IFREG) | - (S_IRUSR | S_IRGRP | S_IROTH) | - (_FAT_directory_isWritable (entry) ? (S_IWUSR | S_IWGRP | S_IWOTH) : 0); // Mode bits based on dirEntry ATTRIB byte - st->st_nlink = 1; // Always one hard link on a FAT file - st->st_uid = 1; // Faked for FAT - st->st_gid = 2; // Faked for FAT - st->st_rdev = st->st_dev; - st->st_size = u8array_to_u32 (entry->entryData, DIR_ENTRY_fileSize); // File size - st->st_atime = _FAT_filetime_to_time_t ( - 0, - u8array_to_u16 (entry->entryData, DIR_ENTRY_aDate) - ); - st->st_spare1 = 0; - st->st_mtime = _FAT_filetime_to_time_t ( - u8array_to_u16 (entry->entryData, DIR_ENTRY_mTime), - u8array_to_u16 (entry->entryData, DIR_ENTRY_mDate) - ); - st->st_spare2 = 0; - st->st_ctime = _FAT_filetime_to_time_t ( - u8array_to_u16 (entry->entryData, DIR_ENTRY_cTime), - u8array_to_u16 (entry->entryData, DIR_ENTRY_cDate) - ); - st->st_spare3 = 0; - st->st_blksize = BYTES_PER_READ; // Prefered file I/O block size - st->st_blocks = (st->st_size + BYTES_PER_READ - 1) / BYTES_PER_READ; // File size in blocks - st->st_spare4[0] = 0; - st->st_spare4[1] = 0; + // Fill in the stat struct + // Some of the values are faked for the sake of compatibility + st->st_dev = _FAT_disc_hostType(partition->disc); // The device is the 32bit ioType value + st->st_ino = (ino_t)(_FAT_directory_entryGetCluster(partition, entry->entryData)); // The file serial number is the start cluster + st->st_mode = (_FAT_directory_isDirectory(entry) ? S_IFDIR : S_IFREG) | + (S_IRUSR | S_IRGRP | S_IROTH) | + (_FAT_directory_isWritable (entry) ? (S_IWUSR | S_IWGRP | S_IWOTH) : 0); // Mode bits based on dirEntry ATTRIB byte + st->st_nlink = 1; // Always one hard link on a FAT file + st->st_uid = 1; // Faked for FAT + st->st_gid = 2; // Faked for FAT + st->st_rdev = st->st_dev; + st->st_size = u8array_to_u32 (entry->entryData, DIR_ENTRY_fileSize); // File size + st->st_atime = _FAT_filetime_to_time_t ( + 0, + u8array_to_u16 (entry->entryData, DIR_ENTRY_aDate) + ); + st->st_spare1 = 0; + st->st_mtime = _FAT_filetime_to_time_t ( + u8array_to_u16 (entry->entryData, DIR_ENTRY_mTime), + u8array_to_u16 (entry->entryData, DIR_ENTRY_mDate) + ); + st->st_spare2 = 0; + st->st_ctime = _FAT_filetime_to_time_t ( + u8array_to_u16 (entry->entryData, DIR_ENTRY_cTime), + u8array_to_u16 (entry->entryData, DIR_ENTRY_cDate) + ); + st->st_spare3 = 0; + st->st_blksize = BYTES_PER_READ; // Prefered file I/O block size + st->st_blocks = (st->st_size + BYTES_PER_READ - 1) / BYTES_PER_READ; // File size in blocks + st->st_spare4[0] = 0; + st->st_spare4[1] = 0; } diff --git a/source/libfat/directory.h b/source/libfat/directory.h index 89821d42..02bd82ff 100644 --- a/source/libfat/directory.h +++ b/source/libfat/directory.h @@ -60,49 +60,49 @@ typedef enum {FT_DIRECTORY, FT_FILE} FILE_TYPE; typedef struct { - uint32_t cluster; - sec_t sector; - int32_t offset; + uint32_t cluster; + sec_t sector; + int32_t offset; } DIR_ENTRY_POSITION; typedef struct { - uint8_t entryData[DIR_ENTRY_DATA_SIZE]; - DIR_ENTRY_POSITION dataStart; // Points to the start of the LFN entries of a file, or the alias for no LFN - DIR_ENTRY_POSITION dataEnd; // Always points to the file/directory's alias entry - char filename[MAX_FILENAME_LENGTH]; + uint8_t entryData[DIR_ENTRY_DATA_SIZE]; + DIR_ENTRY_POSITION dataStart; // Points to the start of the LFN entries of a file, or the alias for no LFN + DIR_ENTRY_POSITION dataEnd; // Always points to the file/directory's alias entry + char filename[MAX_FILENAME_LENGTH]; } DIR_ENTRY; // Directory entry offsets enum DIR_ENTRY_offset { - DIR_ENTRY_name = 0x00, - DIR_ENTRY_extension = 0x08, - DIR_ENTRY_attributes = 0x0B, - DIR_ENTRY_reserved = 0x0C, - DIR_ENTRY_cTime_ms = 0x0D, - DIR_ENTRY_cTime = 0x0E, - DIR_ENTRY_cDate = 0x10, - DIR_ENTRY_aDate = 0x12, - DIR_ENTRY_clusterHigh = 0x14, - DIR_ENTRY_mTime = 0x16, - DIR_ENTRY_mDate = 0x18, - DIR_ENTRY_cluster = 0x1A, - DIR_ENTRY_fileSize = 0x1C + DIR_ENTRY_name = 0x00, + DIR_ENTRY_extension = 0x08, + DIR_ENTRY_attributes = 0x0B, + DIR_ENTRY_reserved = 0x0C, + DIR_ENTRY_cTime_ms = 0x0D, + DIR_ENTRY_cTime = 0x0E, + DIR_ENTRY_cDate = 0x10, + DIR_ENTRY_aDate = 0x12, + DIR_ENTRY_clusterHigh = 0x14, + DIR_ENTRY_mTime = 0x16, + DIR_ENTRY_mDate = 0x18, + DIR_ENTRY_cluster = 0x1A, + DIR_ENTRY_fileSize = 0x1C }; /* Returns true if the file specified by entry is a directory */ static inline bool _FAT_directory_isDirectory (DIR_ENTRY* entry) { - return ((entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) != 0); + return ((entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) != 0); } static inline bool _FAT_directory_isWritable (DIR_ENTRY* entry) { - return ((entry->entryData[DIR_ENTRY_attributes] & ATTRIB_RO) == 0); + return ((entry->entryData[DIR_ENTRY_attributes] & ATTRIB_RO) == 0); } static inline bool _FAT_directory_isDot (DIR_ENTRY* entry) { - return ((entry->filename[0] == '.') && ((entry->filename[1] == '\0') || - ((entry->filename[1] == '.') && entry->filename[2] == '\0'))); + return ((entry->filename[0] == '.') && ((entry->filename[1] == '\0') || + ((entry->filename[1] == '.') && entry->filename[2] == '\0'))); } /* diff --git a/source/libfat/disc_fat.c b/source/libfat/disc_fat.c index afd62ece..f6753d7a 100644 --- a/source/libfat/disc_fat.c +++ b/source/libfat/disc_fat.c @@ -44,24 +44,24 @@ The list is terminated by a NULL/NULL entry. #include static const DISC_INTERFACE* get_io_wiisd (void) { - return &__io_wiisd; + return &__io_wiisd; } static const DISC_INTERFACE* get_io_usbstorage (void) { - return &__io_usbstorage; + return &__io_usbstorage; } static const DISC_INTERFACE* get_io_gcsda (void) { - return &__io_gcsda; + return &__io_gcsda; } static const DISC_INTERFACE* get_io_gcsdb (void) { - return &__io_gcsdb; + return &__io_gcsdb; } const INTERFACE_ID _FAT_disc_interfaces[] = { - {"sd", get_io_wiisd}, - {"usb", get_io_usbstorage}, - {"carda", get_io_gcsda}, - {"cardb", get_io_gcsdb}, - {NULL, NULL} + {"sd", get_io_wiisd}, + {"usb", get_io_usbstorage}, + {"carda", get_io_gcsda}, + {"cardb", get_io_gcsdb}, + {NULL, NULL} }; diff --git a/source/libfat/disc_fat.h b/source/libfat/disc_fat.h index 0e31acaf..14a323b2 100644 --- a/source/libfat/disc_fat.h +++ b/source/libfat/disc_fat.h @@ -36,8 +36,8 @@ A list of all default devices to try at startup, terminated by a {NULL,NULL} entry. */ typedef struct { - const char* name; - const DISC_INTERFACE* (*getInterface)(void); + const char* name; + const DISC_INTERFACE* (*getInterface)(void); } INTERFACE_ID; extern const INTERFACE_ID _FAT_disc_interfaces[]; @@ -46,7 +46,7 @@ Check if a disc is inserted Return true if a disc is inserted and ready, false otherwise */ static inline bool _FAT_disc_isInserted (const DISC_INTERFACE* disc) { - return disc->isInserted(); + return disc->isInserted(); } /* @@ -57,7 +57,7 @@ sector is 0 or greater buffer is a pointer to the memory to fill */ static inline bool _FAT_disc_readSectors (const DISC_INTERFACE* disc, sec_t sector, sec_t numSectors, void* buffer) { - return disc->readSectors (sector, numSectors, buffer); + return disc->readSectors (sector, numSectors, buffer); } /* @@ -68,21 +68,21 @@ sector is 0 or greater buffer is a pointer to the memory to read from */ static inline bool _FAT_disc_writeSectors (const DISC_INTERFACE* disc, sec_t sector, sec_t numSectors, const void* buffer) { - return disc->writeSectors (sector, numSectors, buffer); + return disc->writeSectors (sector, numSectors, buffer); } /* Reset the card back to a ready state */ static inline bool _FAT_disc_clearStatus (const DISC_INTERFACE* disc) { - return disc->clearStatus(); + return disc->clearStatus(); } /* Initialise the disc to a state ready for data reading or writing */ static inline bool _FAT_disc_startup (const DISC_INTERFACE* disc) { - return disc->startup(); + return disc->startup(); } /* @@ -90,21 +90,21 @@ Put the disc in a state ready for power down. Complete any pending writes and disable the disc if necessary */ static inline bool _FAT_disc_shutdown (const DISC_INTERFACE* disc) { - return disc->shutdown(); + return disc->shutdown(); } /* Return a 32 bit value unique to each type of interface */ static inline uint32_t _FAT_disc_hostType (const DISC_INTERFACE* disc) { - return disc->ioType; + return disc->ioType; } /* Return a 32 bit value that specifies the capabilities of the disc */ static inline uint32_t _FAT_disc_features (const DISC_INTERFACE* disc) { - return disc->features; + return disc->features; } #endif // _DISC_H diff --git a/source/libfat/fat.h b/source/libfat/fat.h index cd47e85e..d7b11176 100644 --- a/source/libfat/fat.h +++ b/source/libfat/fat.h @@ -37,41 +37,41 @@ extern "C" { #include #include - /* - Initialise any inserted block-devices. - Add the fat device driver to the devoptab, making it available for standard file functions. - cacheSize: The number of pages to allocate for each inserted block-device - setAsDefaultDevice: if true, make this the default device driver for file operations - */ - extern bool fatInit (uint32_t cacheSize, bool setAsDefaultDevice); +/* +Initialise any inserted block-devices. +Add the fat device driver to the devoptab, making it available for standard file functions. +cacheSize: The number of pages to allocate for each inserted block-device +setAsDefaultDevice: if true, make this the default device driver for file operations +*/ +extern bool fatInit (uint32_t cacheSize, bool setAsDefaultDevice); - /* - Calls fatInit with setAsDefaultDevice = true and cacheSize optimised for the host system. - */ - extern bool fatInitDefault (void); +/* +Calls fatInit with setAsDefaultDevice = true and cacheSize optimised for the host system. +*/ +extern bool fatInitDefault (void); - /* - Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". - You can then access the filesystem using "name:/". - This will mount the active partition or the first valid partition on the disc, - and will use a cache size optimized for the host system. - */ - extern bool fatMountSimple (const char* name, const DISC_INTERFACE* interface); +/* +Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". +You can then access the filesystem using "name:/". +This will mount the active partition or the first valid partition on the disc, +and will use a cache size optimized for the host system. +*/ +extern bool fatMountSimple (const char* name, const DISC_INTERFACE* interface); - /* - Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". - You can then access the filesystem using "name:/". - If startSector = 0, it will mount the active partition of the first valid partition on - the disc. Otherwise it will try to mount the partition starting at startSector. - cacheSize specifies the number of pages to allocate for the cache. - This will not startup the disc, so you need to call interface->startup(); first. - */ - extern bool fatMount (const char* name, const DISC_INTERFACE* interface, sec_t startSector, uint32_t cacheSize, uint32_t SectorsPerPage); - /* - Unmount the partition specified by name. - If there are open files, it will attempt to synchronise them to disc. - */ - extern void fatUnmount (const char* name); +/* +Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". +You can then access the filesystem using "name:/". +If startSector = 0, it will mount the active partition of the first valid partition on +the disc. Otherwise it will try to mount the partition starting at startSector. +cacheSize specifies the number of pages to allocate for the cache. +This will not startup the disc, so you need to call interface->startup(); first. +*/ +extern bool fatMount (const char* name, const DISC_INTERFACE* interface, sec_t startSector, uint32_t cacheSize, uint32_t SectorsPerPage); +/* +Unmount the partition specified by name. +If there are open files, it will attempt to synchronise them to disc. +*/ +extern void fatUnmount (const char* name); #ifdef __cplusplus } diff --git a/source/libfat/fat_cache.c b/source/libfat/fat_cache.c index 47b9acbe..422915b8 100644 --- a/source/libfat/fat_cache.c +++ b/source/libfat/fat_cache.c @@ -47,327 +47,320 @@ #define CACHE_FREE UINT_MAX CACHE* _FAT_cache_constructor (unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition) { - CACHE* cache; - unsigned int i; - CACHE_ENTRY* cacheEntries; + CACHE* cache; + unsigned int i; + CACHE_ENTRY* cacheEntries; - if (numberOfPages < 2) { - numberOfPages = 2; - } + if (numberOfPages < 2) { + numberOfPages = 2; + } - if (sectorsPerPage < 8) { - sectorsPerPage = 8; - } + if (sectorsPerPage < 8) { + sectorsPerPage = 8; + } - cache = (CACHE*) _FAT_mem_allocate (sizeof(CACHE)); - if (cache == NULL) { - return NULL; - } + cache = (CACHE*) _FAT_mem_allocate (sizeof(CACHE)); + if (cache == NULL) { + return NULL; + } - cache->disc = discInterface; - cache->endOfPartition = endOfPartition; - cache->numberOfPages = numberOfPages; - cache->sectorsPerPage = sectorsPerPage; + cache->disc = discInterface; + cache->endOfPartition = endOfPartition; + cache->numberOfPages = numberOfPages; + cache->sectorsPerPage = sectorsPerPage; - cacheEntries = (CACHE_ENTRY*) _FAT_mem_allocate ( sizeof(CACHE_ENTRY) * numberOfPages); - if (cacheEntries == NULL) { - _FAT_mem_free (cache); - return NULL; - } + cacheEntries = (CACHE_ENTRY*) _FAT_mem_allocate ( sizeof(CACHE_ENTRY) * numberOfPages); + if (cacheEntries == NULL) { + _FAT_mem_free (cache); + return NULL; + } - for (i = 0; i < numberOfPages; i++) { - cacheEntries[i].sector = CACHE_FREE; - cacheEntries[i].count = 0; - cacheEntries[i].last_access = 0; - cacheEntries[i].dirty = false; - cacheEntries[i].cache = (uint8_t*) _FAT_mem_align ( sectorsPerPage * BYTES_PER_READ ); - } + for (i = 0; i < numberOfPages; i++) { + cacheEntries[i].sector = CACHE_FREE; + cacheEntries[i].count = 0; + cacheEntries[i].last_access = 0; + cacheEntries[i].dirty = false; + cacheEntries[i].cache = (uint8_t*) _FAT_mem_align ( sectorsPerPage * BYTES_PER_READ ); + } - cache->cacheEntries = cacheEntries; + cache->cacheEntries = cacheEntries; - return cache; + return cache; } void _FAT_cache_destructor (CACHE* cache) { - unsigned int i; - // Clear out cache before destroying it - _FAT_cache_flush(cache); + unsigned int i; + // Clear out cache before destroying it + _FAT_cache_flush(cache); - // Free memory in reverse allocation order - for (i = 0; i < cache->numberOfPages; i++) { - _FAT_mem_free (cache->cacheEntries[i].cache); - } - _FAT_mem_free (cache->cacheEntries); - _FAT_mem_free (cache); + // Free memory in reverse allocation order + for (i = 0; i < cache->numberOfPages; i++) { + _FAT_mem_free (cache->cacheEntries[i].cache); + } + _FAT_mem_free (cache->cacheEntries); + _FAT_mem_free (cache); } static u32 accessCounter = 0; -static u32 accessTime() { - accessCounter++; - return accessCounter; +static u32 accessTime(){ + accessCounter++; + return accessCounter; } -static CACHE_ENTRY* _FAT_cache_getPage(CACHE *cache,sec_t sector) { - unsigned int i; - CACHE_ENTRY* cacheEntries = cache->cacheEntries; - unsigned int numberOfPages = cache->numberOfPages; - unsigned int sectorsPerPage = cache->sectorsPerPage; +static CACHE_ENTRY* _FAT_cache_getPage(CACHE *cache,sec_t sector) +{ + unsigned int i; + CACHE_ENTRY* cacheEntries = cache->cacheEntries; + unsigned int numberOfPages = cache->numberOfPages; + unsigned int sectorsPerPage = cache->sectorsPerPage; - bool foundFree = false; - unsigned int oldUsed = 0; - unsigned int oldAccess = UINT_MAX; + bool foundFree = false; + unsigned int oldUsed = 0; + unsigned int oldAccess = UINT_MAX; - for (i=0;i=cacheEntries[i].sector && sector<(cacheEntries[i].sector + cacheEntries[i].count)) { - cacheEntries[i].last_access = accessTime(); - return &(cacheEntries[i]); - } + for(i=0;i=cacheEntries[i].sector && sector<(cacheEntries[i].sector + cacheEntries[i].count)) { + cacheEntries[i].last_access = accessTime(); + return &(cacheEntries[i]); + } - if (foundFree==false && (cacheEntries[i].sector==CACHE_FREE || cacheEntries[i].last_accessdisc,cacheEntries[oldUsed].sector,cacheEntries[oldUsed].count,cacheEntries[oldUsed].cache)) return NULL; - cacheEntries[oldUsed].dirty = false; - } + if(foundFree==false && cacheEntries[oldUsed].dirty==true) { + if(!_FAT_disc_writeSectors(cache->disc,cacheEntries[oldUsed].sector,cacheEntries[oldUsed].count,cacheEntries[oldUsed].cache)) return NULL; + cacheEntries[oldUsed].dirty = false; + } - sector = (sector/sectorsPerPage)*sectorsPerPage; // align base sector to page size - sec_t next_page = sector + sectorsPerPage; - if (next_page > cache->endOfPartition) next_page = cache->endOfPartition; + sector = (sector/sectorsPerPage)*sectorsPerPage; // align base sector to page size + sec_t next_page = sector + sectorsPerPage; + if(next_page > cache->endOfPartition) next_page = cache->endOfPartition; - if (!_FAT_disc_readSectors(cache->disc,sector,next_page-sector,cacheEntries[oldUsed].cache)) return NULL; + if(!_FAT_disc_readSectors(cache->disc,sector,next_page-sector,cacheEntries[oldUsed].cache)) return NULL; - cacheEntries[oldUsed].sector = sector; - cacheEntries[oldUsed].count = next_page-sector; - cacheEntries[oldUsed].last_access = accessTime(); + cacheEntries[oldUsed].sector = sector; + cacheEntries[oldUsed].count = next_page-sector; + cacheEntries[oldUsed].last_access = accessTime(); - return &(cacheEntries[oldUsed]); + return &(cacheEntries[oldUsed]); } -bool _FAT_cache_readSectors(CACHE *cache,sec_t sector,sec_t numSectors,void *buffer) { - sec_t sec; - sec_t secs_to_read; - CACHE_ENTRY *entry; - uint8_t *dest = buffer; +bool _FAT_cache_readSectors(CACHE *cache,sec_t sector,sec_t numSectors,void *buffer) +{ + sec_t sec; + sec_t secs_to_read; + CACHE_ENTRY *entry; + uint8_t *dest = buffer; - while (numSectors>0) { - entry = _FAT_cache_getPage(cache,sector); - if (entry==NULL) return false; + while(numSectors>0) { + entry = _FAT_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - secs_to_read = entry->count - sec; - if (secs_to_read>numSectors) secs_to_read = numSectors; + sec = sector - entry->sector; + secs_to_read = entry->count - sec; + if(secs_to_read>numSectors) secs_to_read = numSectors; - memcpy(dest,entry->cache + (sec*BYTES_PER_READ),(secs_to_read*BYTES_PER_READ)); + memcpy(dest,entry->cache + (sec*BYTES_PER_READ),(secs_to_read*BYTES_PER_READ)); - dest += (secs_to_read*BYTES_PER_READ); - sector += secs_to_read; - numSectors -= secs_to_read; - } + dest += (secs_to_read*BYTES_PER_READ); + sector += secs_to_read; + numSectors -= secs_to_read; + } - return true; + return true; } /* Reads some data from a cache page, determined by the sector number */ -bool _FAT_cache_readPartialSector (CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size) { - sec_t sec; - CACHE_ENTRY *entry; +bool _FAT_cache_readPartialSector (CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size) +{ + sec_t sec; + CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if (offset + size > BYTES_PER_READ) return false; - entry = _FAT_cache_getPage(cache,sector); - if (entry==NULL) return false; + entry = _FAT_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - memcpy(buffer,entry->cache + ((sec*BYTES_PER_READ) + offset),size); + sec = sector - entry->sector; + memcpy(buffer,entry->cache + ((sec*BYTES_PER_READ) + offset),size); - return true; + return true; } bool _FAT_cache_readLittleEndianValue (CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes) { - uint8_t buf[4]; - if (!_FAT_cache_readPartialSector(cache, buf, sector, offset, num_bytes)) return false; + uint8_t buf[4]; + if (!_FAT_cache_readPartialSector(cache, buf, sector, offset, num_bytes)) return false; - switch (num_bytes) { - case 1: - *value = buf[0]; - break; - case 2: - *value = u8array_to_u16(buf,0); - break; - case 4: - *value = u8array_to_u32(buf,0); - break; - default: - return false; - } - return true; + switch(num_bytes) { + case 1: *value = buf[0]; break; + case 2: *value = u8array_to_u16(buf,0); break; + case 4: *value = u8array_to_u32(buf,0); break; + default: return false; + } + return true; } /* Writes some data to a cache page, making sure it is loaded into memory first. */ -bool _FAT_cache_writePartialSector (CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) { - sec_t sec; - CACHE_ENTRY *entry; +bool _FAT_cache_writePartialSector (CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) +{ + sec_t sec; + CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if (offset + size > BYTES_PER_READ) return false; - entry = _FAT_cache_getPage(cache,sector); - if (entry==NULL) return false; + entry = _FAT_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); + sec = sector - entry->sector; + memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); - entry->dirty = true; - return true; + entry->dirty = true; + return true; } bool _FAT_cache_writeLittleEndianValue (CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, int size) { - uint8_t buf[4] = {0, 0, 0, 0}; + uint8_t buf[4] = {0, 0, 0, 0}; - switch (size) { - case 1: - buf[0] = value; - break; - case 2: - u16_to_u8array(buf, 0, value); - break; - case 4: - u32_to_u8array(buf, 0, value); - break; - default: - return false; - } + switch(size) { + case 1: buf[0] = value; break; + case 2: u16_to_u8array(buf, 0, value); break; + case 4: u32_to_u8array(buf, 0, value); break; + default: return false; + } - return _FAT_cache_writePartialSector(cache, buf, sector, offset, size); + return _FAT_cache_writePartialSector(cache, buf, sector, offset, size); } /* Writes some data to a cache page, zeroing out the page first */ -bool _FAT_cache_eraseWritePartialSector (CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) { - sec_t sec; - CACHE_ENTRY *entry; +bool _FAT_cache_eraseWritePartialSector (CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) +{ + sec_t sec; + CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if (offset + size > BYTES_PER_READ) return false; - entry = _FAT_cache_getPage(cache,sector); - if (entry==NULL) return false; + entry = _FAT_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - memset(entry->cache + (sec*BYTES_PER_READ),0,BYTES_PER_READ); - memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); + sec = sector - entry->sector; + memset(entry->cache + (sec*BYTES_PER_READ),0,BYTES_PER_READ); + memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); - entry->dirty = true; - return true; + entry->dirty = true; + return true; } static CACHE_ENTRY* _FAT_cache_findPage(CACHE *cache, sec_t sector, sec_t count) { - unsigned int i; - CACHE_ENTRY* cacheEntries = cache->cacheEntries; - unsigned int numberOfPages = cache->numberOfPages; - CACHE_ENTRY *entry = NULL; - sec_t lowest = UINT_MAX; + unsigned int i; + CACHE_ENTRY* cacheEntries = cache->cacheEntries; + unsigned int numberOfPages = cache->numberOfPages; + CACHE_ENTRY *entry = NULL; + sec_t lowest = UINT_MAX; - for (i=0;i cacheEntries[i].sector) { - intersect = sector - cacheEntries[i].sector < cacheEntries[i].count; - } else { - intersect = cacheEntries[i].sector - sector < count; - } + for(i=0;i cacheEntries[i].sector) { + intersect = sector - cacheEntries[i].sector < cacheEntries[i].count; + } else { + intersect = cacheEntries[i].sector - sector < count; + } - if ( intersect && (cacheEntries[i].sector < lowest)) { - lowest = cacheEntries[i].sector; - entry = &cacheEntries[i]; - } - } - } + if ( intersect && (cacheEntries[i].sector < lowest)) { + lowest = cacheEntries[i].sector; + entry = &cacheEntries[i]; + } + } + } - return entry; + return entry; } -bool _FAT_cache_writeSectors (CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer) { - sec_t sec; - sec_t secs_to_write; - CACHE_ENTRY* entry; - const uint8_t *src = buffer; +bool _FAT_cache_writeSectors (CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer) +{ + sec_t sec; + sec_t secs_to_write; + CACHE_ENTRY* entry; + const uint8_t *src = buffer; - while (numSectors>0) { - entry = _FAT_cache_findPage(cache,sector,numSectors); + while(numSectors>0) + { + entry = _FAT_cache_findPage(cache,sector,numSectors); - if (entry!=NULL) { + if(entry!=NULL) { - if ( entry->sector > sector) { + if ( entry->sector > sector) { - secs_to_write = entry->sector - sector; + secs_to_write = entry->sector - sector; - _FAT_disc_writeSectors(cache->disc,sector,secs_to_write,src); - src += (secs_to_write*BYTES_PER_READ); - sector += secs_to_write; - numSectors -= secs_to_write; - } + _FAT_disc_writeSectors(cache->disc,sector,secs_to_write,src); + src += (secs_to_write*BYTES_PER_READ); + sector += secs_to_write; + numSectors -= secs_to_write; + } - sec = sector - entry->sector; - secs_to_write = entry->count - sec; + sec = sector - entry->sector; + secs_to_write = entry->count - sec; - if (secs_to_write>numSectors) secs_to_write = numSectors; + if(secs_to_write>numSectors) secs_to_write = numSectors; - memcpy(entry->cache + (sec*BYTES_PER_READ),src,(secs_to_write*BYTES_PER_READ)); + memcpy(entry->cache + (sec*BYTES_PER_READ),src,(secs_to_write*BYTES_PER_READ)); - src += (secs_to_write*BYTES_PER_READ); - sector += secs_to_write; - numSectors -= secs_to_write; + src += (secs_to_write*BYTES_PER_READ); + sector += secs_to_write; + numSectors -= secs_to_write; - entry->dirty = true; + entry->dirty = true; - } else { - _FAT_disc_writeSectors(cache->disc,sector,numSectors,src); - numSectors=0; - } - } - return true; + } else { + _FAT_disc_writeSectors(cache->disc,sector,numSectors,src); + numSectors=0; + } + } + return true; } /* Flushes all dirty pages to disc, clearing the dirty flag. */ bool _FAT_cache_flush (CACHE* cache) { - unsigned int i; + unsigned int i; - for (i = 0; i < cache->numberOfPages; i++) { - if (cache->cacheEntries[i].dirty) { - if (!_FAT_disc_writeSectors (cache->disc, cache->cacheEntries[i].sector, cache->cacheEntries[i].count, cache->cacheEntries[i].cache)) { - return false; - } - } - cache->cacheEntries[i].dirty = false; - } + for (i = 0; i < cache->numberOfPages; i++) { + if (cache->cacheEntries[i].dirty) { + if (!_FAT_disc_writeSectors (cache->disc, cache->cacheEntries[i].sector, cache->cacheEntries[i].count, cache->cacheEntries[i].cache)) { + return false; + } + } + cache->cacheEntries[i].dirty = false; + } - return true; + return true; } void _FAT_cache_invalidate (CACHE* cache) { - unsigned int i; - _FAT_cache_flush(cache); - for (i = 0; i < cache->numberOfPages; i++) { - cache->cacheEntries[i].sector = CACHE_FREE; - cache->cacheEntries[i].last_access = 0; - cache->cacheEntries[i].count = 0; - cache->cacheEntries[i].dirty = false; - } + unsigned int i; + _FAT_cache_flush(cache); + for (i = 0; i < cache->numberOfPages; i++) { + cache->cacheEntries[i].sector = CACHE_FREE; + cache->cacheEntries[i].last_access = 0; + cache->cacheEntries[i].count = 0; + cache->cacheEntries[i].dirty = false; + } } diff --git a/source/libfat/fat_cache.h b/source/libfat/fat_cache.h index f966465e..ce754c6d 100644 --- a/source/libfat/fat_cache.h +++ b/source/libfat/fat_cache.h @@ -43,19 +43,19 @@ #define CACHE_PAGE_SIZE (BYTES_PER_READ * PAGE_SECTORS) typedef struct { - sec_t sector; - unsigned int count; - unsigned int last_access; - bool dirty; - uint8_t* cache; + sec_t sector; + unsigned int count; + unsigned int last_access; + bool dirty; + uint8_t* cache; } CACHE_ENTRY; typedef struct { - const DISC_INTERFACE* disc; - sec_t endOfPartition; - unsigned int numberOfPages; - unsigned int sectorsPerPage; - CACHE_ENTRY* cacheEntries; + const DISC_INTERFACE* disc; + sec_t endOfPartition; + unsigned int numberOfPages; + unsigned int sectorsPerPage; + CACHE_ENTRY* cacheEntries; } CACHE; /* @@ -100,14 +100,14 @@ bool _FAT_cache_readSectors (CACHE* cache, sec_t sector, sec_t numSectors, void* Read a full sector from the cache */ static inline bool _FAT_cache_readSector (CACHE* cache, void* buffer, sec_t sector) { - return _FAT_cache_readPartialSector (cache, buffer, sector, 0, BYTES_PER_READ); + return _FAT_cache_readPartialSector (cache, buffer, sector, 0, BYTES_PER_READ); } /* Write a full sector to the cache */ static inline bool _FAT_cache_writeSector (CACHE* cache, const void* buffer, sec_t sector) { - return _FAT_cache_writePartialSector (cache, buffer, sector, 0, BYTES_PER_READ); + return _FAT_cache_writePartialSector (cache, buffer, sector, 0, BYTES_PER_READ); } bool _FAT_cache_writeSectors (CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer); diff --git a/source/libfat/fatdir.c b/source/libfat/fatdir.c index 21443706..5a555e38 100644 --- a/source/libfat/fatdir.c +++ b/source/libfat/fatdir.c @@ -1,11 +1,11 @@ /* fatdir.c - - Functions used by the newlib disc stubs to interface with + + Functions used by the newlib disc stubs to interface with this library Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -46,564 +46,565 @@ int _FAT_stat_r (struct _reent *r, const char *path, struct stat *st) { - PARTITION* partition = NULL; - DIR_ENTRY dirEntry; + PARTITION* partition = NULL; + DIR_ENTRY dirEntry; + + // Get the partition this file is on + partition = _FAT_partition_getPartitionFromPath (path); + if (partition == NULL) { + r->_errno = ENODEV; + return -1; + } - // Get the partition this file is on - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + // Move the path pointer to the start of the actual path + if (strchr (path, ':') != NULL) { + path = strchr (path, ':') + 1; + } + if (strchr (path, ':') != NULL) { + r->_errno = EINVAL; + return -1; + } - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } + _FAT_lock(&partition->lock); - _FAT_lock(&partition->lock); - - // Search for the file on the disc - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - - // Fill in the stat struct - _FAT_directory_entryStat (partition, &dirEntry, st); - - _FAT_unlock(&partition->lock); - return 0; + // Search for the file on the disc + if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, NULL)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOENT; + return -1; + } + + // Fill in the stat struct + _FAT_directory_entryStat (partition, &dirEntry, st); + + _FAT_unlock(&partition->lock); + return 0; } int _FAT_link_r (struct _reent *r, const char *existing, const char *newLink) { - r->_errno = ENOTSUP; - return -1; + r->_errno = ENOTSUP; + return -1; } int _FAT_unlink_r (struct _reent *r, const char *path) { - PARTITION* partition = NULL; - DIR_ENTRY dirEntry; - DIR_ENTRY dirContents; - uint32_t cluster; - bool nextEntry; - bool errorOccured = false; + PARTITION* partition = NULL; + DIR_ENTRY dirEntry; + DIR_ENTRY dirContents; + uint32_t cluster; + bool nextEntry; + bool errorOccured = false; + + // Get the partition this directory is on + partition = _FAT_partition_getPartitionFromPath (path); + if (partition == NULL) { + r->_errno = ENODEV; + return -1; + } - // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + // Make sure we aren't trying to write to a read-only disc + if (partition->readOnly) { + r->_errno = EROFS; + return -1; + } - // Make sure we aren't trying to write to a read-only disc - if (partition->readOnly) { - r->_errno = EROFS; - return -1; - } + // Move the path pointer to the start of the actual path + if (strchr (path, ':') != NULL) { + path = strchr (path, ':') + 1; + } + if (strchr (path, ':') != NULL) { + r->_errno = EINVAL; + return -1; + } + + _FAT_lock(&partition->lock); + + // Search for the file on the disc + if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, NULL)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOENT; + return -1; + } + + cluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } + + // If this is a directory, make sure it is empty + if (_FAT_directory_isDirectory (&dirEntry)) { + nextEntry = _FAT_directory_getFirstEntry (partition, &dirContents, cluster); + + while (nextEntry) { + if (!_FAT_directory_isDot (&dirContents)) { + // The directory had something in it that isn't a reference to itself or it's parent + _FAT_unlock(&partition->lock); + r->_errno = EPERM; + return -1; + } + nextEntry = _FAT_directory_getNextEntry (partition, &dirContents); + } + } - _FAT_lock(&partition->lock); + if (_FAT_fat_isValidCluster(partition, cluster)) { + // Remove the cluster chain for this file + if (!_FAT_fat_clearLinks (partition, cluster)) { + r->_errno = EIO; + errorOccured = true; + } + } - // Search for the file on the disc - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - - cluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - - - // If this is a directory, make sure it is empty - if (_FAT_directory_isDirectory (&dirEntry)) { - nextEntry = _FAT_directory_getFirstEntry (partition, &dirContents, cluster); - - while (nextEntry) { - if (!_FAT_directory_isDot (&dirContents)) { - // The directory had something in it that isn't a reference to itself or it's parent - _FAT_unlock(&partition->lock); - r->_errno = EPERM; - return -1; - } - nextEntry = _FAT_directory_getNextEntry (partition, &dirContents); - } - } - - if (_FAT_fat_isValidCluster(partition, cluster)) { - // Remove the cluster chain for this file - if (!_FAT_fat_clearLinks (partition, cluster)) { - r->_errno = EIO; - errorOccured = true; - } - } - - // Remove the directory entry for this file - if (!_FAT_directory_removeEntry (partition, &dirEntry)) { - r->_errno = EIO; - errorOccured = true; - } - - // Flush any sectors in the disc cache - if (!_FAT_cache_flush(partition->cache)) { - r->_errno = EIO; - errorOccured = true; - } - - _FAT_unlock(&partition->lock); - if (errorOccured) { - return -1; - } else { - return 0; - } + // Remove the directory entry for this file + if (!_FAT_directory_removeEntry (partition, &dirEntry)) { + r->_errno = EIO; + errorOccured = true; + } + + // Flush any sectors in the disc cache + if (!_FAT_cache_flush(partition->cache)) { + r->_errno = EIO; + errorOccured = true; + } + + _FAT_unlock(&partition->lock); + if (errorOccured) { + return -1; + } else { + return 0; + } } int _FAT_chdir_r (struct _reent *r, const char *path) { - PARTITION* partition = NULL; + PARTITION* partition = NULL; + + // Get the partition this directory is on + partition = _FAT_partition_getPartitionFromPath (path); + if (partition == NULL) { + r->_errno = ENODEV; + return -1; + } - // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + // Move the path pointer to the start of the actual path + if (strchr (path, ':') != NULL) { + path = strchr (path, ':') + 1; + } + if (strchr (path, ':') != NULL) { + r->_errno = EINVAL; + return -1; + } + + _FAT_lock(&partition->lock); - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } - - _FAT_lock(&partition->lock); - - // Try changing directory - if (_FAT_directory_chdir (partition, path)) { - // Successful - _FAT_unlock(&partition->lock); - return 0; - } else { - // Failed - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } + // Try changing directory + if (_FAT_directory_chdir (partition, path)) { + // Successful + _FAT_unlock(&partition->lock); + return 0; + } else { + // Failed + _FAT_unlock(&partition->lock); + r->_errno = ENOTDIR; + return -1; + } } int _FAT_rename_r (struct _reent *r, const char *oldName, const char *newName) { - PARTITION* partition = NULL; - DIR_ENTRY oldDirEntry; - DIR_ENTRY newDirEntry; - const char *pathEnd; - uint32_t dirCluster; + PARTITION* partition = NULL; + DIR_ENTRY oldDirEntry; + DIR_ENTRY newDirEntry; + const char *pathEnd; + uint32_t dirCluster; + + // Get the partition this directory is on + partition = _FAT_partition_getPartitionFromPath (oldName); + if (partition == NULL) { + r->_errno = ENODEV; + return -1; + } + + _FAT_lock(&partition->lock); + + // Make sure the same partition is used for the old and new names + if (partition != _FAT_partition_getPartitionFromPath (newName)) { + _FAT_unlock(&partition->lock); + r->_errno = EXDEV; + return -1; + } - // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath (oldName); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + // Make sure we aren't trying to write to a read-only disc + if (partition->readOnly) { + _FAT_unlock(&partition->lock); + r->_errno = EROFS; + return -1; + } - _FAT_lock(&partition->lock); + // Move the path pointer to the start of the actual path + if (strchr (oldName, ':') != NULL) { + oldName = strchr (oldName, ':') + 1; + } + if (strchr (oldName, ':') != NULL) { + _FAT_unlock(&partition->lock); + r->_errno = EINVAL; + return -1; + } + if (strchr (newName, ':') != NULL) { + newName = strchr (newName, ':') + 1; + } + if (strchr (newName, ':') != NULL) { + _FAT_unlock(&partition->lock); + r->_errno = EINVAL; + return -1; + } - // Make sure the same partition is used for the old and new names - if (partition != _FAT_partition_getPartitionFromPath (newName)) { - _FAT_unlock(&partition->lock); - r->_errno = EXDEV; - return -1; - } + // Search for the file on the disc + if (!_FAT_directory_entryFromPath (partition, &oldDirEntry, oldName, NULL)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOENT; + return -1; + } + + // Make sure there is no existing file / directory with the new name + if (_FAT_directory_entryFromPath (partition, &newDirEntry, newName, NULL)) { + _FAT_unlock(&partition->lock); + r->_errno = EEXIST; + return -1; + } - // Make sure we aren't trying to write to a read-only disc - if (partition->readOnly) { - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } + // Create the new file entry + // Get the directory it has to go in + pathEnd = strrchr (newName, DIR_SEPARATOR); + if (pathEnd == NULL) { + // No path was specified + dirCluster = partition->cwdCluster; + pathEnd = newName; + } else { + // Path was specified -- get the right dirCluster + // Recycling newDirEntry, since it needs to be recreated anyway + if (!_FAT_directory_entryFromPath (partition, &newDirEntry, newName, pathEnd) || + !_FAT_directory_isDirectory(&newDirEntry)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOTDIR; + return -1; + } + dirCluster = _FAT_directory_entryGetCluster (partition, newDirEntry.entryData); + // Move the pathEnd past the last DIR_SEPARATOR + pathEnd += 1; + } - // Move the path pointer to the start of the actual path - if (strchr (oldName, ':') != NULL) { - oldName = strchr (oldName, ':') + 1; - } - if (strchr (oldName, ':') != NULL) { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } - if (strchr (newName, ':') != NULL) { - newName = strchr (newName, ':') + 1; - } - if (strchr (newName, ':') != NULL) { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } + // Copy the entry data + memcpy (&newDirEntry, &oldDirEntry, sizeof(DIR_ENTRY)); + + // Set the new name + strncpy (newDirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); + + // Write the new entry + if (!_FAT_directory_addEntry (partition, &newDirEntry, dirCluster)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOSPC; + return -1; + } + + // Remove the old entry + if (!_FAT_directory_removeEntry (partition, &oldDirEntry)) { + _FAT_unlock(&partition->lock); + r->_errno = EIO; + return -1; + } + + // Flush any sectors in the disc cache + if (!_FAT_cache_flush (partition->cache)) { + _FAT_unlock(&partition->lock); + r->_errno = EIO; + return -1; + } - // Search for the file on the disc - if (!_FAT_directory_entryFromPath (partition, &oldDirEntry, oldName, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - - // Make sure there is no existing file / directory with the new name - if (_FAT_directory_entryFromPath (partition, &newDirEntry, newName, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = EEXIST; - return -1; - } - - // Create the new file entry - // Get the directory it has to go in - pathEnd = strrchr (newName, DIR_SEPARATOR); - if (pathEnd == NULL) { - // No path was specified - dirCluster = partition->cwdCluster; - pathEnd = newName; - } else { - // Path was specified -- get the right dirCluster - // Recycling newDirEntry, since it needs to be recreated anyway - if (!_FAT_directory_entryFromPath (partition, &newDirEntry, newName, pathEnd) || - !_FAT_directory_isDirectory(&newDirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } - dirCluster = _FAT_directory_entryGetCluster (partition, newDirEntry.entryData); - // Move the pathEnd past the last DIR_SEPARATOR - pathEnd += 1; - } - - // Copy the entry data - memcpy (&newDirEntry, &oldDirEntry, sizeof(DIR_ENTRY)); - - // Set the new name - strncpy (newDirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); - - // Write the new entry - if (!_FAT_directory_addEntry (partition, &newDirEntry, dirCluster)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - - // Remove the old entry - if (!_FAT_directory_removeEntry (partition, &oldDirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } - - // Flush any sectors in the disc cache - if (!_FAT_cache_flush (partition->cache)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } - - _FAT_unlock(&partition->lock); - return 0; + _FAT_unlock(&partition->lock); + return 0; } int _FAT_mkdir_r (struct _reent *r, const char *path, int mode) { - PARTITION* partition = NULL; - bool fileExists; - DIR_ENTRY dirEntry; - const char* pathEnd; - uint32_t parentCluster, dirCluster; - uint8_t newEntryData[DIR_ENTRY_DATA_SIZE]; + PARTITION* partition = NULL; + bool fileExists; + DIR_ENTRY dirEntry; + const char* pathEnd; + uint32_t parentCluster, dirCluster; + uint8_t newEntryData[DIR_ENTRY_DATA_SIZE]; - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + partition = _FAT_partition_getPartitionFromPath (path); + if (partition == NULL) { + r->_errno = ENODEV; + return -1; + } - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } + // Move the path pointer to the start of the actual path + if (strchr (path, ':') != NULL) { + path = strchr (path, ':') + 1; + } + if (strchr (path, ':') != NULL) { + r->_errno = EINVAL; + return -1; + } + + _FAT_lock(&partition->lock); - _FAT_lock(&partition->lock); + // Search for the file/directory on the disc + fileExists = _FAT_directory_entryFromPath (partition, &dirEntry, path, NULL); + + // Make sure it doesn't exist + if (fileExists) { + _FAT_unlock(&partition->lock); + r->_errno = EEXIST; + return -1; + } + + if (partition->readOnly) { + // We can't write to a read-only partition + _FAT_unlock(&partition->lock); + r->_errno = EROFS; + return -1; + } + + // Get the directory it has to go in + pathEnd = strrchr (path, DIR_SEPARATOR); + if (pathEnd == NULL) { + // No path was specified + parentCluster = partition->cwdCluster; + pathEnd = path; + } else { + // Path was specified -- get the right parentCluster + // Recycling dirEntry, since it needs to be recreated anyway + if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, pathEnd) || + !_FAT_directory_isDirectory(&dirEntry)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOTDIR; + return -1; + } + parentCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); + // Move the pathEnd past the last DIR_SEPARATOR + pathEnd += 1; + } + // Create the entry data + strncpy (dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); + memset (dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE); + + // Set the creation time and date + dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC()); + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC()); + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC()); + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC()); + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC()); + + // Set the directory attribute + dirEntry.entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; + + // Get a cluster for the new directory + dirCluster = _FAT_fat_linkFreeClusterCleared (partition, CLUSTER_FREE); + if (!_FAT_fat_isValidCluster(partition, dirCluster)) { + // No space left on disc for the cluster + _FAT_unlock(&partition->lock); + r->_errno = ENOSPC; + return -1; + } + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cluster, dirCluster); + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_clusterHigh, dirCluster >> 16); - // Search for the file/directory on the disc - fileExists = _FAT_directory_entryFromPath (partition, &dirEntry, path, NULL); + // Write the new directory's entry to it's parent + if (!_FAT_directory_addEntry (partition, &dirEntry, parentCluster)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOSPC; + return -1; + } + + // Create the dot entry within the directory + memset (newEntryData, 0, DIR_ENTRY_DATA_SIZE); + memset (newEntryData, ' ', 11); + newEntryData[DIR_ENTRY_name] = '.'; + newEntryData[DIR_ENTRY_attributes] = ATTRIB_DIR; + u16_to_u8array (newEntryData, DIR_ENTRY_cluster, dirCluster); + u16_to_u8array (newEntryData, DIR_ENTRY_clusterHigh, dirCluster >> 16); + + // Write it to the directory, erasing that sector in the process + _FAT_cache_eraseWritePartialSector ( partition->cache, newEntryData, + _FAT_fat_clusterToSector (partition, dirCluster), 0, DIR_ENTRY_DATA_SIZE); + + + // Create the double dot entry within the directory - // Make sure it doesn't exist - if (fileExists) { - _FAT_unlock(&partition->lock); - r->_errno = EEXIST; - return -1; - } + // if ParentDir == Rootdir then ".."" always link to Cluster 0 + if(parentCluster == partition->rootDirCluster) + parentCluster = FAT16_ROOT_DIR_CLUSTER; - if (partition->readOnly) { - // We can't write to a read-only partition - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } + newEntryData[DIR_ENTRY_name + 1] = '.'; + u16_to_u8array (newEntryData, DIR_ENTRY_cluster, parentCluster); + u16_to_u8array (newEntryData, DIR_ENTRY_clusterHigh, parentCluster >> 16); - // Get the directory it has to go in - pathEnd = strrchr (path, DIR_SEPARATOR); - if (pathEnd == NULL) { - // No path was specified - parentCluster = partition->cwdCluster; - pathEnd = path; - } else { - // Path was specified -- get the right parentCluster - // Recycling dirEntry, since it needs to be recreated anyway - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, pathEnd) || - !_FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } - parentCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - // Move the pathEnd past the last DIR_SEPARATOR - pathEnd += 1; - } - // Create the entry data - strncpy (dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); - memset (dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE); + // Write it to the directory + _FAT_cache_writePartialSector ( partition->cache, newEntryData, + _FAT_fat_clusterToSector (partition, dirCluster), DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - // Set the creation time and date - dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC()); + // Flush any sectors in the disc cache + if (!_FAT_cache_flush(partition->cache)) { + _FAT_unlock(&partition->lock); + r->_errno = EIO; + return -1; + } - // Set the directory attribute - dirEntry.entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; - - // Get a cluster for the new directory - dirCluster = _FAT_fat_linkFreeClusterCleared (partition, CLUSTER_FREE); - if (!_FAT_fat_isValidCluster(partition, dirCluster)) { - // No space left on disc for the cluster - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cluster, dirCluster); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_clusterHigh, dirCluster >> 16); - - // Write the new directory's entry to it's parent - if (!_FAT_directory_addEntry (partition, &dirEntry, parentCluster)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - - // Create the dot entry within the directory - memset (newEntryData, 0, DIR_ENTRY_DATA_SIZE); - memset (newEntryData, ' ', 11); - newEntryData[DIR_ENTRY_name] = '.'; - newEntryData[DIR_ENTRY_attributes] = ATTRIB_DIR; - u16_to_u8array (newEntryData, DIR_ENTRY_cluster, dirCluster); - u16_to_u8array (newEntryData, DIR_ENTRY_clusterHigh, dirCluster >> 16); - - // Write it to the directory, erasing that sector in the process - _FAT_cache_eraseWritePartialSector ( partition->cache, newEntryData, - _FAT_fat_clusterToSector (partition, dirCluster), 0, DIR_ENTRY_DATA_SIZE); - - - // Create the double dot entry within the directory - - // if ParentDir == Rootdir then ".."" always link to Cluster 0 - if (parentCluster == partition->rootDirCluster) - parentCluster = FAT16_ROOT_DIR_CLUSTER; - - newEntryData[DIR_ENTRY_name + 1] = '.'; - u16_to_u8array (newEntryData, DIR_ENTRY_cluster, parentCluster); - u16_to_u8array (newEntryData, DIR_ENTRY_clusterHigh, parentCluster >> 16); - - // Write it to the directory - _FAT_cache_writePartialSector ( partition->cache, newEntryData, - _FAT_fat_clusterToSector (partition, dirCluster), DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - - // Flush any sectors in the disc cache - if (!_FAT_cache_flush(partition->cache)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } - - _FAT_unlock(&partition->lock); - return 0; + _FAT_unlock(&partition->lock); + return 0; } -int _FAT_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) { - PARTITION* partition = NULL; - unsigned int freeClusterCount; +int _FAT_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) +{ + PARTITION* partition = NULL; + unsigned int freeClusterCount; - // Get the partition of the requested path - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + // Get the partition of the requested path + partition = _FAT_partition_getPartitionFromPath (path); + if (partition == NULL) { + r->_errno = ENODEV; + return -1; + } - _FAT_lock(&partition->lock); + _FAT_lock(&partition->lock); - freeClusterCount = _FAT_fat_freeClusterCount (partition); + freeClusterCount = _FAT_fat_freeClusterCount (partition); + + // FAT clusters = POSIX blocks + buf->f_bsize = partition->bytesPerCluster; // File system block size. + buf->f_frsize = partition->bytesPerCluster; // Fundamental file system block size. + + buf->f_blocks = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of blocks on file system in units of f_frsize. + buf->f_bfree = freeClusterCount; // Total number of free blocks. + buf->f_bavail = freeClusterCount; // Number of free blocks available to non-privileged process. - // FAT clusters = POSIX blocks - buf->f_bsize = partition->bytesPerCluster; // File system block size. - buf->f_frsize = partition->bytesPerCluster; // Fundamental file system block size. + // Treat requests for info on inodes as clusters + buf->f_files = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of file serial numbers. + buf->f_ffree = freeClusterCount; // Total number of free file serial numbers. + buf->f_favail = freeClusterCount; // Number of file serial numbers available to non-privileged process. + + // File system ID. 32bit ioType value + buf->f_fsid = _FAT_disc_hostType(partition->disc); + + // Bit mask of f_flag values. + buf->f_flag = ST_NOSUID /* No support for ST_ISUID and ST_ISGID file mode bits */ + | (partition->readOnly ? ST_RDONLY /* Read only file system */ : 0 ) ; + // Maximum filename length. + buf->f_namemax = MAX_FILENAME_LENGTH; - buf->f_blocks = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of blocks on file system in units of f_frsize. - buf->f_bfree = freeClusterCount; // Total number of free blocks. - buf->f_bavail = freeClusterCount; // Number of free blocks available to non-privileged process. - - // Treat requests for info on inodes as clusters - buf->f_files = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of file serial numbers. - buf->f_ffree = freeClusterCount; // Total number of free file serial numbers. - buf->f_favail = freeClusterCount; // Number of file serial numbers available to non-privileged process. - - // File system ID. 32bit ioType value - buf->f_fsid = _FAT_disc_hostType(partition->disc); - - // Bit mask of f_flag values. - buf->f_flag = ST_NOSUID /* No support for ST_ISUID and ST_ISGID file mode bits */ - | (partition->readOnly ? ST_RDONLY /* Read only file system */ : 0 ) ; - // Maximum filename length. - buf->f_namemax = MAX_FILENAME_LENGTH; - - _FAT_unlock(&partition->lock); - return 0; + _FAT_unlock(&partition->lock); + return 0; } DIR_ITER* _FAT_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path) { - DIR_ENTRY dirEntry; - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); - bool fileExists; + DIR_ENTRY dirEntry; + DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); + bool fileExists; + + state->partition = _FAT_partition_getPartitionFromPath (path); + if (state->partition == NULL) { + r->_errno = ENODEV; + return NULL; + } - state->partition = _FAT_partition_getPartitionFromPath (path); - if (state->partition == NULL) { - r->_errno = ENODEV; - return NULL; - } + // Move the path pointer to the start of the actual path + if (strchr (path, ':') != NULL) { + path = strchr (path, ':') + 1; + } + if (strchr (path, ':') != NULL) { + r->_errno = EINVAL; + return NULL; + } + + _FAT_lock(&state->partition->lock); + + // Get the start cluster of the directory + fileExists = _FAT_directory_entryFromPath (state->partition, &dirEntry, path, NULL); + + if (!fileExists) { + _FAT_unlock(&state->partition->lock); + r->_errno = ENOENT; + return NULL; + } + + // Make sure it is a directory + if (! _FAT_directory_isDirectory (&dirEntry)) { + _FAT_unlock(&state->partition->lock); + r->_errno = ENOTDIR; + return NULL; + } - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return NULL; - } - - _FAT_lock(&state->partition->lock); - - // Get the start cluster of the directory - fileExists = _FAT_directory_entryFromPath (state->partition, &dirEntry, path, NULL); - - if (!fileExists) { - _FAT_unlock(&state->partition->lock); - r->_errno = ENOENT; - return NULL; - } - - // Make sure it is a directory - if (! _FAT_directory_isDirectory (&dirEntry)) { - _FAT_unlock(&state->partition->lock); - r->_errno = ENOTDIR; - return NULL; - } - - // Save the start cluster for use when resetting the directory data - state->startCluster = _FAT_directory_entryGetCluster (state->partition, dirEntry.entryData); - - // Get the first entry for use with a call to dirnext - state->validEntry = - _FAT_directory_getFirstEntry (state->partition, &(state->currentEntry), state->startCluster); - - // We are now using this entry - state->inUse = true; - _FAT_unlock(&state->partition->lock); - return (DIR_ITER*) state; + // Save the start cluster for use when resetting the directory data + state->startCluster = _FAT_directory_entryGetCluster (state->partition, dirEntry.entryData); + + // Get the first entry for use with a call to dirnext + state->validEntry = + _FAT_directory_getFirstEntry (state->partition, &(state->currentEntry), state->startCluster); + + // We are now using this entry + state->inUse = true; + _FAT_unlock(&state->partition->lock); + return (DIR_ITER*) state; } int _FAT_dirreset_r (struct _reent *r, DIR_ITER *dirState) { - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); + DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); - _FAT_lock(&state->partition->lock); + _FAT_lock(&state->partition->lock); + + // Make sure we are still using this entry + if (!state->inUse) { + _FAT_unlock(&state->partition->lock); + r->_errno = EBADF; + return -1; + } - // Make sure we are still using this entry - if (!state->inUse) { - _FAT_unlock(&state->partition->lock); - r->_errno = EBADF; - return -1; - } + // Get the first entry for use with a call to dirnext + state->validEntry = + _FAT_directory_getFirstEntry (state->partition, &(state->currentEntry), state->startCluster); - // Get the first entry for use with a call to dirnext - state->validEntry = - _FAT_directory_getFirstEntry (state->partition, &(state->currentEntry), state->startCluster); - - _FAT_unlock(&state->partition->lock); - return 0; + _FAT_unlock(&state->partition->lock); + return 0; } int _FAT_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat) { - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); + DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); - _FAT_lock(&state->partition->lock); + _FAT_lock(&state->partition->lock); + + // Make sure we are still using this entry + if (!state->inUse) { + _FAT_unlock(&state->partition->lock); + r->_errno = EBADF; + return -1; + } + + // Make sure there is another file to report on + if (! state->validEntry) { + _FAT_unlock(&state->partition->lock); + r->_errno = ENOENT; + return -1; + } - // Make sure we are still using this entry - if (!state->inUse) { - _FAT_unlock(&state->partition->lock); - r->_errno = EBADF; - return -1; - } + // Get the filename + strncpy (filename, state->currentEntry.filename, MAX_FILENAME_LENGTH); + // Get the stats, if requested + if (filestat != NULL) { + _FAT_directory_entryStat (state->partition, &(state->currentEntry), filestat); + } + + // Look for the next entry for use next time + state->validEntry = + _FAT_directory_getNextEntry (state->partition, &(state->currentEntry)); - // Make sure there is another file to report on - if (! state->validEntry) { - _FAT_unlock(&state->partition->lock); - r->_errno = ENOENT; - return -1; - } - - // Get the filename - strncpy (filename, state->currentEntry.filename, MAX_FILENAME_LENGTH); - // Get the stats, if requested - if (filestat != NULL) { - _FAT_directory_entryStat (state->partition, &(state->currentEntry), filestat); - } - - // Look for the next entry for use next time - state->validEntry = - _FAT_directory_getNextEntry (state->partition, &(state->currentEntry)); - - _FAT_unlock(&state->partition->lock); - return 0; + _FAT_unlock(&state->partition->lock); + return 0; } int _FAT_dirclose_r (struct _reent *r, DIR_ITER *dirState) { - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); + DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); + + // We are no longer using this entry + _FAT_lock(&state->partition->lock); + state->inUse = false; + _FAT_unlock(&state->partition->lock); - // We are no longer using this entry - _FAT_lock(&state->partition->lock); - state->inUse = false; - _FAT_unlock(&state->partition->lock); - - return 0; + return 0; } diff --git a/source/libfat/fatdir.h b/source/libfat/fatdir.h index d7d4901c..1b47a914 100644 --- a/source/libfat/fatdir.h +++ b/source/libfat/fatdir.h @@ -40,11 +40,11 @@ #include "directory.h" typedef struct { - PARTITION* partition; - DIR_ENTRY currentEntry; - uint32_t startCluster; - bool inUse; - bool validEntry; + PARTITION* partition; + DIR_ENTRY currentEntry; + uint32_t startCluster; + bool inUse; + bool validEntry; } DIR_STATE_STRUCT; extern int _FAT_stat_r (struct _reent *r, const char *path, struct stat *st); diff --git a/source/libfat/fatfile.c b/source/libfat/fatfile.c index 1ad3d186..ba8dddb5 100644 --- a/source/libfat/fatfile.c +++ b/source/libfat/fatfile.c @@ -46,207 +46,207 @@ #include "lock.h" int _FAT_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) { - PARTITION* partition = NULL; - bool fileExists; - DIR_ENTRY dirEntry; - const char* pathEnd; - uint32_t dirCluster; - FILE_STRUCT* file = (FILE_STRUCT*) fileStruct; - partition = _FAT_partition_getPartitionFromPath (path); + PARTITION* partition = NULL; + bool fileExists; + DIR_ENTRY dirEntry; + const char* pathEnd; + uint32_t dirCluster; + FILE_STRUCT* file = (FILE_STRUCT*) fileStruct; + partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + if (partition == NULL) { + r->_errno = ENODEV; + return -1; + } - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } + // Move the path pointer to the start of the actual path + if (strchr (path, ':') != NULL) { + path = strchr (path, ':') + 1; + } + if (strchr (path, ':') != NULL) { + r->_errno = EINVAL; + return -1; + } - // Determine which mode the file is openned for - if ((flags & 0x03) == O_RDONLY) { - // Open the file for read-only access - file->read = true; - file->write = false; - file->append = false; - } else if ((flags & 0x03) == O_WRONLY) { - // Open file for write only access - file->read = false; - file->write = true; - file->append = false; - } else if ((flags & 0x03) == O_RDWR) { - // Open file for read/write access - file->read = true; - file->write = true; - file->append = false; - } else { - r->_errno = EACCES; - return -1; - } + // Determine which mode the file is openned for + if ((flags & 0x03) == O_RDONLY) { + // Open the file for read-only access + file->read = true; + file->write = false; + file->append = false; + } else if ((flags & 0x03) == O_WRONLY) { + // Open file for write only access + file->read = false; + file->write = true; + file->append = false; + } else if ((flags & 0x03) == O_RDWR) { + // Open file for read/write access + file->read = true; + file->write = true; + file->append = false; + } else { + r->_errno = EACCES; + return -1; + } - // Make sure we aren't trying to write to a read-only disc - if (file->write && partition->readOnly) { - r->_errno = EROFS; - return -1; - } + // Make sure we aren't trying to write to a read-only disc + if (file->write && partition->readOnly) { + r->_errno = EROFS; + return -1; + } - // Search for the file on the disc - _FAT_lock(&partition->lock); - fileExists = _FAT_directory_entryFromPath (partition, &dirEntry, path, NULL); + // Search for the file on the disc + _FAT_lock(&partition->lock); + fileExists = _FAT_directory_entryFromPath (partition, &dirEntry, path, NULL); - // The file shouldn't exist if we are trying to create it - if ((flags & O_CREAT) && (flags & O_EXCL) && fileExists) { - _FAT_unlock(&partition->lock); - r->_errno = EEXIST; - return -1; - } + // The file shouldn't exist if we are trying to create it + if ((flags & O_CREAT) && (flags & O_EXCL) && fileExists) { + _FAT_unlock(&partition->lock); + r->_errno = EEXIST; + return -1; + } - // It should not be a directory if we're openning a file, - if (fileExists && _FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EISDIR; - return -1; - } + // It should not be a directory if we're openning a file, + if (fileExists && _FAT_directory_isDirectory(&dirEntry)) { + _FAT_unlock(&partition->lock); + r->_errno = EISDIR; + return -1; + } - // We haven't modified the file yet - file->modified = false; + // We haven't modified the file yet + file->modified = false; - // If the file doesn't exist, create it if we're allowed to - if (!fileExists) { - if (flags & O_CREAT) { - if (partition->readOnly) { - // We can't write to a read-only partition - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } - // Create the file - // Get the directory it has to go in - pathEnd = strrchr (path, DIR_SEPARATOR); - if (pathEnd == NULL) { - // No path was specified - dirCluster = partition->cwdCluster; - pathEnd = path; - } else { - // Path was specified -- get the right dirCluster - // Recycling dirEntry, since it needs to be recreated anyway - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, pathEnd) || - !_FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } - dirCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - // Move the pathEnd past the last DIR_SEPARATOR - pathEnd += 1; - } - // Create the entry data - strncpy (dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); - memset (dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE); + // If the file doesn't exist, create it if we're allowed to + if (!fileExists) { + if (flags & O_CREAT) { + if (partition->readOnly) { + // We can't write to a read-only partition + _FAT_unlock(&partition->lock); + r->_errno = EROFS; + return -1; + } + // Create the file + // Get the directory it has to go in + pathEnd = strrchr (path, DIR_SEPARATOR); + if (pathEnd == NULL) { + // No path was specified + dirCluster = partition->cwdCluster; + pathEnd = path; + } else { + // Path was specified -- get the right dirCluster + // Recycling dirEntry, since it needs to be recreated anyway + if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, pathEnd) || + !_FAT_directory_isDirectory(&dirEntry)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOTDIR; + return -1; + } + dirCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); + // Move the pathEnd past the last DIR_SEPARATOR + pathEnd += 1; + } + // Create the entry data + strncpy (dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); + memset (dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE); - // Set the creation time and date - dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC()); + // Set the creation time and date + dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC()); + u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC()); - if (!_FAT_directory_addEntry (partition, &dirEntry, dirCluster)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } + if (!_FAT_directory_addEntry (partition, &dirEntry, dirCluster)) { + _FAT_unlock(&partition->lock); + r->_errno = ENOSPC; + return -1; + } - // File entry is modified - file->modified = true; - } else { - // file doesn't exist, and we aren't creating it - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - } + // File entry is modified + file->modified = true; + } else { + // file doesn't exist, and we aren't creating it + _FAT_unlock(&partition->lock); + r->_errno = ENOENT; + return -1; + } + } - file->filesize = u8array_to_u32 (dirEntry.entryData, DIR_ENTRY_fileSize); + file->filesize = u8array_to_u32 (dirEntry.entryData, DIR_ENTRY_fileSize); - /* Allow LARGEFILEs with undefined results - // Make sure that the file size can fit in the available space - if (!(flags & O_LARGEFILE) && (file->filesize >= (1<<31))) { - r->_errno = EFBIG; - return -1; - } - */ + /* Allow LARGEFILEs with undefined results + // Make sure that the file size can fit in the available space + if (!(flags & O_LARGEFILE) && (file->filesize >= (1<<31))) { + r->_errno = EFBIG; + return -1; + } + */ - // Make sure we aren't trying to write to a read-only file - if (file->write && !_FAT_directory_isWritable(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } + // Make sure we aren't trying to write to a read-only file + if (file->write && !_FAT_directory_isWritable(&dirEntry)) { + _FAT_unlock(&partition->lock); + r->_errno = EROFS; + return -1; + } - // Associate this file with a particular partition - file->partition = partition; + // Associate this file with a particular partition + file->partition = partition; - file->startCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); + file->startCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - // Truncate the file if requested - if ((flags & O_TRUNC) && file->write && (file->startCluster != 0)) { - _FAT_fat_clearLinks (partition, file->startCluster); - file->startCluster = CLUSTER_FREE; - file->filesize = 0; - // File is modified since we just cut it all off - file->modified = true; - } + // Truncate the file if requested + if ((flags & O_TRUNC) && file->write && (file->startCluster != 0)) { + _FAT_fat_clearLinks (partition, file->startCluster); + file->startCluster = CLUSTER_FREE; + file->filesize = 0; + // File is modified since we just cut it all off + file->modified = true; + } - // Remember the position of this file's directory entry - file->dirEntryStart = dirEntry.dataStart; // Points to the start of the LFN entries of a file, or the alias for no LFN - file->dirEntryEnd = dirEntry.dataEnd; + // Remember the position of this file's directory entry + file->dirEntryStart = dirEntry.dataStart; // Points to the start of the LFN entries of a file, or the alias for no LFN + file->dirEntryEnd = dirEntry.dataEnd; - // Reset read/write pointer - file->currentPosition = 0; - file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; - file->rwPosition.byte = 0; + // Reset read/write pointer + file->currentPosition = 0; + file->rwPosition.cluster = file->startCluster; + file->rwPosition.sector = 0; + file->rwPosition.byte = 0; - if (flags & O_APPEND) { - file->append = true; + if (flags & O_APPEND) { + file->append = true; - // Set append pointer to the end of the file - file->appendPosition.cluster = _FAT_fat_lastCluster (partition, file->startCluster); - file->appendPosition.sector = (file->filesize % partition->bytesPerCluster) / BYTES_PER_READ; - file->appendPosition.byte = file->filesize % BYTES_PER_READ; + // Set append pointer to the end of the file + file->appendPosition.cluster = _FAT_fat_lastCluster (partition, file->startCluster); + file->appendPosition.sector = (file->filesize % partition->bytesPerCluster) / BYTES_PER_READ; + file->appendPosition.byte = file->filesize % BYTES_PER_READ; - // Check if the end of the file is on the end of a cluster - if ( (file->filesize > 0) && ((file->filesize % partition->bytesPerCluster)==0) ) { - // Set flag to allocate a new cluster - file->appendPosition.sector = partition->sectorsPerCluster; - file->appendPosition.byte = 0; - } - } else { - file->append = false; - // Use something sane for the append pointer, so the whole file struct contains known values - file->appendPosition = file->rwPosition; - } + // Check if the end of the file is on the end of a cluster + if ( (file->filesize > 0) && ((file->filesize % partition->bytesPerCluster)==0) ){ + // Set flag to allocate a new cluster + file->appendPosition.sector = partition->sectorsPerCluster; + file->appendPosition.byte = 0; + } + } else { + file->append = false; + // Use something sane for the append pointer, so the whole file struct contains known values + file->appendPosition = file->rwPosition; + } - file->inUse = true; + file->inUse = true; - // Insert this file into the double-linked list of open files - partition->openFileCount += 1; - if (partition->firstOpenFile) { - file->nextOpenFile = partition->firstOpenFile; - partition->firstOpenFile->prevOpenFile = file; - } else { - file->nextOpenFile = NULL; - } - file->prevOpenFile = NULL; - partition->firstOpenFile = file; + // Insert this file into the double-linked list of open files + partition->openFileCount += 1; + if (partition->firstOpenFile) { + file->nextOpenFile = partition->firstOpenFile; + partition->firstOpenFile->prevOpenFile = file; + } else { + file->nextOpenFile = NULL; + } + file->prevOpenFile = NULL; + partition->firstOpenFile = file; - _FAT_unlock(&partition->lock); + _FAT_unlock(&partition->lock); - return (int) file; + return (int) file; } /* @@ -255,256 +255,260 @@ Does no locking of its own -- lock the partition before calling. Returns 0 on success, an error code on failure. */ int _FAT_syncToDisc (FILE_STRUCT* file) { - uint8_t dirEntryData[DIR_ENTRY_DATA_SIZE]; + uint8_t dirEntryData[DIR_ENTRY_DATA_SIZE]; - if (!file || !file->inUse) { - return EBADF; - } + if (!file || !file->inUse) { + return EBADF; + } - if (file->write && file->modified) { - // Load the old entry - _FAT_cache_readPartialSector (file->partition->cache, dirEntryData, - _FAT_fat_clusterToSector(file->partition, file->dirEntryEnd.cluster) + file->dirEntryEnd.sector, - file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + if (file->write && file->modified) { + // Load the old entry + _FAT_cache_readPartialSector (file->partition->cache, dirEntryData, + _FAT_fat_clusterToSector(file->partition, file->dirEntryEnd.cluster) + file->dirEntryEnd.sector, + file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - // Write new data to the directory entry - // File size - u32_to_u8array (dirEntryData, DIR_ENTRY_fileSize, file->filesize); + // Write new data to the directory entry + // File size + u32_to_u8array (dirEntryData, DIR_ENTRY_fileSize, file->filesize); - // Start cluster - u16_to_u8array (dirEntryData, DIR_ENTRY_cluster, file->startCluster); - u16_to_u8array (dirEntryData, DIR_ENTRY_clusterHigh, file->startCluster >> 16); + // Start cluster + u16_to_u8array (dirEntryData, DIR_ENTRY_cluster, file->startCluster); + u16_to_u8array (dirEntryData, DIR_ENTRY_clusterHigh, file->startCluster >> 16); - // Modification time and date - u16_to_u8array (dirEntryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC()); + // Modification time and date + u16_to_u8array (dirEntryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC()); + u16_to_u8array (dirEntryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC()); - // Access date - u16_to_u8array (dirEntryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC()); + // Access date + u16_to_u8array (dirEntryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC()); - // Set archive attribute - dirEntryData[DIR_ENTRY_attributes] |= ATTRIB_ARCH; + // Set archive attribute + dirEntryData[DIR_ENTRY_attributes] |= ATTRIB_ARCH; - // Write the new entry - _FAT_cache_writePartialSector (file->partition->cache, dirEntryData, - _FAT_fat_clusterToSector(file->partition, file->dirEntryEnd.cluster) + file->dirEntryEnd.sector, - file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + // Write the new entry + _FAT_cache_writePartialSector (file->partition->cache, dirEntryData, + _FAT_fat_clusterToSector(file->partition, file->dirEntryEnd.cluster) + file->dirEntryEnd.sector, + file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - // Flush any sectors in the disc cache - if (!_FAT_cache_flush(file->partition->cache)) { - return EIO; - } - } + // Flush any sectors in the disc cache + if (!_FAT_cache_flush(file->partition->cache)) { + return EIO; + } + } - file->modified = false; + file->modified = false; - return 0; + return 0; } int _FAT_close_r (struct _reent *r, int fd) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - int ret = 0; + FILE_STRUCT* file = (FILE_STRUCT*) fd; + int ret = 0; - if (!file->inUse) { - r->_errno = EBADF; - return -1; - } + if (!file->inUse) { + r->_errno = EBADF; + return -1; + } - _FAT_lock(&file->partition->lock); + _FAT_lock(&file->partition->lock); - if (file->write) { - ret = _FAT_syncToDisc (file); - if (ret != 0) { - r->_errno = ret; - ret = -1; - } - } + if (file->write) { + ret = _FAT_syncToDisc (file); + if (ret != 0) { + r->_errno = ret; + ret = -1; + } + } - file->inUse = false; + file->inUse = false; - // Remove this file from the double-linked list of open files - file->partition->openFileCount -= 1; - if (file->nextOpenFile) { - file->nextOpenFile->prevOpenFile = file->prevOpenFile; - } - if (file->prevOpenFile) { - file->prevOpenFile->nextOpenFile = file->nextOpenFile; - } else { - file->partition->firstOpenFile = file->nextOpenFile; - } + // Remove this file from the double-linked list of open files + file->partition->openFileCount -= 1; + if (file->nextOpenFile) { + file->nextOpenFile->prevOpenFile = file->prevOpenFile; + } + if (file->prevOpenFile) { + file->prevOpenFile->nextOpenFile = file->nextOpenFile; + } else { + file->partition->firstOpenFile = file->nextOpenFile; + } - _FAT_unlock(&file->partition->lock); + _FAT_unlock(&file->partition->lock); - return ret; + return ret; } ssize_t _FAT_read_r (struct _reent *r, int fd, char *ptr, size_t len) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - CACHE* cache; - FILE_POSITION position; - uint32_t tempNextCluster; - unsigned int tempVar; - size_t remain; - bool flagNoError = true; + FILE_STRUCT* file = (FILE_STRUCT*) fd; + PARTITION* partition; + CACHE* cache; + FILE_POSITION position; + uint32_t tempNextCluster; + unsigned int tempVar; + size_t remain; + bool flagNoError = true; - // Short circuit cases where len is 0 (or less) - if (len <= 0) { - return 0; - } + // Short circuit cases where len is 0 (or less) + if (len <= 0) { + return 0; + } - // Make sure we can actually read from the file - if ((file == NULL) || !file->inUse || !file->read) { - r->_errno = EBADF; - return -1; - } + // Make sure we can actually read from the file + if ((file == NULL) || !file->inUse || !file->read) { + r->_errno = EBADF; + return -1; + } - partition = file->partition; - _FAT_lock(&partition->lock); + partition = file->partition; + _FAT_lock(&partition->lock); - // Don't try to read if the read pointer is past the end of file - if (file->currentPosition >= file->filesize || file->startCluster == CLUSTER_FREE) { - r->_errno = EOVERFLOW; - _FAT_unlock(&partition->lock); - return 0; - } + // Don't try to read if the read pointer is past the end of file + if (file->currentPosition >= file->filesize || file->startCluster == CLUSTER_FREE) { + r->_errno = EOVERFLOW; + _FAT_unlock(&partition->lock); + return 0; + } - // Don't read past end of file - if (len + file->currentPosition > file->filesize) { - r->_errno = EOVERFLOW; - len = file->filesize - file->currentPosition; - } + // Don't read past end of file + if (len + file->currentPosition > file->filesize) { + r->_errno = EOVERFLOW; + len = file->filesize - file->currentPosition; + } - remain = len; - position = file->rwPosition; - cache = file->partition->cache; + remain = len; + position = file->rwPosition; + cache = file->partition->cache; - // Align to sector - tempVar = BYTES_PER_READ - position.byte; - if (tempVar > remain) { - tempVar = remain; - } + // Align to sector + tempVar = BYTES_PER_READ - position.byte; + if (tempVar > remain) { + tempVar = remain; + } - if ((tempVar < BYTES_PER_READ) && flagNoError) { - _FAT_cache_readPartialSector ( cache, ptr, _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, - position.byte, tempVar); + if ((tempVar < BYTES_PER_READ) && flagNoError) + { + _FAT_cache_readPartialSector ( cache, ptr, _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, + position.byte, tempVar); - remain -= tempVar; - ptr += tempVar; + remain -= tempVar; + ptr += tempVar; - position.byte += tempVar; - if (position.byte >= BYTES_PER_READ) { - position.byte = 0; - position.sector++; - } - } + position.byte += tempVar; + if (position.byte >= BYTES_PER_READ) { + position.byte = 0; + position.sector++; + } + } - // align to cluster - // tempVar is number of sectors to read - if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { - tempVar = partition->sectorsPerCluster - position.sector; - } else { - tempVar = remain / BYTES_PER_READ; - } + // align to cluster + // tempVar is number of sectors to read + if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { + tempVar = partition->sectorsPerCluster - position.sector; + } else { + tempVar = remain / BYTES_PER_READ; + } - if ((tempVar > 0) && flagNoError) { - if (! _FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, - tempVar, ptr)) { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } + if ((tempVar > 0) && flagNoError) { + if (! _FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, + tempVar, ptr)) + { + flagNoError = false; + r->_errno = EIO; + } else { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } - // Move onto next cluster - // It should get to here without reading anything if a cluster is due to be allocated - if ((position.sector >= partition->sectorsPerCluster) && flagNoError) { - tempNextCluster = _FAT_fat_nextCluster(partition, position.cluster); - if ((remain == 0) && (tempNextCluster == CLUSTER_EOF)) { - position.sector = partition->sectorsPerCluster; - } else if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - r->_errno = EIO; - flagNoError = false; - } else { - position.sector = 0; - position.cluster = tempNextCluster; - } - } + // Move onto next cluster + // It should get to here without reading anything if a cluster is due to be allocated + if ((position.sector >= partition->sectorsPerCluster) && flagNoError) { + tempNextCluster = _FAT_fat_nextCluster(partition, position.cluster); + if ((remain == 0) && (tempNextCluster == CLUSTER_EOF)) { + position.sector = partition->sectorsPerCluster; + } else if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { + r->_errno = EIO; + flagNoError = false; + } else { + position.sector = 0; + position.cluster = tempNextCluster; + } + } - // Read in whole clusters, contiguous blocks at a time - while ((remain >= partition->bytesPerCluster) && flagNoError) { - uint32_t chunkEnd; - uint32_t nextChunkStart = position.cluster; - size_t chunkSize = 0; + // Read in whole clusters, contiguous blocks at a time + while ((remain >= partition->bytesPerCluster) && flagNoError) { + uint32_t chunkEnd; + uint32_t nextChunkStart = position.cluster; + size_t chunkSize = 0; - do { - chunkEnd = nextChunkStart; - nextChunkStart = _FAT_fat_nextCluster (partition, chunkEnd); - chunkSize += partition->bytesPerCluster; - } while ((nextChunkStart == chunkEnd + 1) && + do { + chunkEnd = nextChunkStart; + nextChunkStart = _FAT_fat_nextCluster (partition, chunkEnd); + chunkSize += partition->bytesPerCluster; + } while ((nextChunkStart == chunkEnd + 1) && #ifdef LIMIT_SECTORS - (chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ) && + (chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ) && #endif - (chunkSize + partition->bytesPerCluster <= remain)); + (chunkSize + partition->bytesPerCluster <= remain)); - if (!_FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), - chunkSize / BYTES_PER_READ, ptr)) { - flagNoError = false; - r->_errno = EIO; - break; - } - ptr += chunkSize; - remain -= chunkSize; + if (!_FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), + chunkSize / BYTES_PER_READ, ptr)) + { + flagNoError = false; + r->_errno = EIO; + break; + } + ptr += chunkSize; + remain -= chunkSize; - // Advance to next cluster - if ((remain == 0) && (nextChunkStart == CLUSTER_EOF)) { - position.sector = partition->sectorsPerCluster; - position.cluster = chunkEnd; - } else if (!_FAT_fat_isValidCluster(partition, nextChunkStart)) { - r->_errno = EIO; - flagNoError = false; - } else { - position.sector = 0; - position.cluster = nextChunkStart; - } - } + // Advance to next cluster + if ((remain == 0) && (nextChunkStart == CLUSTER_EOF)) { + position.sector = partition->sectorsPerCluster; + position.cluster = chunkEnd; + } else if (!_FAT_fat_isValidCluster(partition, nextChunkStart)) { + r->_errno = EIO; + flagNoError = false; + } else { + position.sector = 0; + position.cluster = nextChunkStart; + } + } - // Read remaining sectors - tempVar = remain / BYTES_PER_READ; // Number of sectors left - if ((tempVar > 0) && flagNoError) { - if (!_FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), - tempVar, ptr)) { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } + // Read remaining sectors + tempVar = remain / BYTES_PER_READ; // Number of sectors left + if ((tempVar > 0) && flagNoError) { + if (!_FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), + tempVar, ptr)) + { + flagNoError = false; + r->_errno = EIO; + } else { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } - // Last remaining sector - // Check if anything is left - if ((remain > 0) && flagNoError) { - _FAT_cache_readPartialSector ( cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - position.byte += remain; - remain = 0; - } + // Last remaining sector + // Check if anything is left + if ((remain > 0) && flagNoError) { + _FAT_cache_readPartialSector ( cache, ptr, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); + position.byte += remain; + remain = 0; + } - // Length read is the wanted length minus the stuff not read - len = len - remain; + // Length read is the wanted length minus the stuff not read + len = len - remain; - // Update file information - file->rwPosition = position; - file->currentPosition += len; + // Update file information + file->rwPosition = position; + file->currentPosition += len; - _FAT_unlock(&partition->lock); - return len; + _FAT_unlock(&partition->lock); + return len; } // if current position is on the cluster border and more data has to be written @@ -512,661 +516,667 @@ ssize_t _FAT_read_r (struct _reent *r, int fd, char *ptr, size_t len) { // this solves the over-allocation problems when file size is aligned to cluster size // return true on succes, false on error static bool _FAT_check_position_for_next_cluster(struct _reent *r, - FILE_POSITION *position, PARTITION* partition, size_t remain, bool *flagNoError) { - uint32_t tempNextCluster; - // do nothing if no more data to write - if (remain == 0) return true; - if (flagNoError && *flagNoError == false) return false; - if ((remain < 0) || (position->sector > partition->sectorsPerCluster)) { - // invalid arguments - internal error - r->_errno = EINVAL; - goto err; - } - if (position->sector == partition->sectorsPerCluster) { - // need to advance to next cluster - tempNextCluster = _FAT_fat_nextCluster(partition, position->cluster); - if ((tempNextCluster == CLUSTER_EOF) || (tempNextCluster == CLUSTER_FREE)) { - // Ran out of clusters so get a new one - tempNextCluster = _FAT_fat_linkFreeCluster(partition, position->cluster); - } - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - goto err; - } - position->sector = 0; - position->cluster = tempNextCluster; - } - return true; + FILE_POSITION *position, PARTITION* partition, size_t remain, bool *flagNoError) +{ + uint32_t tempNextCluster; + // do nothing if no more data to write + if (remain == 0) return true; + if (flagNoError && *flagNoError == false) return false; + if ((remain < 0) || (position->sector > partition->sectorsPerCluster)) { + // invalid arguments - internal error + r->_errno = EINVAL; + goto err; + } + if (position->sector == partition->sectorsPerCluster) { + // need to advance to next cluster + tempNextCluster = _FAT_fat_nextCluster(partition, position->cluster); + if ((tempNextCluster == CLUSTER_EOF) || (tempNextCluster == CLUSTER_FREE)) { + // Ran out of clusters so get a new one + tempNextCluster = _FAT_fat_linkFreeCluster(partition, position->cluster); + } + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + goto err; + } + position->sector = 0; + position->cluster = tempNextCluster; + } + return true; err: - if (flagNoError) *flagNoError = false; - return false; + if (flagNoError) *flagNoError = false; + return false; } /* Extend a file so that the size is the same as the rwPosition */ static bool _FAT_file_extend_r (struct _reent *r, FILE_STRUCT* file) { - PARTITION* partition = file->partition; - CACHE* cache = file->partition->cache; - FILE_POSITION position; - uint8_t zeroBuffer [BYTES_PER_READ] = {0}; - uint32_t remain; - uint32_t tempNextCluster; - unsigned int sector; + PARTITION* partition = file->partition; + CACHE* cache = file->partition->cache; + FILE_POSITION position; + uint8_t zeroBuffer [BYTES_PER_READ] = {0}; + uint32_t remain; + uint32_t tempNextCluster; + unsigned int sector; - position.byte = file->filesize % BYTES_PER_READ; - position.sector = (file->filesize % partition->bytesPerCluster) / BYTES_PER_READ; - // It is assumed that there is always a startCluster - // This will be true when _FAT_file_extend_r is called from _FAT_write_r - position.cluster = _FAT_fat_lastCluster (partition, file->startCluster); + position.byte = file->filesize % BYTES_PER_READ; + position.sector = (file->filesize % partition->bytesPerCluster) / BYTES_PER_READ; + // It is assumed that there is always a startCluster + // This will be true when _FAT_file_extend_r is called from _FAT_write_r + position.cluster = _FAT_fat_lastCluster (partition, file->startCluster); - remain = file->currentPosition - file->filesize; + remain = file->currentPosition - file->filesize; - if ((remain > 0) && (file->filesize > 0) && (position.sector == 0) && (position.byte == 0)) { - // Get a new cluster on the edge of a cluster boundary - tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - return false; - } - position.cluster = tempNextCluster; - position.sector = 0; - } + if ((remain > 0) && (file->filesize > 0) && (position.sector == 0) && (position.byte == 0)) { + // Get a new cluster on the edge of a cluster boundary + tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + return false; + } + position.cluster = tempNextCluster; + position.sector = 0; + } - if (remain + position.byte < BYTES_PER_READ) { - // Only need to clear to the end of the sector - _FAT_cache_writePartialSector (cache, zeroBuffer, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, remain); - position.byte += remain; - } else { - if (position.byte > 0) { - _FAT_cache_writePartialSector (cache, zeroBuffer, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, - BYTES_PER_READ - position.byte); - remain -= (BYTES_PER_READ - position.byte); - position.byte = 0; - position.sector ++; - } + if (remain + position.byte < BYTES_PER_READ) { + // Only need to clear to the end of the sector + _FAT_cache_writePartialSector (cache, zeroBuffer, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, remain); + position.byte += remain; + } else { + if (position.byte > 0) { + _FAT_cache_writePartialSector (cache, zeroBuffer, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, + BYTES_PER_READ - position.byte); + remain -= (BYTES_PER_READ - position.byte); + position.byte = 0; + position.sector ++; + } - while (remain >= BYTES_PER_READ) { - if (position.sector >= partition->sectorsPerCluster) { - position.sector = 0; - // Ran out of clusters so get a new one - tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - return false; - } - position.cluster = tempNextCluster; - } + while (remain >= BYTES_PER_READ) { + if (position.sector >= partition->sectorsPerCluster) { + position.sector = 0; + // Ran out of clusters so get a new one + tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + return false; + } + position.cluster = tempNextCluster; + } - sector = _FAT_fat_clusterToSector (partition, position.cluster) + position.sector; - _FAT_cache_writeSectors (cache, sector, 1, zeroBuffer); + sector = _FAT_fat_clusterToSector (partition, position.cluster) + position.sector; + _FAT_cache_writeSectors (cache, sector, 1, zeroBuffer); - remain -= BYTES_PER_READ; - position.sector ++; - } + remain -= BYTES_PER_READ; + position.sector ++; + } - if (!_FAT_check_position_for_next_cluster(r, &position, partition, remain, NULL)) { - // error already marked - return false; - } + if (!_FAT_check_position_for_next_cluster(r, &position, partition, remain, NULL)) { + // error already marked + return false; + } - if (remain > 0) { - _FAT_cache_writePartialSector (cache, zeroBuffer, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - position.byte = remain; - } - } + if (remain > 0) { + _FAT_cache_writePartialSector (cache, zeroBuffer, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); + position.byte = remain; + } + } - file->rwPosition = position; - file->filesize = file->currentPosition; - return true; + file->rwPosition = position; + file->filesize = file->currentPosition; + return true; } ssize_t _FAT_write_r (struct _reent *r, int fd, const char *ptr, size_t len) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - CACHE* cache; - FILE_POSITION position; - uint32_t tempNextCluster; - unsigned int tempVar; - size_t remain; - bool flagNoError = true; - bool flagAppending = false; + FILE_STRUCT* file = (FILE_STRUCT*) fd; + PARTITION* partition; + CACHE* cache; + FILE_POSITION position; + uint32_t tempNextCluster; + unsigned int tempVar; + size_t remain; + bool flagNoError = true; + bool flagAppending = false; - // Make sure we can actually write to the file - if ((file == NULL) || !file->inUse || !file->write) { - r->_errno = EBADF; - return -1; - } + // Make sure we can actually write to the file + if ((file == NULL) || !file->inUse || !file->write) { + r->_errno = EBADF; + return -1; + } - partition = file->partition; - cache = file->partition->cache; - _FAT_lock(&partition->lock); + partition = file->partition; + cache = file->partition->cache; + _FAT_lock(&partition->lock); - // Only write up to the maximum file size, taking into account wrap-around of ints - if (remain + file->filesize > FILE_MAX_SIZE || len + file->filesize < file->filesize) { - len = FILE_MAX_SIZE - file->filesize; - } - remain = len; + // Only write up to the maximum file size, taking into account wrap-around of ints + if (remain + file->filesize > FILE_MAX_SIZE || len + file->filesize < file->filesize) { + len = FILE_MAX_SIZE - file->filesize; + } + remain = len; - // Short circuit cases where len is 0 (or less) - if (len <= 0) { - _FAT_unlock(&partition->lock); - return 0; - } + // Short circuit cases where len is 0 (or less) + if (len <= 0) { + _FAT_unlock(&partition->lock); + return 0; + } - // Get a new cluster for the start of the file if required - if (file->startCluster == CLUSTER_FREE) { - tempNextCluster = _FAT_fat_linkFreeCluster (partition, CLUSTER_FREE); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort immediately - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - file->startCluster = tempNextCluster; + // Get a new cluster for the start of the file if required + if (file->startCluster == CLUSTER_FREE) { + tempNextCluster = _FAT_fat_linkFreeCluster (partition, CLUSTER_FREE); + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { + // Couldn't get a cluster, so abort immediately + _FAT_unlock(&partition->lock); + r->_errno = ENOSPC; + return -1; + } + file->startCluster = tempNextCluster; - // Appending starts at the begining for a 0 byte file - file->appendPosition.cluster = file->startCluster; - file->appendPosition.sector = 0; - file->appendPosition.byte = 0; + // Appending starts at the begining for a 0 byte file + file->appendPosition.cluster = file->startCluster; + file->appendPosition.sector = 0; + file->appendPosition.byte = 0; - file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; - file->rwPosition.byte = 0; - } + file->rwPosition.cluster = file->startCluster; + file->rwPosition.sector = 0; + file->rwPosition.byte = 0; + } - if (file->append) { - position = file->appendPosition; - flagAppending = true; - } else { - // If the write pointer is past the end of the file, extend the file to that size - if (file->currentPosition > file->filesize) { - if (!_FAT_file_extend_r (r, file)) { - _FAT_unlock(&partition->lock); - return -1; - } - } + if (file->append) { + position = file->appendPosition; + flagAppending = true; + } else { + // If the write pointer is past the end of the file, extend the file to that size + if (file->currentPosition > file->filesize) { + if (!_FAT_file_extend_r (r, file)) { + _FAT_unlock(&partition->lock); + return -1; + } + } - // Write at current read pointer - position = file->rwPosition; + // Write at current read pointer + position = file->rwPosition; - // If it is writing past the current end of file, set appending flag - if (len + file->currentPosition > file->filesize) { - flagAppending = true; - } - } + // If it is writing past the current end of file, set appending flag + if (len + file->currentPosition > file->filesize) { + flagAppending = true; + } + } - // Move onto next cluster if needed - _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); + // Move onto next cluster if needed + _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); - // Align to sector - tempVar = BYTES_PER_READ - position.byte; - if (tempVar > remain) { - tempVar = remain; - } + // Align to sector + tempVar = BYTES_PER_READ - position.byte; + if (tempVar > remain) { + tempVar = remain; + } - if ((tempVar < BYTES_PER_READ) && flagNoError) { - // Write partial sector to disk - _FAT_cache_writePartialSector (cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, tempVar); + if ((tempVar < BYTES_PER_READ) && flagNoError) { + // Write partial sector to disk + _FAT_cache_writePartialSector (cache, ptr, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, tempVar); - remain -= tempVar; - ptr += tempVar; - position.byte += tempVar; + remain -= tempVar; + ptr += tempVar; + position.byte += tempVar; - // Move onto next sector - if (position.byte >= BYTES_PER_READ) { - position.byte = 0; - position.sector ++; - } - } + // Move onto next sector + if (position.byte >= BYTES_PER_READ) { + position.byte = 0; + position.sector ++; + } + } - // Align to cluster - // tempVar is number of sectors to write - if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { - tempVar = partition->sectorsPerCluster - position.sector; - } else { - tempVar = remain / BYTES_PER_READ; - } + // Align to cluster + // tempVar is number of sectors to write + if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { + tempVar = partition->sectorsPerCluster - position.sector; + } else { + tempVar = remain / BYTES_PER_READ; + } - if ((tempVar > 0 && tempVar < partition->sectorsPerCluster) && flagNoError) { - if (!_FAT_cache_writeSectors (cache, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, tempVar, ptr)) { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } + if ((tempVar > 0 && tempVar < partition->sectorsPerCluster) && flagNoError) { + if (!_FAT_cache_writeSectors (cache, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, tempVar, ptr)) + { + flagNoError = false; + r->_errno = EIO; + } else { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } - // Write whole clusters - while ((remain >= partition->bytesPerCluster) && flagNoError) { - // allocate next cluster - _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); - if (!flagNoError) break; - // set indexes to the current position - uint32_t chunkEnd = position.cluster; - uint32_t nextChunkStart = position.cluster; - size_t chunkSize = partition->bytesPerCluster; - FILE_POSITION next_position = position; + // Write whole clusters + while ((remain >= partition->bytesPerCluster) && flagNoError) { + // allocate next cluster + _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); + if (!flagNoError) break; + // set indexes to the current position + uint32_t chunkEnd = position.cluster; + uint32_t nextChunkStart = position.cluster; + size_t chunkSize = partition->bytesPerCluster; + FILE_POSITION next_position = position; - // group consecutive clusters - while (flagNoError && + // group consecutive clusters + while (flagNoError && #ifdef LIMIT_SECTORS - (chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ) && + (chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ) && #endif - (chunkSize + partition->bytesPerCluster < remain)) { - // pretend to use up all sectors in next_position - next_position.sector = partition->sectorsPerCluster; - // get or allocate next cluster - _FAT_check_position_for_next_cluster(r, &next_position, partition, - remain - chunkSize, &flagNoError); - if (!flagNoError) break; // exit loop on error - nextChunkStart = next_position.cluster; - if (nextChunkStart != chunkEnd + 1) break; // exit loop if not consecutive - chunkEnd = nextChunkStart; - chunkSize += partition->bytesPerCluster; - } + (chunkSize + partition->bytesPerCluster < remain)) + { + // pretend to use up all sectors in next_position + next_position.sector = partition->sectorsPerCluster; + // get or allocate next cluster + _FAT_check_position_for_next_cluster(r, &next_position, partition, + remain - chunkSize, &flagNoError); + if (!flagNoError) break; // exit loop on error + nextChunkStart = next_position.cluster; + if (nextChunkStart != chunkEnd + 1) break; // exit loop if not consecutive + chunkEnd = nextChunkStart; + chunkSize += partition->bytesPerCluster; + } - if ( !_FAT_cache_writeSectors (cache, - _FAT_fat_clusterToSector(partition, position.cluster), chunkSize / BYTES_PER_READ, ptr)) { - flagNoError = false; - r->_errno = EIO; - break; - } - ptr += chunkSize; - remain -= chunkSize; + if ( !_FAT_cache_writeSectors (cache, + _FAT_fat_clusterToSector(partition, position.cluster), chunkSize / BYTES_PER_READ, ptr)) + { + flagNoError = false; + r->_errno = EIO; + break; + } + ptr += chunkSize; + remain -= chunkSize; - if ((chunkEnd != nextChunkStart) && _FAT_fat_isValidCluster(partition, nextChunkStart)) { - // new cluster is already allocated (because it was not consecutive) - position.cluster = nextChunkStart; - position.sector = 0; - } else { - // Allocate a new cluster when next writing the file - position.cluster = chunkEnd; - position.sector = partition->sectorsPerCluster; - } - } + if ((chunkEnd != nextChunkStart) && _FAT_fat_isValidCluster(partition, nextChunkStart)) { + // new cluster is already allocated (because it was not consecutive) + position.cluster = nextChunkStart; + position.sector = 0; + } else { + // Allocate a new cluster when next writing the file + position.cluster = chunkEnd; + position.sector = partition->sectorsPerCluster; + } + } - // allocate next cluster if needed - _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); + // allocate next cluster if needed + _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); - // Write remaining sectors - tempVar = remain / BYTES_PER_READ; // Number of sectors left - if ((tempVar > 0) && flagNoError) { - if (!_FAT_cache_writeSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), tempVar, ptr)) { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } + // Write remaining sectors + tempVar = remain / BYTES_PER_READ; // Number of sectors left + if ((tempVar > 0) && flagNoError) { + if (!_FAT_cache_writeSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), tempVar, ptr)) + { + flagNoError = false; + r->_errno = EIO; + } else { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } - // Last remaining sector - if ((remain > 0) && flagNoError) { - if (flagAppending) { - _FAT_cache_eraseWritePartialSector ( cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - } else { - _FAT_cache_writePartialSector ( cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - } - position.byte += remain; - remain = 0; - } + // Last remaining sector + if ((remain > 0) && flagNoError) { + if (flagAppending) { + _FAT_cache_eraseWritePartialSector ( cache, ptr, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); + } else { + _FAT_cache_writePartialSector ( cache, ptr, + _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); + } + position.byte += remain; + remain = 0; + } - // Amount written is the originally requested amount minus stuff remaining - len = len - remain; + // Amount written is the originally requested amount minus stuff remaining + len = len - remain; - // Update file information - file->modified = true; - if (file->append) { - // Appending doesn't affect the read pointer - file->appendPosition = position; - file->filesize += len; - } else { - // Writing also shifts the read pointer - file->rwPosition = position; - file->currentPosition += len; - if (file->filesize < file->currentPosition) { - file->filesize = file->currentPosition; - } - } - _FAT_unlock(&partition->lock); + // Update file information + file->modified = true; + if (file->append) { + // Appending doesn't affect the read pointer + file->appendPosition = position; + file->filesize += len; + } else { + // Writing also shifts the read pointer + file->rwPosition = position; + file->currentPosition += len; + if (file->filesize < file->currentPosition) { + file->filesize = file->currentPosition; + } + } + _FAT_unlock(&partition->lock); - return len; + return len; } off_t _FAT_seek_r (struct _reent *r, int fd, off_t pos, int dir) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - uint32_t cluster, nextCluster; - int clusCount; - off_t newPosition; - uint32_t position; + FILE_STRUCT* file = (FILE_STRUCT*) fd; + PARTITION* partition; + uint32_t cluster, nextCluster; + int clusCount; + off_t newPosition; + uint32_t position; - if ((file == NULL) || (file->inUse == false)) { - // invalid file - r->_errno = EBADF; - return -1; - } + if ((file == NULL) || (file->inUse == false)) { + // invalid file + r->_errno = EBADF; + return -1; + } - partition = file->partition; - _FAT_lock(&partition->lock); + partition = file->partition; + _FAT_lock(&partition->lock); - switch (dir) { - case SEEK_SET: - newPosition = pos; - break; - case SEEK_CUR: - newPosition = (off_t)file->currentPosition + pos; - break; - case SEEK_END: - newPosition = (off_t)file->filesize + pos; - break; - default: - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } + switch (dir) { + case SEEK_SET: + newPosition = pos; + break; + case SEEK_CUR: + newPosition = (off_t)file->currentPosition + pos; + break; + case SEEK_END: + newPosition = (off_t)file->filesize + pos; + break; + default: + _FAT_unlock(&partition->lock); + r->_errno = EINVAL; + return -1; + } - if ((pos > 0) && (newPosition < 0)) { - _FAT_unlock(&partition->lock); - r->_errno = EOVERFLOW; - return -1; - } + if ((pos > 0) && (newPosition < 0)) { + _FAT_unlock(&partition->lock); + r->_errno = EOVERFLOW; + return -1; + } - // newPosition can only be larger than the FILE_MAX_SIZE on platforms where - // off_t is larger than 32 bits. - if (newPosition < 0 || ((sizeof(newPosition) > 4) && newPosition > (off_t)FILE_MAX_SIZE)) { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } + // newPosition can only be larger than the FILE_MAX_SIZE on platforms where + // off_t is larger than 32 bits. + if (newPosition < 0 || ((sizeof(newPosition) > 4) && newPosition > (off_t)FILE_MAX_SIZE)) { + _FAT_unlock(&partition->lock); + r->_errno = EINVAL; + return -1; + } - position = (uint32_t)newPosition; + position = (uint32_t)newPosition; - // Only change the read/write position if it is within the bounds of the current filesize, - // or at the very edge of the file - if (position <= file->filesize && file->startCluster != CLUSTER_FREE) { - // Calculate where the correct cluster is - // how many clusters from start of file - clusCount = position / partition->bytesPerCluster; - cluster = file->startCluster; - if (position >= file->currentPosition) { - // start from current cluster - int currentCount = file->currentPosition / partition->bytesPerCluster; - if (file->rwPosition.sector == partition->sectorsPerCluster) { - currentCount--; - } - clusCount -= currentCount; - cluster = file->rwPosition.cluster; - } - // Calculate the sector and byte of the current position, - // and store them - file->rwPosition.sector = (position % partition->bytesPerCluster) / BYTES_PER_READ; - file->rwPosition.byte = position % BYTES_PER_READ; + // Only change the read/write position if it is within the bounds of the current filesize, + // or at the very edge of the file + if (position <= file->filesize && file->startCluster != CLUSTER_FREE) { + // Calculate where the correct cluster is + // how many clusters from start of file + clusCount = position / partition->bytesPerCluster; + cluster = file->startCluster; + if (position >= file->currentPosition) { + // start from current cluster + int currentCount = file->currentPosition / partition->bytesPerCluster; + if (file->rwPosition.sector == partition->sectorsPerCluster) { + currentCount--; + } + clusCount -= currentCount; + cluster = file->rwPosition.cluster; + } + // Calculate the sector and byte of the current position, + // and store them + file->rwPosition.sector = (position % partition->bytesPerCluster) / BYTES_PER_READ; + file->rwPosition.byte = position % BYTES_PER_READ; - nextCluster = _FAT_fat_nextCluster (partition, cluster); - while ((clusCount > 0) && (nextCluster != CLUSTER_FREE) && (nextCluster != CLUSTER_EOF)) { - clusCount--; - cluster = nextCluster; - nextCluster = _FAT_fat_nextCluster (partition, cluster); - } + nextCluster = _FAT_fat_nextCluster (partition, cluster); + while ((clusCount > 0) && (nextCluster != CLUSTER_FREE) && (nextCluster != CLUSTER_EOF)) { + clusCount--; + cluster = nextCluster; + nextCluster = _FAT_fat_nextCluster (partition, cluster); + } - // Check if ran out of clusters and it needs to allocate a new one - if (clusCount > 0) { - if ((clusCount == 1) && (file->filesize == position) && (file->rwPosition.sector == 0)) { - // Set flag to allocate a new cluster - file->rwPosition.sector = partition->sectorsPerCluster; - file->rwPosition.byte = 0; - } else { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } - } + // Check if ran out of clusters and it needs to allocate a new one + if (clusCount > 0) { + if ((clusCount == 1) && (file->filesize == position) && (file->rwPosition.sector == 0)) { + // Set flag to allocate a new cluster + file->rwPosition.sector = partition->sectorsPerCluster; + file->rwPosition.byte = 0; + } else { + _FAT_unlock(&partition->lock); + r->_errno = EINVAL; + return -1; + } + } - file->rwPosition.cluster = cluster; - } + file->rwPosition.cluster = cluster; + } - // Save position - file->currentPosition = position; + // Save position + file->currentPosition = position; - _FAT_unlock(&partition->lock); - return position; + _FAT_unlock(&partition->lock); + return position; } int _FAT_fstat_r (struct _reent *r, int fd, struct stat *st) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - DIR_ENTRY fileEntry; + FILE_STRUCT* file = (FILE_STRUCT*) fd; + PARTITION* partition; + DIR_ENTRY fileEntry; - if ((file == NULL) || (file->inUse == false)) { - // invalid file - r->_errno = EBADF; - return -1; - } + if ((file == NULL) || (file->inUse == false)) { + // invalid file + r->_errno = EBADF; + return -1; + } - partition = file->partition; - _FAT_lock(&partition->lock); + partition = file->partition; + _FAT_lock(&partition->lock); - // Get the file's entry data - fileEntry.dataStart = file->dirEntryStart; - fileEntry.dataEnd = file->dirEntryEnd; + // Get the file's entry data + fileEntry.dataStart = file->dirEntryStart; + fileEntry.dataEnd = file->dirEntryEnd; - if (!_FAT_directory_entryFromPosition (partition, &fileEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } + if (!_FAT_directory_entryFromPosition (partition, &fileEntry)) { + _FAT_unlock(&partition->lock); + r->_errno = EIO; + return -1; + } - // Fill in the stat struct - _FAT_directory_entryStat (partition, &fileEntry, st); + // Fill in the stat struct + _FAT_directory_entryStat (partition, &fileEntry, st); - // Fix stats that have changed since the file was openned - st->st_ino = (ino_t)(file->startCluster); // The file serial number is the start cluster - st->st_size = file->filesize; // File size + // Fix stats that have changed since the file was openned + st->st_ino = (ino_t)(file->startCluster); // The file serial number is the start cluster + st->st_size = file->filesize; // File size - _FAT_unlock(&partition->lock); - return 0; + _FAT_unlock(&partition->lock); + return 0; } int _FAT_ftruncate_r (struct _reent *r, int fd, off_t len) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - int ret=0; - uint32_t newSize = (uint32_t)len; + FILE_STRUCT* file = (FILE_STRUCT*) fd; + PARTITION* partition; + int ret=0; + uint32_t newSize = (uint32_t)len; - if (len < 0) { - // Trying to truncate to a negative size - r->_errno = EINVAL; - return -1; - } + if (len < 0) { + // Trying to truncate to a negative size + r->_errno = EINVAL; + return -1; + } - if ((sizeof(len) > 4) && len > (off_t)FILE_MAX_SIZE) { - // Trying to extend the file beyond what FAT supports - r->_errno = EFBIG; - return -1; - } + if ((sizeof(len) > 4) && len > (off_t)FILE_MAX_SIZE) { + // Trying to extend the file beyond what FAT supports + r->_errno = EFBIG; + return -1; + } - if (!file || !file->inUse) { - // invalid file - r->_errno = EBADF; - return -1; - } + if (!file || !file->inUse) { + // invalid file + r->_errno = EBADF; + return -1; + } - if (!file->write) { - // Read-only file - r->_errno = EINVAL; - return -1; - } + if (!file->write) { + // Read-only file + r->_errno = EINVAL; + return -1; + } - partition = file->partition; - _FAT_lock(&partition->lock); + partition = file->partition; + _FAT_lock(&partition->lock); - if (newSize > file->filesize) { - // Expanding the file - FILE_POSITION savedPosition; - uint32_t savedOffset; - // Get a new cluster for the start of the file if required - if (file->startCluster == CLUSTER_FREE) { - uint32_t tempNextCluster = _FAT_fat_linkFreeCluster (partition, CLUSTER_FREE); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort immediately - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - file->startCluster = tempNextCluster; + if (newSize > file->filesize) { + // Expanding the file + FILE_POSITION savedPosition; + uint32_t savedOffset; + // Get a new cluster for the start of the file if required + if (file->startCluster == CLUSTER_FREE) { + uint32_t tempNextCluster = _FAT_fat_linkFreeCluster (partition, CLUSTER_FREE); + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { + // Couldn't get a cluster, so abort immediately + _FAT_unlock(&partition->lock); + r->_errno = ENOSPC; + return -1; + } + file->startCluster = tempNextCluster; - file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; - file->rwPosition.byte = 0; - } - // Save the read/write pointer - savedPosition = file->rwPosition; - savedOffset = file->currentPosition; - // Set the position to the new size - file->currentPosition = newSize; - // Extend the file to the new position - if (!_FAT_file_extend_r (r, file)) { - ret = -1; - } - // Set the append position to the new rwPointer - if (file->append) { - file->appendPosition = file->rwPosition; - } - // Restore the old rwPointer; - file->rwPosition = savedPosition; - file->currentPosition = savedOffset; - } else if (newSize < file->filesize) { - // Shrinking the file - if (len == 0) { - // Cutting the file down to nothing, clear all clusters used - _FAT_fat_clearLinks (partition, file->startCluster); - file->startCluster = CLUSTER_FREE; + file->rwPosition.cluster = file->startCluster; + file->rwPosition.sector = 0; + file->rwPosition.byte = 0; + } + // Save the read/write pointer + savedPosition = file->rwPosition; + savedOffset = file->currentPosition; + // Set the position to the new size + file->currentPosition = newSize; + // Extend the file to the new position + if (!_FAT_file_extend_r (r, file)) { + ret = -1; + } + // Set the append position to the new rwPointer + if (file->append) { + file->appendPosition = file->rwPosition; + } + // Restore the old rwPointer; + file->rwPosition = savedPosition; + file->currentPosition = savedOffset; + } else if (newSize < file->filesize){ + // Shrinking the file + if (len == 0) { + // Cutting the file down to nothing, clear all clusters used + _FAT_fat_clearLinks (partition, file->startCluster); + file->startCluster = CLUSTER_FREE; - file->appendPosition.cluster = CLUSTER_FREE; - file->appendPosition.sector = 0; - file->appendPosition.byte = 0; - } else { - // Trimming the file down to the required size - unsigned int chainLength; - uint32_t lastCluster; + file->appendPosition.cluster = CLUSTER_FREE; + file->appendPosition.sector = 0; + file->appendPosition.byte = 0; + } else { + // Trimming the file down to the required size + unsigned int chainLength; + uint32_t lastCluster; - // Drop the unneeded end of the cluster chain. - // If the end falls on a cluster boundary, drop that cluster too, - // then set a flag to allocate a cluster as needed - chainLength = ((newSize-1) / partition->bytesPerCluster) + 1; - lastCluster = _FAT_fat_trimChain (partition, file->startCluster, chainLength); + // Drop the unneeded end of the cluster chain. + // If the end falls on a cluster boundary, drop that cluster too, + // then set a flag to allocate a cluster as needed + chainLength = ((newSize-1) / partition->bytesPerCluster) + 1; + lastCluster = _FAT_fat_trimChain (partition, file->startCluster, chainLength); - if (file->append) { - file->appendPosition.byte = newSize % BYTES_PER_READ; - // Does the end of the file fall on the edge of a cluster? - if (newSize % partition->bytesPerCluster == 0) { - // Set a flag to allocate a new cluster - file->appendPosition.sector = partition->sectorsPerCluster; - } else { - file->appendPosition.sector = (newSize % partition->bytesPerCluster) / BYTES_PER_READ; - } - file->appendPosition.cluster = lastCluster; - } - } - } else { - // Truncating to same length, so don't do anything - } + if (file->append) { + file->appendPosition.byte = newSize % BYTES_PER_READ; + // Does the end of the file fall on the edge of a cluster? + if (newSize % partition->bytesPerCluster == 0) { + // Set a flag to allocate a new cluster + file->appendPosition.sector = partition->sectorsPerCluster; + } else { + file->appendPosition.sector = (newSize % partition->bytesPerCluster) / BYTES_PER_READ; + } + file->appendPosition.cluster = lastCluster; + } + } + } else { + // Truncating to same length, so don't do anything + } - file->filesize = newSize; - file->modified = true; + file->filesize = newSize; + file->modified = true; - _FAT_unlock(&partition->lock); - return ret; + _FAT_unlock(&partition->lock); + return ret; } int _FAT_fsync_r (struct _reent *r, int fd) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - int ret = 0; + FILE_STRUCT* file = (FILE_STRUCT*) fd; + int ret = 0; - if (!file->inUse) { - r->_errno = EBADF; - return -1; - } + if (!file->inUse) { + r->_errno = EBADF; + return -1; + } - _FAT_lock(&file->partition->lock); + _FAT_lock(&file->partition->lock); - ret = _FAT_syncToDisc (file); - if (ret != 0) { - r->_errno = ret; - ret = -1; - } + ret = _FAT_syncToDisc (file); + if (ret != 0) { + r->_errno = ret; + ret = -1; + } - _FAT_unlock(&file->partition->lock); + _FAT_unlock(&file->partition->lock); - return ret; + return ret; } typedef int (*_frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); -int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void *callback_data) { - struct _reent r; - FILE_STRUCT file; - PARTITION* partition; - u32 cluster; - u32 sector; - u32 offset; // in sectors - u32 size; // in sectors - int ret = -1; - int fd; +int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void *callback_data) +{ + struct _reent r; + FILE_STRUCT file; + PARTITION* partition; + u32 cluster; + u32 sector; + u32 offset; // in sectors + u32 size; // in sectors + int ret = -1; + int fd; - fd = _FAT_open_r (&r, &file, path, O_RDONLY, 0); - if (fd == -1) return -1; - if (fd != (int)&file) return -1; + fd = _FAT_open_r (&r, &file, path, O_RDONLY, 0); + if (fd == -1) return -1; + if (fd != (int)&file) return -1; - partition = file.partition; - _FAT_lock(&partition->lock); + partition = file.partition; + _FAT_lock(&partition->lock); - size = file.filesize / BYTES_PER_READ; - cluster = file.startCluster; - offset = 0; + size = file.filesize / BYTES_PER_READ; + cluster = file.startCluster; + offset = 0; - do { - if (!_FAT_fat_isValidCluster(partition, cluster)) { - // invalid cluster - goto out; - } - // add cluster to fileinfo - sector = _FAT_fat_clusterToSector(partition, cluster); - if (append_fragment(callback_data, offset, sector, partition->sectorsPerCluster)) { - // too many fragments - goto out; - } - offset += partition->sectorsPerCluster; - cluster = _FAT_fat_nextCluster (partition, cluster); - } while (offset < size); + do { + if (!_FAT_fat_isValidCluster(partition, cluster)) { + // invalid cluster + goto out; + } + // add cluster to fileinfo + sector = _FAT_fat_clusterToSector(partition, cluster); + if (append_fragment(callback_data, offset, sector, partition->sectorsPerCluster)) { + // too many fragments + goto out; + } + offset += partition->sectorsPerCluster; + cluster = _FAT_fat_nextCluster (partition, cluster); + } while (offset < size); - // set size - append_fragment(callback_data, size, 0, 0); - // success - ret = 0; + // set size + append_fragment(callback_data, size, 0, 0); + // success + ret = 0; -out: - _FAT_unlock(&partition->lock); - _FAT_close_r(&r, fd); - return ret; + out: + _FAT_unlock(&partition->lock); + _FAT_close_r(&r, fd); + return ret; } diff --git a/source/libfat/fatfile.h b/source/libfat/fatfile.h index a6fb544b..448a5ee3 100644 --- a/source/libfat/fatfile.h +++ b/source/libfat/fatfile.h @@ -1,11 +1,11 @@ /* fatfile.h - - Functions used by the newlib disc stubs to interface with + + Functions used by the newlib disc stubs to interface with this library Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -42,29 +42,29 @@ #define FILE_MAX_SIZE ((uint32_t)0xFFFFFFFF) // 4GiB - 1B typedef struct { - u32 cluster; - sec_t sector; - s32 byte; + u32 cluster; + sec_t sector; + s32 byte; } FILE_POSITION; struct _FILE_STRUCT; struct _FILE_STRUCT { - uint32_t filesize; - uint32_t startCluster; - uint32_t currentPosition; - FILE_POSITION rwPosition; - FILE_POSITION appendPosition; - DIR_ENTRY_POSITION dirEntryStart; // Points to the start of the LFN entries of a file, or the alias for no LFN - DIR_ENTRY_POSITION dirEntryEnd; // Always points to the file's alias entry - PARTITION* partition; - struct _FILE_STRUCT* prevOpenFile; // The previous entry in a double-linked list of open files - struct _FILE_STRUCT* nextOpenFile; // The next entry in a double-linked list of open files - bool read; - bool write; - bool append; - bool inUse; - bool modified; + uint32_t filesize; + uint32_t startCluster; + uint32_t currentPosition; + FILE_POSITION rwPosition; + FILE_POSITION appendPosition; + DIR_ENTRY_POSITION dirEntryStart; // Points to the start of the LFN entries of a file, or the alias for no LFN + DIR_ENTRY_POSITION dirEntryEnd; // Always points to the file's alias entry + PARTITION* partition; + struct _FILE_STRUCT* prevOpenFile; // The previous entry in a double-linked list of open files + struct _FILE_STRUCT* nextOpenFile; // The next entry in a double-linked list of open files + bool read; + bool write; + bool append; + bool inUse; + bool modified; }; typedef struct _FILE_STRUCT FILE_STRUCT; diff --git a/source/libfat/file_allocation_table.c b/source/libfat/file_allocation_table.c index 4f7f6a20..639a6374 100644 --- a/source/libfat/file_allocation_table.c +++ b/source/libfat/file_allocation_table.c @@ -35,79 +35,83 @@ /* Gets the cluster linked from input cluster */ -uint32_t _FAT_fat_nextCluster(PARTITION* partition, uint32_t cluster) { - uint32_t nextCluster = CLUSTER_FREE; - sec_t sector; - int offset; +uint32_t _FAT_fat_nextCluster(PARTITION* partition, uint32_t cluster) +{ + uint32_t nextCluster = CLUSTER_FREE; + sec_t sector; + int offset; - if (cluster == CLUSTER_FREE) { - return CLUSTER_FREE; - } + if (cluster == CLUSTER_FREE) { + return CLUSTER_FREE; + } - switch (partition->filesysType) { - case FS_UNKNOWN: - return CLUSTER_ERROR; - break; + switch (partition->filesysType) + { + case FS_UNKNOWN: + return CLUSTER_ERROR; + break; - case FS_FAT12: { - u32 nextCluster_h; - sector = partition->fat.fatStart + (((cluster * 3) / 2) / BYTES_PER_READ); - offset = ((cluster * 3) / 2) % BYTES_PER_READ; + case FS_FAT12: + { + u32 nextCluster_h; + sector = partition->fat.fatStart + (((cluster * 3) / 2) / BYTES_PER_READ); + offset = ((cluster * 3) / 2) % BYTES_PER_READ; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u8)); + _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u8)); - offset++; + offset++; - if (offset >= BYTES_PER_READ) { - offset = 0; - sector++; - } - nextCluster_h = 0; + if (offset >= BYTES_PER_READ) { + offset = 0; + sector++; + } + nextCluster_h = 0; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster_h, sector, offset, sizeof(u8)); - nextCluster |= (nextCluster_h << 8); + _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster_h, sector, offset, sizeof(u8)); + nextCluster |= (nextCluster_h << 8); - if (cluster & 0x01) { - nextCluster = nextCluster >> 4; - } else { - nextCluster &= 0x0FFF; - } + if (cluster & 0x01) { + nextCluster = nextCluster >> 4; + } else { + nextCluster &= 0x0FFF; + } - if (nextCluster >= 0x0FF7) { - nextCluster = CLUSTER_EOF; - } + if (nextCluster >= 0x0FF7) + { + nextCluster = CLUSTER_EOF; + } - break; - } - case FS_FAT16: - sector = partition->fat.fatStart + ((cluster << 1) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 1)) << 1; + break; + } + case FS_FAT16: + sector = partition->fat.fatStart + ((cluster << 1) / BYTES_PER_READ); + offset = (cluster % (BYTES_PER_READ >> 1)) << 1; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u16)); + _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u16)); - if (nextCluster >= 0xFFF7) { - nextCluster = CLUSTER_EOF; - } - break; + if (nextCluster >= 0xFFF7) { + nextCluster = CLUSTER_EOF; + } + break; - case FS_FAT32: - sector = partition->fat.fatStart + ((cluster << 2) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 2)) << 2; + case FS_FAT32: + sector = partition->fat.fatStart + ((cluster << 2) / BYTES_PER_READ); + offset = (cluster % (BYTES_PER_READ >> 2)) << 2; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u32)); + _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u32)); - if (nextCluster >= 0x0FFFFFF7) { - nextCluster = CLUSTER_EOF; - } - break; + if (nextCluster >= 0x0FFFFFF7) { + nextCluster = CLUSTER_EOF; + } + break; - default: - return CLUSTER_ERROR; - break; - } + default: + return CLUSTER_ERROR; + break; + } - return nextCluster; + return nextCluster; } /* @@ -115,80 +119,82 @@ writes value into the correct offset within a partition's FAT, based on the cluster number. */ static bool _FAT_fat_writeFatEntry (PARTITION* partition, uint32_t cluster, uint32_t value) { - sec_t sector; - int offset; - uint32_t oldValue; + sec_t sector; + int offset; + uint32_t oldValue; - if ((cluster < CLUSTER_FIRST) || (cluster > partition->fat.lastCluster /* This will catch CLUSTER_ERROR */)) { - return false; - } + if ((cluster < CLUSTER_FIRST) || (cluster > partition->fat.lastCluster /* This will catch CLUSTER_ERROR */)) + { + return false; + } - switch (partition->filesysType) { - case FS_UNKNOWN: - return false; - break; + switch (partition->filesysType) + { + case FS_UNKNOWN: + return false; + break; - case FS_FAT12: - sector = partition->fat.fatStart + (((cluster * 3) / 2) / BYTES_PER_READ); - offset = ((cluster * 3) / 2) % BYTES_PER_READ; + case FS_FAT12: + sector = partition->fat.fatStart + (((cluster * 3) / 2) / BYTES_PER_READ); + offset = ((cluster * 3) / 2) % BYTES_PER_READ; - if (cluster & 0x01) { + if (cluster & 0x01) { - _FAT_cache_readLittleEndianValue (partition->cache, &oldValue, sector, offset, sizeof(u8)); + _FAT_cache_readLittleEndianValue (partition->cache, &oldValue, sector, offset, sizeof(u8)); - value = (value << 4) | (oldValue & 0x0F); + value = (value << 4) | (oldValue & 0x0F); - _FAT_cache_writeLittleEndianValue (partition->cache, value & 0xFF, sector, offset, sizeof(u8)); + _FAT_cache_writeLittleEndianValue (partition->cache, value & 0xFF, sector, offset, sizeof(u8)); - offset++; - if (offset >= BYTES_PER_READ) { - offset = 0; - sector++; - } + offset++; + if (offset >= BYTES_PER_READ) { + offset = 0; + sector++; + } - _FAT_cache_writeLittleEndianValue (partition->cache, (value >> 8) & 0xFF, sector, offset, sizeof(u8)); + _FAT_cache_writeLittleEndianValue (partition->cache, (value >> 8) & 0xFF, sector, offset, sizeof(u8)); - } else { + } else { - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u8)); + _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u8)); - offset++; - if (offset >= BYTES_PER_READ) { - offset = 0; - sector++; - } + offset++; + if (offset >= BYTES_PER_READ) { + offset = 0; + sector++; + } - _FAT_cache_readLittleEndianValue (partition->cache, &oldValue, sector, offset, sizeof(u8)); + _FAT_cache_readLittleEndianValue (partition->cache, &oldValue, sector, offset, sizeof(u8)); - value = ((value >> 8) & 0x0F) | (oldValue & 0xF0); + value = ((value >> 8) & 0x0F) | (oldValue & 0xF0); - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u8)); - } + _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u8)); + } - break; + break; - case FS_FAT16: - sector = partition->fat.fatStart + ((cluster << 1) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 1)) << 1; + case FS_FAT16: + sector = partition->fat.fatStart + ((cluster << 1) / BYTES_PER_READ); + offset = (cluster % (BYTES_PER_READ >> 1)) << 1; - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u16)); + _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u16)); - break; + break; - case FS_FAT32: - sector = partition->fat.fatStart + ((cluster << 2) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 2)) << 2; + case FS_FAT32: + sector = partition->fat.fatStart + ((cluster << 2) / BYTES_PER_READ); + offset = (cluster % (BYTES_PER_READ >> 2)) << 2; - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u32)); + _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u32)); - break; + break; - default: - return false; - break; - } + default: + return false; + break; + } - return true; + return true; } /*----------------------------------------------------------------- @@ -198,56 +204,57 @@ cluster number If an error occurs, return CLUSTER_ERROR -----------------------------------------------------------------*/ uint32_t _FAT_fat_linkFreeCluster(PARTITION* partition, uint32_t cluster) { - uint32_t firstFree; - uint32_t curLink; - uint32_t lastCluster; - bool loopedAroundFAT = false; + uint32_t firstFree; + uint32_t curLink; + uint32_t lastCluster; + bool loopedAroundFAT = false; - lastCluster = partition->fat.lastCluster; + lastCluster = partition->fat.lastCluster; - if (cluster > lastCluster) { - return CLUSTER_ERROR; - } + if (cluster > lastCluster) { + return CLUSTER_ERROR; + } - // Check if the cluster already has a link, and return it if so - curLink = _FAT_fat_nextCluster(partition, cluster); - if ((curLink >= CLUSTER_FIRST) && (curLink <= lastCluster)) { - return curLink; // Return the current link - don't allocate a new one - } + // Check if the cluster already has a link, and return it if so + curLink = _FAT_fat_nextCluster(partition, cluster); + if ((curLink >= CLUSTER_FIRST) && (curLink <= lastCluster)) { + return curLink; // Return the current link - don't allocate a new one + } - // Get a free cluster - firstFree = partition->fat.firstFree; - // Start at first valid cluster - if (firstFree < CLUSTER_FIRST) { - firstFree = CLUSTER_FIRST; - } + // Get a free cluster + firstFree = partition->fat.firstFree; + // Start at first valid cluster + if (firstFree < CLUSTER_FIRST) { + firstFree = CLUSTER_FIRST; + } - // Search until a free cluster is found - while (_FAT_fat_nextCluster(partition, firstFree) != CLUSTER_FREE) { - firstFree++; - if (firstFree > lastCluster) { - if (loopedAroundFAT) { - // If couldn't get a free cluster then return an error - partition->fat.firstFree = firstFree; - return CLUSTER_ERROR; - } else { - // Try looping back to the beginning of the FAT - // This was suggested by loopy - firstFree = CLUSTER_FIRST; - loopedAroundFAT = true; - } - } - } - partition->fat.firstFree = firstFree; + // Search until a free cluster is found + while (_FAT_fat_nextCluster(partition, firstFree) != CLUSTER_FREE) { + firstFree++; + if (firstFree > lastCluster) { + if (loopedAroundFAT) { + // If couldn't get a free cluster then return an error + partition->fat.firstFree = firstFree; + return CLUSTER_ERROR; + } else { + // Try looping back to the beginning of the FAT + // This was suggested by loopy + firstFree = CLUSTER_FIRST; + loopedAroundFAT = true; + } + } + } + partition->fat.firstFree = firstFree; - if ((cluster >= CLUSTER_FIRST) && (cluster < lastCluster)) { - // Update the linked from FAT entry - _FAT_fat_writeFatEntry (partition, cluster, firstFree); - } - // Create the linked to FAT entry - _FAT_fat_writeFatEntry (partition, firstFree, CLUSTER_EOF); + if ((cluster >= CLUSTER_FIRST) && (cluster < lastCluster)) + { + // Update the linked from FAT entry + _FAT_fat_writeFatEntry (partition, cluster, firstFree); + } + // Create the linked to FAT entry + _FAT_fat_writeFatEntry (partition, firstFree, CLUSTER_EOF); - return firstFree; + return firstFree; } /*----------------------------------------------------------------- @@ -257,26 +264,26 @@ cluster to 0 valued bytes, then returns the cluster number If an error occurs, return CLUSTER_ERROR -----------------------------------------------------------------*/ uint32_t _FAT_fat_linkFreeClusterCleared (PARTITION* partition, uint32_t cluster) { - uint32_t newCluster; - uint32_t i; - uint8_t emptySector[BYTES_PER_READ]; + uint32_t newCluster; + uint32_t i; + uint8_t emptySector[BYTES_PER_READ]; - // Link the cluster - newCluster = _FAT_fat_linkFreeCluster(partition, cluster); + // Link the cluster + newCluster = _FAT_fat_linkFreeCluster(partition, cluster); - if (newCluster == CLUSTER_FREE || newCluster == CLUSTER_ERROR) { - return CLUSTER_ERROR; - } + if (newCluster == CLUSTER_FREE || newCluster == CLUSTER_ERROR) { + return CLUSTER_ERROR; + } - // Clear all the sectors within the cluster - memset (emptySector, 0, BYTES_PER_READ); - for (i = 0; i < partition->sectorsPerCluster; i++) { - _FAT_cache_writeSectors (partition->cache, - _FAT_fat_clusterToSector (partition, newCluster) + i, - 1, emptySector); - } + // Clear all the sectors within the cluster + memset (emptySector, 0, BYTES_PER_READ); + for (i = 0; i < partition->sectorsPerCluster; i++) { + _FAT_cache_writeSectors (partition->cache, + _FAT_fat_clusterToSector (partition, newCluster) + i, + 1, emptySector); + } - return newCluster; + return newCluster; } @@ -285,28 +292,28 @@ _FAT_fat_clearLinks frees any cluster used by a file -----------------------------------------------------------------*/ bool _FAT_fat_clearLinks (PARTITION* partition, uint32_t cluster) { - uint32_t nextCluster; + uint32_t nextCluster; - if ((cluster < CLUSTER_FIRST) || (cluster > partition->fat.lastCluster /* This will catch CLUSTER_ERROR */)) - return false; + if ((cluster < CLUSTER_FIRST) || (cluster > partition->fat.lastCluster /* This will catch CLUSTER_ERROR */)) + return false; - // If this clears up more space in the FAT before the current free pointer, move it backwards - if (cluster < partition->fat.firstFree) { - partition->fat.firstFree = cluster; - } + // If this clears up more space in the FAT before the current free pointer, move it backwards + if (cluster < partition->fat.firstFree) { + partition->fat.firstFree = cluster; + } - while ((cluster != CLUSTER_EOF) && (cluster != CLUSTER_FREE) && (cluster != CLUSTER_ERROR)) { - // Store next cluster before erasing the link - nextCluster = _FAT_fat_nextCluster (partition, cluster); + while ((cluster != CLUSTER_EOF) && (cluster != CLUSTER_FREE) && (cluster != CLUSTER_ERROR)) { + // Store next cluster before erasing the link + nextCluster = _FAT_fat_nextCluster (partition, cluster); - // Erase the link - _FAT_fat_writeFatEntry (partition, cluster, CLUSTER_FREE); + // Erase the link + _FAT_fat_writeFatEntry (partition, cluster, CLUSTER_FREE); - // Move onto next cluster - cluster = nextCluster; - } + // Move onto next cluster + cluster = nextCluster; + } - return true; + return true; } /*----------------------------------------------------------------- @@ -318,32 +325,32 @@ dropped, and so on. Return the last cluster left in the chain. -----------------------------------------------------------------*/ uint32_t _FAT_fat_trimChain (PARTITION* partition, uint32_t startCluster, unsigned int chainLength) { - uint32_t nextCluster; + uint32_t nextCluster; - if (chainLength == 0) { - // Drop the entire chain - _FAT_fat_clearLinks (partition, startCluster); - return CLUSTER_FREE; - } else { - // Find the last cluster in the chain, and the one after it - chainLength--; - nextCluster = _FAT_fat_nextCluster (partition, startCluster); - while ((chainLength > 0) && (nextCluster != CLUSTER_FREE) && (nextCluster != CLUSTER_EOF)) { - chainLength--; - startCluster = nextCluster; - nextCluster = _FAT_fat_nextCluster (partition, startCluster); - } + if (chainLength == 0) { + // Drop the entire chain + _FAT_fat_clearLinks (partition, startCluster); + return CLUSTER_FREE; + } else { + // Find the last cluster in the chain, and the one after it + chainLength--; + nextCluster = _FAT_fat_nextCluster (partition, startCluster); + while ((chainLength > 0) && (nextCluster != CLUSTER_FREE) && (nextCluster != CLUSTER_EOF)) { + chainLength--; + startCluster = nextCluster; + nextCluster = _FAT_fat_nextCluster (partition, startCluster); + } - // Drop all clusters after the last in the chain - if (nextCluster != CLUSTER_FREE && nextCluster != CLUSTER_EOF) { - _FAT_fat_clearLinks (partition, nextCluster); - } + // Drop all clusters after the last in the chain + if (nextCluster != CLUSTER_FREE && nextCluster != CLUSTER_EOF) { + _FAT_fat_clearLinks (partition, nextCluster); + } - // Mark the last cluster in the chain as the end of the file - _FAT_fat_writeFatEntry (partition, startCluster, CLUSTER_EOF); + // Mark the last cluster in the chain as the end of the file + _FAT_fat_writeFatEntry (partition, startCluster, CLUSTER_EOF); - return startCluster; - } + return startCluster; + } } /*----------------------------------------------------------------- @@ -351,10 +358,10 @@ _FAT_fat_lastCluster Trace the cluster links until the last one is found -----------------------------------------------------------------*/ uint32_t _FAT_fat_lastCluster (PARTITION* partition, uint32_t cluster) { - while ((_FAT_fat_nextCluster(partition, cluster) != CLUSTER_FREE) && (_FAT_fat_nextCluster(partition, cluster) != CLUSTER_EOF)) { - cluster = _FAT_fat_nextCluster(partition, cluster); - } - return cluster; + while ((_FAT_fat_nextCluster(partition, cluster) != CLUSTER_FREE) && (_FAT_fat_nextCluster(partition, cluster) != CLUSTER_EOF)) { + cluster = _FAT_fat_nextCluster(partition, cluster); + } + return cluster; } /*----------------------------------------------------------------- @@ -362,15 +369,15 @@ _FAT_fat_freeClusterCount Return the number of free clusters available -----------------------------------------------------------------*/ unsigned int _FAT_fat_freeClusterCount (PARTITION* partition) { - unsigned int count = 0; - uint32_t curCluster; + unsigned int count = 0; + uint32_t curCluster; - for (curCluster = CLUSTER_FIRST; curCluster <= partition->fat.lastCluster; curCluster++) { - if (_FAT_fat_nextCluster(partition, curCluster) == CLUSTER_FREE) { - count++; - } - } + for (curCluster = CLUSTER_FIRST; curCluster <= partition->fat.lastCluster; curCluster++) { + if (_FAT_fat_nextCluster(partition, curCluster) == CLUSTER_FREE) { + count++; + } + } - return count; + return count; } diff --git a/source/libfat/file_allocation_table.h b/source/libfat/file_allocation_table.h index 7ea3f332..de500496 100644 --- a/source/libfat/file_allocation_table.h +++ b/source/libfat/file_allocation_table.h @@ -58,13 +58,13 @@ uint32_t _FAT_fat_lastCluster (PARTITION* partition, uint32_t cluster); unsigned int _FAT_fat_freeClusterCount (PARTITION* partition); static inline sec_t _FAT_fat_clusterToSector (PARTITION* partition, uint32_t cluster) { - return (cluster >= CLUSTER_FIRST) ? - ((cluster - CLUSTER_FIRST) * (sec_t)partition->sectorsPerCluster) + partition->dataStart : - partition->rootDirStart; + return (cluster >= CLUSTER_FIRST) ? + ((cluster - CLUSTER_FIRST) * (sec_t)partition->sectorsPerCluster) + partition->dataStart : + partition->rootDirStart; } static inline bool _FAT_fat_isValidCluster (PARTITION* partition, uint32_t cluster) { - return (cluster >= CLUSTER_FIRST) && (cluster <= partition->fat.lastCluster /* This will catch CLUSTER_ERROR */); + return (cluster >= CLUSTER_FIRST) && (cluster <= partition->fat.lastCluster /* This will catch CLUSTER_ERROR */); } #endif // _FAT_H diff --git a/source/libfat/filetime.c b/source/libfat/filetime.c index 0cb92db2..d297bf64 100644 --- a/source/libfat/filetime.c +++ b/source/libfat/filetime.c @@ -3,7 +3,7 @@ Conversion of file time and date values to various other types Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -42,66 +42,66 @@ uint16_t _FAT_filetime_getTimeFromRTC (void) { #ifdef USE_RTC_TIME - struct tm timeParts; - time_t epochTime; + struct tm timeParts; + time_t epochTime; + + if (time(&epochTime) == (time_t)-1) { + return 0; + } + localtime_r(&epochTime, &timeParts); - if (time(&epochTime) == (time_t)-1) { - return 0; - } - localtime_r(&epochTime, &timeParts); - - // Check that the values are all in range. - // If they are not, return 0 (no timestamp) - if ((timeParts.tm_hour < 0) || (timeParts.tm_hour > MAX_HOUR)) return 0; - if ((timeParts.tm_min < 0) || (timeParts.tm_min > MAX_MINUTE)) return 0; - if ((timeParts.tm_sec < 0) || (timeParts.tm_sec > MAX_SECOND)) return 0; - - return ( - ((timeParts.tm_hour & 0x1F) << 11) | - ((timeParts.tm_min & 0x3F) << 5) | - ((timeParts.tm_sec >> 1) & 0x1F) - ); + // Check that the values are all in range. + // If they are not, return 0 (no timestamp) + if ((timeParts.tm_hour < 0) || (timeParts.tm_hour > MAX_HOUR)) return 0; + if ((timeParts.tm_min < 0) || (timeParts.tm_min > MAX_MINUTE)) return 0; + if ((timeParts.tm_sec < 0) || (timeParts.tm_sec > MAX_SECOND)) return 0; + + return ( + ((timeParts.tm_hour & 0x1F) << 11) | + ((timeParts.tm_min & 0x3F) << 5) | + ((timeParts.tm_sec >> 1) & 0x1F) + ); #else - return 0; + return 0; #endif } uint16_t _FAT_filetime_getDateFromRTC (void) { #ifdef USE_RTC_TIME - struct tm timeParts; - time_t epochTime; + struct tm timeParts; + time_t epochTime; + + if (time(&epochTime) == (time_t)-1) { + return 0; + } + localtime_r(&epochTime, &timeParts); - if (time(&epochTime) == (time_t)-1) { - return 0; - } - localtime_r(&epochTime, &timeParts); - - if ((timeParts.tm_mon < MIN_MONTH) || (timeParts.tm_mon > MAX_MONTH)) return 0; - if ((timeParts.tm_mday < MIN_DAY) || (timeParts.tm_mday > MAX_DAY)) return 0; - - return ( - (((timeParts.tm_year - 80) & 0x7F) <<9) | // Adjust for MS-FAT base year (1980 vs 1900 for tm_year) - (((timeParts.tm_mon + 1) & 0xF) << 5) | - (timeParts.tm_mday & 0x1F) - ); + if ((timeParts.tm_mon < MIN_MONTH) || (timeParts.tm_mon > MAX_MONTH)) return 0; + if ((timeParts.tm_mday < MIN_DAY) || (timeParts.tm_mday > MAX_DAY)) return 0; + + return ( + (((timeParts.tm_year - 80) & 0x7F) <<9) | // Adjust for MS-FAT base year (1980 vs 1900 for tm_year) + (((timeParts.tm_mon + 1) & 0xF) << 5) | + (timeParts.tm_mday & 0x1F) + ); #else - return 0; + return 0; #endif } time_t _FAT_filetime_to_time_t (uint16_t t, uint16_t d) { - struct tm timeParts; + struct tm timeParts; - timeParts.tm_hour = t >> 11; - timeParts.tm_min = (t >> 5) & 0x3F; - timeParts.tm_sec = (t & 0x1F) << 1; - - timeParts.tm_mday = d & 0x1F; - timeParts.tm_mon = ((d >> 5) & 0x0F) - 1; - timeParts.tm_year = (d >> 9) + 80; - - timeParts.tm_isdst = 0; - - return mktime(&timeParts); + timeParts.tm_hour = t >> 11; + timeParts.tm_min = (t >> 5) & 0x3F; + timeParts.tm_sec = (t & 0x1F) << 1; + + timeParts.tm_mday = d & 0x1F; + timeParts.tm_mon = ((d >> 5) & 0x0F) - 1; + timeParts.tm_year = (d >> 9) + 80; + + timeParts.tm_isdst = 0; + + return mktime(&timeParts); } diff --git a/source/libfat/libfat.c b/source/libfat/libfat.c index 9a7bd7b3..0b3cbd06 100644 --- a/source/libfat/libfat.c +++ b/source/libfat/libfat.c @@ -39,156 +39,159 @@ #include "disc_fat.h" static const devoptab_t dotab_fat = { - "fat", - sizeof (FILE_STRUCT), - _FAT_open_r, - _FAT_close_r, - _FAT_write_r, - _FAT_read_r, - _FAT_seek_r, - _FAT_fstat_r, - _FAT_stat_r, - _FAT_link_r, - _FAT_unlink_r, - _FAT_chdir_r, - _FAT_rename_r, - _FAT_mkdir_r, - sizeof (DIR_STATE_STRUCT), - _FAT_diropen_r, - _FAT_dirreset_r, - _FAT_dirnext_r, - _FAT_dirclose_r, - _FAT_statvfs_r, - _FAT_ftruncate_r, - _FAT_fsync_r, - NULL /* Device data */ + "fat", + sizeof (FILE_STRUCT), + _FAT_open_r, + _FAT_close_r, + _FAT_write_r, + _FAT_read_r, + _FAT_seek_r, + _FAT_fstat_r, + _FAT_stat_r, + _FAT_link_r, + _FAT_unlink_r, + _FAT_chdir_r, + _FAT_rename_r, + _FAT_mkdir_r, + sizeof (DIR_STATE_STRUCT), + _FAT_diropen_r, + _FAT_dirreset_r, + _FAT_dirnext_r, + _FAT_dirclose_r, + _FAT_statvfs_r, + _FAT_ftruncate_r, + _FAT_fsync_r, + NULL /* Device data */ }; bool fatMount (const char* name, const DISC_INTERFACE* interface, sec_t startSector, uint32_t cacheSize, uint32_t SectorsPerPage) { - PARTITION* partition; - devoptab_t* devops; - char* nameCopy; + PARTITION* partition; + devoptab_t* devops; + char* nameCopy; - if (!interface->startup()) - return false; + if(!interface->startup()) + return false; - if (!interface->isInserted()) { - interface->shutdown(); - return false; - } + if(!interface->isInserted()) { + interface->shutdown(); + return false; + } - devops = _FAT_mem_allocate (sizeof(devoptab_t) + strlen(name) + 1); - if (!devops) { - interface->shutdown(); - return false; - } - // Use the space allocated at the end of the devoptab struct for storing the name - nameCopy = (char*)(devops+1); + devops = _FAT_mem_allocate (sizeof(devoptab_t) + strlen(name) + 1); + if (!devops) { + interface->shutdown(); + return false; + } + // Use the space allocated at the end of the devoptab struct for storing the name + nameCopy = (char*)(devops+1); - // Initialize the file system - partition = _FAT_partition_constructor (interface, cacheSize, SectorsPerPage, startSector); - if (!partition) { - _FAT_mem_free (devops); - interface->shutdown(); - return false; - } + // Initialize the file system + partition = _FAT_partition_constructor (interface, cacheSize, SectorsPerPage, startSector); + if (!partition) { + _FAT_mem_free (devops); + interface->shutdown(); + return false; + } - // Add an entry for this device to the devoptab table - memcpy (devops, &dotab_fat, sizeof(dotab_fat)); - strcpy (nameCopy, name); - devops->name = nameCopy; - devops->deviceData = partition; + // Add an entry for this device to the devoptab table + memcpy (devops, &dotab_fat, sizeof(dotab_fat)); + strcpy (nameCopy, name); + devops->name = nameCopy; + devops->deviceData = partition; - AddDevice (devops); + AddDevice (devops); - return true; + return true; } bool fatMountSimple (const char* name, const DISC_INTERFACE* interface) { - return fatMount (name, interface, 0, DEFAULT_CACHE_PAGES, DEFAULT_SECTORS_PAGE); + return fatMount (name, interface, 0, DEFAULT_CACHE_PAGES, DEFAULT_SECTORS_PAGE); } void fatUnmount (const char* name) { - devoptab_t *devops; - PARTITION* partition; - const DISC_INTERFACE *disc; + devoptab_t *devops; + PARTITION* partition; + const DISC_INTERFACE *disc; - devops = (devoptab_t*)GetDeviceOpTab (name); - if (!devops) { - return; - } + devops = (devoptab_t*)GetDeviceOpTab (name); + if (!devops) { + return; + } - // Perform a quick check to make sure we're dealing with a libfat controlled device - if (devops->open_r != dotab_fat.open_r) { - return; - } + // Perform a quick check to make sure we're dealing with a libfat controlled device + if (devops->open_r != dotab_fat.open_r) { + return; + } - if (RemoveDevice (name) == -1) { - return; - } + if (RemoveDevice (name) == -1) { + return; + } - partition = (PARTITION*)devops->deviceData; - disc = partition->disc; - _FAT_partition_destructor (partition); - _FAT_mem_free (devops); - disc->shutdown(); + partition = (PARTITION*)devops->deviceData; + disc = partition->disc; + _FAT_partition_destructor (partition); + _FAT_mem_free (devops); + disc->shutdown(); } bool fatInit (uint32_t cacheSize, bool setAsDefaultDevice) { - int i; - int defaultDevice = -1; - const DISC_INTERFACE *disc; + int i; + int defaultDevice = -1; + const DISC_INTERFACE *disc; - for (i = 0; - _FAT_disc_interfaces[i].name != NULL && _FAT_disc_interfaces[i].getInterface != NULL; - i++) { - disc = _FAT_disc_interfaces[i].getInterface(); - if (fatMount (_FAT_disc_interfaces[i].name, disc, 0, cacheSize, DEFAULT_SECTORS_PAGE)) { - // The first device to successfully mount is set as the default - if (defaultDevice < 0) { - defaultDevice = i; - } - } - } + for (i = 0; + _FAT_disc_interfaces[i].name != NULL && _FAT_disc_interfaces[i].getInterface != NULL; + i++) + { + disc = _FAT_disc_interfaces[i].getInterface(); + if (fatMount (_FAT_disc_interfaces[i].name, disc, 0, cacheSize, DEFAULT_SECTORS_PAGE)) { + // The first device to successfully mount is set as the default + if (defaultDevice < 0) { + defaultDevice = i; + } + } + } - if (defaultDevice < 0) { - // None of our devices mounted - return false; - } + if (defaultDevice < 0) { + // None of our devices mounted + return false; + } - if (setAsDefaultDevice) { - char filePath[MAXPATHLEN * 2]; - strcpy (filePath, _FAT_disc_interfaces[defaultDevice].name); - strcat (filePath, ":/"); + if (setAsDefaultDevice) { + char filePath[MAXPATHLEN * 2]; + strcpy (filePath, _FAT_disc_interfaces[defaultDevice].name); + strcat (filePath, ":/"); #ifdef ARGV_MAGIC - if ( __system_argv->argvMagic == ARGV_MAGIC && __system_argv->argc >= 1 && strrchr( __system_argv->argv[0], '/' )!=NULL ) { - // Check the app's path against each of our mounted devices, to see - // if we can support it. If so, change to that path. - for (i = 0; - _FAT_disc_interfaces[i].name != NULL && _FAT_disc_interfaces[i].getInterface != NULL; - i++) { - if ( !strncasecmp( __system_argv->argv[0], _FAT_disc_interfaces[i].name, - strlen(_FAT_disc_interfaces[i].name))) { - char *lastSlash; - strcpy(filePath, __system_argv->argv[0]); - lastSlash = strrchr( filePath, '/' ); + if ( __system_argv->argvMagic == ARGV_MAGIC && __system_argv->argc >= 1 && strrchr( __system_argv->argv[0], '/' )!=NULL ) { + // Check the app's path against each of our mounted devices, to see + // if we can support it. If so, change to that path. + for (i = 0; + _FAT_disc_interfaces[i].name != NULL && _FAT_disc_interfaces[i].getInterface != NULL; + i++) + { + if ( !strncasecmp( __system_argv->argv[0], _FAT_disc_interfaces[i].name, + strlen(_FAT_disc_interfaces[i].name))) + { + char *lastSlash; + strcpy(filePath, __system_argv->argv[0]); + lastSlash = strrchr( filePath, '/' ); - if ( NULL != lastSlash) { - if ( *(lastSlash - 1) == ':') lastSlash++; - *lastSlash = 0; - } - } - } - } + if ( NULL != lastSlash) { + if ( *(lastSlash - 1) == ':') lastSlash++; + *lastSlash = 0; + } + } + } + } #endif - chdir (filePath); - } + chdir (filePath); + } - return true; + return true; } bool fatInitDefault (void) { - return fatInit (DEFAULT_CACHE_PAGES, true); + return fatInit (DEFAULT_CACHE_PAGES, true); } diff --git a/source/libfat/lock.h b/source/libfat/lock.h index fecc68bd..73b8902b 100644 --- a/source/libfat/lock.h +++ b/source/libfat/lock.h @@ -33,20 +33,24 @@ #ifdef USE_LWP_LOCK -static inline void _FAT_lock_init(mutex_t *mutex) { - LWP_MutexInit(mutex, false); +static inline void _FAT_lock_init(mutex_t *mutex) +{ + LWP_MutexInit(mutex, false); } -static inline void _FAT_lock_deinit(mutex_t *mutex) { - LWP_MutexDestroy(*mutex); +static inline void _FAT_lock_deinit(mutex_t *mutex) +{ + LWP_MutexDestroy(*mutex); } -static inline void _FAT_lock(mutex_t *mutex) { - LWP_MutexLock(*mutex); +static inline void _FAT_lock(mutex_t *mutex) +{ + LWP_MutexLock(*mutex); } -static inline void _FAT_unlock(mutex_t *mutex) { - LWP_MutexUnlock(*mutex); +static inline void _FAT_unlock(mutex_t *mutex) +{ + LWP_MutexUnlock(*mutex); } #else @@ -56,20 +60,24 @@ static inline void _FAT_unlock(mutex_t *mutex) { typedef int mutex_t; #endif -static inline void _FAT_lock_init(mutex_t *mutex) { - return; +static inline void _FAT_lock_init(mutex_t *mutex) +{ + return; } -static inline void _FAT_lock_deinit(mutex_t *mutex) { - return; +static inline void _FAT_lock_deinit(mutex_t *mutex) +{ + return; } -static inline void _FAT_lock(mutex_t *mutex) { - return; +static inline void _FAT_lock(mutex_t *mutex) +{ + return; } -static inline void _FAT_unlock(mutex_t *mutex) { - return; +static inline void _FAT_unlock(mutex_t *mutex) +{ + return; } #endif // USE_LWP_LOCK diff --git a/source/libfat/mem_allocate.h b/source/libfat/mem_allocate.h index 30564c79..2d38f9ce 100644 --- a/source/libfat/mem_allocate.h +++ b/source/libfat/mem_allocate.h @@ -34,16 +34,16 @@ #include static inline void* _FAT_mem_allocate (size_t size) { - return malloc (size); + return malloc (size); } static inline void* _FAT_mem_align (size_t size) { - return memalign (32, size); + return memalign (32, size); } static inline void _FAT_mem_free (void* mem) { - free (mem); + free (mem); } #endif // _MEM_ALLOCATE_H diff --git a/source/libfat/partition.c b/source/libfat/partition.c index b3bdb871..955468de 100644 --- a/source/libfat/partition.c +++ b/source/libfat/partition.c @@ -51,257 +51,262 @@ Data offsets // BIOS Parameter Block offsets enum BPB { - BPB_jmpBoot = 0x00, - BPB_OEMName = 0x03, - // BIOS Parameter Block - BPB_bytesPerSector = 0x0B, - BPB_sectorsPerCluster = 0x0D, - BPB_reservedSectors = 0x0E, - BPB_numFATs = 0x10, - BPB_rootEntries = 0x11, - BPB_numSectorsSmall = 0x13, - BPB_mediaDesc = 0x15, - BPB_sectorsPerFAT = 0x16, - BPB_sectorsPerTrk = 0x18, - BPB_numHeads = 0x1A, - BPB_numHiddenSectors = 0x1C, - BPB_numSectors = 0x20, - // Ext BIOS Parameter Block for FAT16 - BPB_FAT16_driveNumber = 0x24, - BPB_FAT16_reserved1 = 0x25, - BPB_FAT16_extBootSig = 0x26, - BPB_FAT16_volumeID = 0x27, - BPB_FAT16_volumeLabel = 0x2B, - BPB_FAT16_fileSysType = 0x36, - // Bootcode - BPB_FAT16_bootCode = 0x3E, - // FAT32 extended block - BPB_FAT32_sectorsPerFAT32 = 0x24, - BPB_FAT32_extFlags = 0x28, - BPB_FAT32_fsVer = 0x2A, - BPB_FAT32_rootClus = 0x2C, - BPB_FAT32_fsInfo = 0x30, - BPB_FAT32_bkBootSec = 0x32, - // Ext BIOS Parameter Block for FAT32 - BPB_FAT32_driveNumber = 0x40, - BPB_FAT32_reserved1 = 0x41, - BPB_FAT32_extBootSig = 0x42, - BPB_FAT32_volumeID = 0x43, - BPB_FAT32_volumeLabel = 0x47, - BPB_FAT32_fileSysType = 0x52, - // Bootcode - BPB_FAT32_bootCode = 0x5A, - BPB_bootSig_55 = 0x1FE, - BPB_bootSig_AA = 0x1FF + BPB_jmpBoot = 0x00, + BPB_OEMName = 0x03, + // BIOS Parameter Block + BPB_bytesPerSector = 0x0B, + BPB_sectorsPerCluster = 0x0D, + BPB_reservedSectors = 0x0E, + BPB_numFATs = 0x10, + BPB_rootEntries = 0x11, + BPB_numSectorsSmall = 0x13, + BPB_mediaDesc = 0x15, + BPB_sectorsPerFAT = 0x16, + BPB_sectorsPerTrk = 0x18, + BPB_numHeads = 0x1A, + BPB_numHiddenSectors = 0x1C, + BPB_numSectors = 0x20, + // Ext BIOS Parameter Block for FAT16 + BPB_FAT16_driveNumber = 0x24, + BPB_FAT16_reserved1 = 0x25, + BPB_FAT16_extBootSig = 0x26, + BPB_FAT16_volumeID = 0x27, + BPB_FAT16_volumeLabel = 0x2B, + BPB_FAT16_fileSysType = 0x36, + // Bootcode + BPB_FAT16_bootCode = 0x3E, + // FAT32 extended block + BPB_FAT32_sectorsPerFAT32 = 0x24, + BPB_FAT32_extFlags = 0x28, + BPB_FAT32_fsVer = 0x2A, + BPB_FAT32_rootClus = 0x2C, + BPB_FAT32_fsInfo = 0x30, + BPB_FAT32_bkBootSec = 0x32, + // Ext BIOS Parameter Block for FAT32 + BPB_FAT32_driveNumber = 0x40, + BPB_FAT32_reserved1 = 0x41, + BPB_FAT32_extBootSig = 0x42, + BPB_FAT32_volumeID = 0x43, + BPB_FAT32_volumeLabel = 0x47, + BPB_FAT32_fileSysType = 0x52, + // Bootcode + BPB_FAT32_bootCode = 0x5A, + BPB_bootSig_55 = 0x1FE, + BPB_bootSig_AA = 0x1FF }; static const char FAT_SIG[3] = {'F', 'A', 'T'}; -sec_t FindFirstValidPartition(const DISC_INTERFACE* disc) { - uint8_t part_table[16*4]; - uint8_t *ptr; - int i; +sec_t FindFirstValidPartition(const DISC_INTERFACE* disc) +{ + uint8_t part_table[16*4]; + uint8_t *ptr; + int i; - uint8_t sectorBuffer[BYTES_PER_READ] = {0}; + uint8_t sectorBuffer[BYTES_PER_READ] = {0}; - // Read first sector of disc - if (!_FAT_disc_readSectors (disc, 0, 1, sectorBuffer)) { - return 0; - } + // Read first sector of disc + if (!_FAT_disc_readSectors (disc, 0, 1, sectorBuffer)) { + return 0; + } - memcpy(part_table,sectorBuffer+0x1BE,16*4); - ptr = part_table; + memcpy(part_table,sectorBuffer+0x1BE,16*4); + ptr = part_table; - for (i=0;i<4;i++,ptr+=16) { - sec_t part_lba = u8array_to_u32(ptr, 0x8); + for(i=0;i<4;i++,ptr+=16) { + sec_t part_lba = u8array_to_u32(ptr, 0x8); - if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || - !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - return part_lba; - } + if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || + !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { + return part_lba; + } - if (ptr[4]==0) continue; + if(ptr[4]==0) continue; - if (ptr[4]==0x0F) { - sec_t part_lba2=part_lba; - sec_t next_lba2=0; - int n; + if(ptr[4]==0x0F) { + sec_t part_lba2=part_lba; + sec_t next_lba2=0; + int n; - for (n=0;n<8;n++) { // max 8 logic partitions - if (!_FAT_disc_readSectors (disc, part_lba+next_lba2, 1, sectorBuffer)) return 0; + for(n=0;n<8;n++) // max 8 logic partitions + { + if(!_FAT_disc_readSectors (disc, part_lba+next_lba2, 1, sectorBuffer)) return 0; - part_lba2 = part_lba + next_lba2 + u8array_to_u32(sectorBuffer, 0x1C6) ; - next_lba2 = u8array_to_u32(sectorBuffer, 0x1D6); + part_lba2 = part_lba + next_lba2 + u8array_to_u32(sectorBuffer, 0x1C6) ; + next_lba2 = u8array_to_u32(sectorBuffer, 0x1D6); - if (!_FAT_disc_readSectors (disc, part_lba2, 1, sectorBuffer)) return 0; + if(!_FAT_disc_readSectors (disc, part_lba2, 1, sectorBuffer)) return 0; - if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || - !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - return part_lba2; - } + if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || + !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) + { + return part_lba2; + } - if (next_lba2==0) break; - } - } else { - if (!_FAT_disc_readSectors (disc, part_lba, 1, sectorBuffer)) return 0; - if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || - !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - return part_lba; - } - } - } - return 0; + if(next_lba2==0) break; + } + } else { + if(!_FAT_disc_readSectors (disc, part_lba, 1, sectorBuffer)) return 0; + if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || + !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { + return part_lba; + } + } + } + return 0; } PARTITION* _FAT_partition_constructor (const DISC_INTERFACE* disc, uint32_t cacheSize, uint32_t sectorsPerPage, sec_t startSector) { - PARTITION* partition; - uint8_t sectorBuffer[BYTES_PER_READ] = {0}; + PARTITION* partition; + uint8_t sectorBuffer[BYTES_PER_READ] = {0}; - // Read first sector of disc - if (!_FAT_disc_readSectors (disc, startSector, 1, sectorBuffer)) { - return NULL; - } + // Read first sector of disc + if (!_FAT_disc_readSectors (disc, startSector, 1, sectorBuffer)) { + return NULL; + } - // Make sure it is a valid MBR or boot sector - if ( (sectorBuffer[BPB_bootSig_55] != 0x55) || (sectorBuffer[BPB_bootSig_AA] != 0xAA)) { - return NULL; - } + // Make sure it is a valid MBR or boot sector + if ( (sectorBuffer[BPB_bootSig_55] != 0x55) || (sectorBuffer[BPB_bootSig_AA] != 0xAA)) { + return NULL; + } - if (startSector != 0) { - // We're told where to start the partition, so just accept it - } else if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - // Check if there is a FAT string, which indicates this is a boot sector - startSector = 0; - } else if (!memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - // Check for FAT32 - startSector = 0; - } else { - startSector = FindFirstValidPartition(disc); - if (!_FAT_disc_readSectors (disc, startSector, 1, sectorBuffer)) { - return NULL; - } - } + if (startSector != 0) { + // We're told where to start the partition, so just accept it + } else if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { + // Check if there is a FAT string, which indicates this is a boot sector + startSector = 0; + } else if (!memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { + // Check for FAT32 + startSector = 0; + } else { + startSector = FindFirstValidPartition(disc); + if (!_FAT_disc_readSectors (disc, startSector, 1, sectorBuffer)) { + return NULL; + } + } - // Now verify that this is indeed a FAT partition - if (memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) && - memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - return NULL; - } + // Now verify that this is indeed a FAT partition + if (memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) && + memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) + { + return NULL; + } - // check again for the last two cases to make sure that we really have a FAT filesystem here - // and won't corrupt any data - if (memcmp(sectorBuffer + BPB_FAT16_fileSysType, "FAT", 3) != 0 && memcmp(sectorBuffer + BPB_FAT32_fileSysType, "FAT32", 5) != 0) { - return NULL; - } + // check again for the last two cases to make sure that we really have a FAT filesystem here + // and won't corrupt any data + if(memcmp(sectorBuffer + BPB_FAT16_fileSysType, "FAT", 3) != 0 && memcmp(sectorBuffer + BPB_FAT32_fileSysType, "FAT32", 5) != 0) + { + return NULL; + } - partition = (PARTITION*) _FAT_mem_allocate (sizeof(PARTITION)); - if (partition == NULL) { - return NULL; - } + partition = (PARTITION*) _FAT_mem_allocate (sizeof(PARTITION)); + if (partition == NULL) { + return NULL; + } - _FAT_startSector = startSector; + _FAT_startSector = startSector; - // Init the partition lock - _FAT_lock_init(&partition->lock); + // Init the partition lock + _FAT_lock_init(&partition->lock); - // Set partition's disc interface - partition->disc = disc; + // Set partition's disc interface + partition->disc = disc; - // Store required information about the file system - partition->fat.sectorsPerFat = u8array_to_u16(sectorBuffer, BPB_sectorsPerFAT); - if (partition->fat.sectorsPerFat == 0) { - partition->fat.sectorsPerFat = u8array_to_u32( sectorBuffer, BPB_FAT32_sectorsPerFAT32); - } + // Store required information about the file system + partition->fat.sectorsPerFat = u8array_to_u16(sectorBuffer, BPB_sectorsPerFAT); + if (partition->fat.sectorsPerFat == 0) { + partition->fat.sectorsPerFat = u8array_to_u32( sectorBuffer, BPB_FAT32_sectorsPerFAT32); + } - partition->numberOfSectors = u8array_to_u16( sectorBuffer, BPB_numSectorsSmall); - if (partition->numberOfSectors == 0) { - partition->numberOfSectors = u8array_to_u32( sectorBuffer, BPB_numSectors); - } + partition->numberOfSectors = u8array_to_u16( sectorBuffer, BPB_numSectorsSmall); + if (partition->numberOfSectors == 0) { + partition->numberOfSectors = u8array_to_u32( sectorBuffer, BPB_numSectors); + } - partition->bytesPerSector = BYTES_PER_READ; // Sector size is redefined to be 512 bytes - partition->sectorsPerCluster = sectorBuffer[BPB_sectorsPerCluster] * u8array_to_u16(sectorBuffer, BPB_bytesPerSector) / BYTES_PER_READ; - partition->bytesPerCluster = partition->bytesPerSector * partition->sectorsPerCluster; - partition->fat.fatStart = startSector + u8array_to_u16(sectorBuffer, BPB_reservedSectors); + partition->bytesPerSector = BYTES_PER_READ; // Sector size is redefined to be 512 bytes + partition->sectorsPerCluster = sectorBuffer[BPB_sectorsPerCluster] * u8array_to_u16(sectorBuffer, BPB_bytesPerSector) / BYTES_PER_READ; + partition->bytesPerCluster = partition->bytesPerSector * partition->sectorsPerCluster; + partition->fat.fatStart = startSector + u8array_to_u16(sectorBuffer, BPB_reservedSectors); - partition->rootDirStart = partition->fat.fatStart + (sectorBuffer[BPB_numFATs] * partition->fat.sectorsPerFat); - partition->dataStart = partition->rootDirStart + - (( u8array_to_u16(sectorBuffer, BPB_rootEntries) * DIR_ENTRY_DATA_SIZE) / partition->bytesPerSector); + partition->rootDirStart = partition->fat.fatStart + (sectorBuffer[BPB_numFATs] * partition->fat.sectorsPerFat); + partition->dataStart = partition->rootDirStart + + (( u8array_to_u16(sectorBuffer, BPB_rootEntries) * DIR_ENTRY_DATA_SIZE) / partition->bytesPerSector); - partition->totalSize = ((uint64_t)partition->numberOfSectors - (partition->dataStart - startSector)) * (uint64_t)partition->bytesPerSector; + partition->totalSize = ((uint64_t)partition->numberOfSectors - (partition->dataStart - startSector)) * (uint64_t)partition->bytesPerSector; - // Store info about FAT - uint32_t clusterCount = (partition->numberOfSectors - (uint32_t)(partition->dataStart - startSector)) / partition->sectorsPerCluster; - partition->fat.lastCluster = clusterCount + CLUSTER_FIRST - 1; - partition->fat.firstFree = CLUSTER_FIRST; + // Store info about FAT + uint32_t clusterCount = (partition->numberOfSectors - (uint32_t)(partition->dataStart - startSector)) / partition->sectorsPerCluster; + partition->fat.lastCluster = clusterCount + CLUSTER_FIRST - 1; + partition->fat.firstFree = CLUSTER_FIRST; - if (clusterCount < CLUSTERS_PER_FAT12) { - partition->filesysType = FS_FAT12; // FAT12 volume - } else if (clusterCount < CLUSTERS_PER_FAT16) { - partition->filesysType = FS_FAT16; // FAT16 volume - } else { - partition->filesysType = FS_FAT32; // FAT32 volume - } + if (clusterCount < CLUSTERS_PER_FAT12) { + partition->filesysType = FS_FAT12; // FAT12 volume + } else if (clusterCount < CLUSTERS_PER_FAT16) { + partition->filesysType = FS_FAT16; // FAT16 volume + } else { + partition->filesysType = FS_FAT32; // FAT32 volume + } - if (partition->filesysType != FS_FAT32) { - partition->rootDirCluster = FAT16_ROOT_DIR_CLUSTER; - } else { - // Set up for the FAT32 way - partition->rootDirCluster = u8array_to_u32(sectorBuffer, BPB_FAT32_rootClus); - // Check if FAT mirroring is enabled - if (!(sectorBuffer[BPB_FAT32_extFlags] & 0x80)) { - // Use the active FAT - partition->fat.fatStart = partition->fat.fatStart + ( partition->fat.sectorsPerFat * (sectorBuffer[BPB_FAT32_extFlags] & 0x0F)); - } - } + if (partition->filesysType != FS_FAT32) { + partition->rootDirCluster = FAT16_ROOT_DIR_CLUSTER; + } else { + // Set up for the FAT32 way + partition->rootDirCluster = u8array_to_u32(sectorBuffer, BPB_FAT32_rootClus); + // Check if FAT mirroring is enabled + if (!(sectorBuffer[BPB_FAT32_extFlags] & 0x80)) { + // Use the active FAT + partition->fat.fatStart = partition->fat.fatStart + ( partition->fat.sectorsPerFat * (sectorBuffer[BPB_FAT32_extFlags] & 0x0F)); + } + } - // Create a cache to use - partition->cache = _FAT_cache_constructor (cacheSize, sectorsPerPage, partition->disc, startSector+partition->numberOfSectors); + // Create a cache to use + partition->cache = _FAT_cache_constructor (cacheSize, sectorsPerPage, partition->disc, startSector+partition->numberOfSectors); - // Set current directory to the root - partition->cwdCluster = partition->rootDirCluster; + // Set current directory to the root + partition->cwdCluster = partition->rootDirCluster; - // Check if this disc is writable, and set the readOnly property appropriately - partition->readOnly = !(_FAT_disc_features(disc) & FEATURE_MEDIUM_CANWRITE); + // Check if this disc is writable, and set the readOnly property appropriately + partition->readOnly = !(_FAT_disc_features(disc) & FEATURE_MEDIUM_CANWRITE); - // There are currently no open files on this partition - partition->openFileCount = 0; - partition->firstOpenFile = NULL; + // There are currently no open files on this partition + partition->openFileCount = 0; + partition->firstOpenFile = NULL; - return partition; + return partition; } void _FAT_partition_destructor (PARTITION* partition) { - FILE_STRUCT* nextFile; + FILE_STRUCT* nextFile; - _FAT_lock(&partition->lock); + _FAT_lock(&partition->lock); - // Synchronize open files - nextFile = partition->firstOpenFile; - while (nextFile) { - _FAT_syncToDisc (nextFile); - nextFile = nextFile->nextOpenFile; - } + // Synchronize open files + nextFile = partition->firstOpenFile; + while (nextFile) { + _FAT_syncToDisc (nextFile); + nextFile = nextFile->nextOpenFile; + } - // Free memory used by the cache, writing it to disc at the same time - _FAT_cache_destructor (partition->cache); + // Free memory used by the cache, writing it to disc at the same time + _FAT_cache_destructor (partition->cache); - // Unlock the partition and destroy the lock - _FAT_unlock(&partition->lock); - _FAT_lock_deinit(&partition->lock); + // Unlock the partition and destroy the lock + _FAT_unlock(&partition->lock); + _FAT_lock_deinit(&partition->lock); - // Free memory used by the partition - _FAT_mem_free (partition); + // Free memory used by the partition + _FAT_mem_free (partition); } PARTITION* _FAT_partition_getPartitionFromPath (const char* path) { - const devoptab_t *devops; + const devoptab_t *devops; - devops = GetDeviceOpTab (path); + devops = GetDeviceOpTab (path); - if (!devops) { - return NULL; - } + if (!devops) { + return NULL; + } - return (PARTITION*)devops->deviceData; + return (PARTITION*)devops->deviceData; } diff --git a/source/libfat/partition.h b/source/libfat/partition.h index 0648a80d..5c9595e0 100644 --- a/source/libfat/partition.h +++ b/source/libfat/partition.h @@ -41,32 +41,32 @@ extern const char* DEVICE_NAME; typedef enum {FS_UNKNOWN, FS_FAT12, FS_FAT16, FS_FAT32} FS_TYPE; typedef struct { - sec_t fatStart; - uint32_t sectorsPerFat; - uint32_t lastCluster; - uint32_t firstFree; + sec_t fatStart; + uint32_t sectorsPerFat; + uint32_t lastCluster; + uint32_t firstFree; } FAT; typedef struct { - const DISC_INTERFACE* disc; - CACHE* cache; - // Info about the partition - FS_TYPE filesysType; - uint64_t totalSize; - sec_t rootDirStart; - uint32_t rootDirCluster; - uint32_t numberOfSectors; - sec_t dataStart; - uint32_t bytesPerSector; - uint32_t sectorsPerCluster; - uint32_t bytesPerCluster; - FAT fat; - // Values that may change after construction - uint32_t cwdCluster; // Current working directory cluster - int openFileCount; - struct _FILE_STRUCT* firstOpenFile; // The start of a linked list of files - mutex_t lock; // A lock for partition operations - bool readOnly; // If this is set, then do not try writing to the disc + const DISC_INTERFACE* disc; + CACHE* cache; + // Info about the partition + FS_TYPE filesysType; + uint64_t totalSize; + sec_t rootDirStart; + uint32_t rootDirCluster; + uint32_t numberOfSectors; + sec_t dataStart; + uint32_t bytesPerSector; + uint32_t sectorsPerCluster; + uint32_t bytesPerCluster; + FAT fat; + // Values that may change after construction + uint32_t cwdCluster; // Current working directory cluster + int openFileCount; + struct _FILE_STRUCT* firstOpenFile; // The start of a linked list of files + mutex_t lock; // A lock for partition operations + bool readOnly; // If this is set, then do not try writing to the disc } PARTITION; /* diff --git a/source/libntfs/acls.c b/source/libntfs/acls.c index 90ae06a7..4bfd3652 100644 --- a/source/libntfs/acls.c +++ b/source/libntfs/acls.c @@ -23,9 +23,9 @@ */ #ifdef HAVE_CONFIG_H -/* - * integration into ntfs-3g - */ + /* + * integration into ntfs-3g + */ #include "config.h" #ifdef HAVE_STDIO_H @@ -60,10 +60,10 @@ #include "misc.h" #else -/* - * integration into secaudit, check whether Win32, - * may have to be adapted to compiler or something else - */ + /* + * integration into secaudit, check whether Win32, + * may have to be adapted to compiler or something else + */ #ifndef WIN32 #if defined(__WIN32) | defined(__WIN32__) | defined(WNSC) @@ -79,26 +79,26 @@ #include #include -/* - * integration into secaudit/Win32 - */ + /* + * integration into secaudit/Win32 + */ #ifdef WIN32 #include #include #define __LITTLE_ENDIAN 1234 #define __BYTE_ORDER __LITTLE_ENDIAN #else -/* - * integration into secaudit/STSC - */ + /* + * integration into secaudit/STSC + */ #ifdef STSC #include #undef __BYTE_ORDER #define __BYTE_ORDER __BIG_ENDIAN #else -/* - * integration into secaudit/Linux - */ + /* + * integration into secaudit/Linux + */ #include #include #include @@ -117,11 +117,11 @@ */ static const char nullsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 0, /* base */ - 0, 0, 0, 0 /* 1st level */ -}; + 1, /* revision */ + 1, /* auth count */ + 0, 0, 0, 0, 0, 0, /* base */ + 0, 0, 0, 0 /* 1st level */ + }; static const SID *nullsid = (const SID*)nullsidbytes; @@ -130,10 +130,10 @@ static const SID *nullsid = (const SID*)nullsidbytes; */ static const char worldsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 1, /* base */ - 0, 0, 0, 0 /* 1st level */ + 1, /* revision */ + 1, /* auth count */ + 0, 0, 0, 0, 0, 1, /* base */ + 0, 0, 0, 0 /* 1st level */ } ; const SID *worldsid = (const SID*)worldsidbytes; @@ -143,11 +143,11 @@ const SID *worldsid = (const SID*)worldsidbytes; */ static const char adminsidbytes[] = { - 1, /* revision */ - 2, /* auth count */ - 0, 0, 0, 0, 0, 5, /* base */ - 32, 0, 0, 0, /* 1st level */ - 32, 2, 0, 0 /* 2nd level */ + 1, /* revision */ + 2, /* auth count */ + 0, 0, 0, 0, 0, 5, /* base */ + 32, 0, 0, 0, /* 1st level */ + 32, 2, 0, 0 /* 2nd level */ }; const SID *adminsid = (const SID*)adminsidbytes; @@ -157,11 +157,11 @@ const SID *adminsid = (const SID*)adminsidbytes; */ static const char systemsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 5, /* base */ - 18, 0, 0, 0 /* 1st level */ -}; + 1, /* revision */ + 1, /* auth count */ + 0, 0, 0, 0, 0, 5, /* base */ + 18, 0, 0, 0 /* 1st level */ + }; static const SID *systemsid = (const SID*)systemsidbytes; @@ -171,10 +171,10 @@ static const SID *systemsid = (const SID*)systemsidbytes; */ static const char ownersidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 3, /* base */ - 0, 0, 0, 0 /* 1st level */ + 1, /* revision */ + 1, /* auth count */ + 0, 0, 0, 0, 0, 3, /* base */ + 0, 0, 0, 0 /* 1st level */ } ; static const SID *ownersid = (const SID*)ownersidbytes; @@ -185,10 +185,10 @@ static const SID *ownersid = (const SID*)ownersidbytes; */ static const char groupsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 3, /* base */ - 1, 0, 0, 0 /* 1st level */ + 1, /* revision */ + 1, /* auth count */ + 0, 0, 0, 0, 0, 3, /* base */ + 1, 0, 0, 0 /* 1st level */ } ; static const SID *groupsid = (const SID*)groupsidbytes; @@ -197,20 +197,22 @@ static const SID *groupsid = (const SID*)groupsidbytes; * Determine the size of a SID */ -int ntfs_sid_size(const SID * sid) { - return (sid->sub_authority_count * 4 + 8); +int ntfs_sid_size(const SID * sid) +{ + return (sid->sub_authority_count * 4 + 8); } /* * Test whether two SID are equal */ -BOOL ntfs_same_sid(const SID *first, const SID *second) { - int size; +BOOL ntfs_same_sid(const SID *first, const SID *second) +{ + int size; - size = ntfs_sid_size(first); - return ((ntfs_sid_size(second) == size) - && !memcmp(first, second, size)); + size = ntfs_sid_size(first); + return ((ntfs_sid_size(second) == size) + && !memcmp(first, second, size)); } /* @@ -218,21 +220,22 @@ BOOL ntfs_same_sid(const SID *first, const SID *second) { * Local users group also recognized as world */ -static int is_world_sid(const SID * usid) { - return ( - /* check whether S-1-1-0 : world */ - ((usid->sub_authority_count == 1) - && (usid->identifier_authority.high_part == const_cpu_to_be16(0)) - && (usid->identifier_authority.low_part == const_cpu_to_be32(1)) - && (usid->sub_authority[0] == const_cpu_to_le32(0))) +static int is_world_sid(const SID * usid) +{ + return ( + /* check whether S-1-1-0 : world */ + ((usid->sub_authority_count == 1) + && (usid->identifier_authority.high_part == const_cpu_to_be16(0)) + && (usid->identifier_authority.low_part == const_cpu_to_be32(1)) + && (usid->sub_authority[0] == const_cpu_to_le32(0))) - /* check whether S-1-5-32-545 : local user */ - || ((usid->sub_authority_count == 2) - && (usid->identifier_authority.high_part == const_cpu_to_be16(0)) - && (usid->identifier_authority.low_part == const_cpu_to_be32(5)) - && (usid->sub_authority[0] == const_cpu_to_le32(32)) - && (usid->sub_authority[1] == const_cpu_to_le32(545))) - ); + /* check whether S-1-5-32-545 : local user */ + || ((usid->sub_authority_count == 2) + && (usid->identifier_authority.high_part == const_cpu_to_be16(0)) + && (usid->identifier_authority.low_part == const_cpu_to_be32(5)) + && (usid->sub_authority[0] == const_cpu_to_le32(32)) + && (usid->sub_authority[1] == const_cpu_to_le32(545))) + ); } /* @@ -241,11 +244,12 @@ static int is_world_sid(const SID * usid) { * probably test for other configurations */ -BOOL ntfs_is_user_sid(const SID *usid) { - return ((usid->sub_authority_count == 5) - && (usid->identifier_authority.high_part == const_cpu_to_be16(0)) - && (usid->identifier_authority.low_part == const_cpu_to_be32(5)) - && (usid->sub_authority[0] == const_cpu_to_le32(21))); +BOOL ntfs_is_user_sid(const SID *usid) +{ + return ((usid->sub_authority_count == 5) + && (usid->identifier_authority.high_part == const_cpu_to_be16(0)) + && (usid->identifier_authority.low_part == const_cpu_to_be32(5)) + && (usid->sub_authority[0] == const_cpu_to_le32(21))); } /* @@ -253,58 +257,59 @@ BOOL ntfs_is_user_sid(const SID *usid) { * whatever the order of fields */ -unsigned int ntfs_attr_size(const char *attr) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const ACL *pdacl; - const ACL *psacl; - const SID *psid; - unsigned int offdacl; - unsigned int offsacl; - unsigned int offowner; - unsigned int offgroup; - unsigned int endsid; - unsigned int endacl; - unsigned int attrsz; +unsigned int ntfs_attr_size(const char *attr) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const ACL *pdacl; + const ACL *psacl; + const SID *psid; + unsigned int offdacl; + unsigned int offsacl; + unsigned int offowner; + unsigned int offgroup; + unsigned int endsid; + unsigned int endacl; + unsigned int attrsz; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; - /* - * First check group, which is the last field in all descriptors - * we build, and in most descriptors built by Windows - */ - attrsz = sizeof(SECURITY_DESCRIPTOR_RELATIVE); - offgroup = le32_to_cpu(phead->group); - if (offgroup >= attrsz) { - /* find end of GSID */ - psid = (const SID*)&attr[offgroup]; - endsid = offgroup + ntfs_sid_size(psid); - if (endsid > attrsz) attrsz = endsid; - } - offowner = le32_to_cpu(phead->owner); - if (offowner >= attrsz) { - /* find end of USID */ - psid = (const SID*)&attr[offowner]; - endsid = offowner + ntfs_sid_size(psid); - attrsz = endsid; - } - offsacl = le32_to_cpu(phead->sacl); - if (offsacl >= attrsz) { - /* find end of SACL */ - psacl = (const ACL*)&attr[offsacl]; - endacl = offsacl + le16_to_cpu(psacl->size); - if (endacl > attrsz) - attrsz = endacl; - } + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; + /* + * First check group, which is the last field in all descriptors + * we build, and in most descriptors built by Windows + */ + attrsz = sizeof(SECURITY_DESCRIPTOR_RELATIVE); + offgroup = le32_to_cpu(phead->group); + if (offgroup >= attrsz) { + /* find end of GSID */ + psid = (const SID*)&attr[offgroup]; + endsid = offgroup + ntfs_sid_size(psid); + if (endsid > attrsz) attrsz = endsid; + } + offowner = le32_to_cpu(phead->owner); + if (offowner >= attrsz) { + /* find end of USID */ + psid = (const SID*)&attr[offowner]; + endsid = offowner + ntfs_sid_size(psid); + attrsz = endsid; + } + offsacl = le32_to_cpu(phead->sacl); + if (offsacl >= attrsz) { + /* find end of SACL */ + psacl = (const ACL*)&attr[offsacl]; + endacl = offsacl + le16_to_cpu(psacl->size); + if (endacl > attrsz) + attrsz = endacl; + } - /* find end of DACL */ - offdacl = le32_to_cpu(phead->dacl); - if (offdacl >= attrsz) { - pdacl = (const ACL*)&attr[offdacl]; - endacl = offdacl + le16_to_cpu(pdacl->size); - if (endacl > attrsz) - attrsz = endacl; - } - return (attrsz); + /* find end of DACL */ + offdacl = le32_to_cpu(phead->dacl); + if (offdacl >= attrsz) { + pdacl = (const ACL*)&attr[offdacl]; + endacl = offdacl + le16_to_cpu(pdacl->size); + if (endacl > attrsz) + attrsz = endacl; + } + return (attrsz); } /* @@ -312,10 +317,11 @@ unsigned int ntfs_attr_size(const char *attr) { * (just check revision and number of authorities) */ -BOOL ntfs_valid_sid(const SID *sid) { - return ((sid->revision == SID_REVISION) - && (sid->sub_authority_count >= 1) - && (sid->sub_authority_count <= 8)); +BOOL ntfs_valid_sid(const SID *sid) +{ + return ((sid->revision == SID_REVISION) + && (sid->sub_authority_count >= 1) + && (sid->sub_authority_count <= 8)); } /* @@ -328,15 +334,16 @@ BOOL ntfs_valid_sid(const SID *sid) { * from a gid an be inserted with no overflow. */ -BOOL ntfs_valid_pattern(const SID *sid) { - int cnt; - u32 auth; - le32 leauth; +BOOL ntfs_valid_pattern(const SID *sid) +{ + int cnt; + u32 auth; + le32 leauth; - cnt = sid->sub_authority_count; - leauth = sid->sub_authority[cnt-1]; - auth = le32_to_cpu(leauth); - return ((auth >= 1000) && (auth <= 0x7fffffff)); + cnt = sid->sub_authority_count; + leauth = sid->sub_authority[cnt-1]; + auth = le32_to_cpu(leauth); + return ((auth >= 1000) && (auth <= 0x7fffffff)); } /* @@ -346,52 +353,53 @@ BOOL ntfs_valid_pattern(const SID *sid) { * Returns 0 (root) if it does not match pattern */ -static u32 findimplicit(const SID *xsid, const SID *pattern, int parity) { - BIGSID defsid; - SID *psid; - u32 xid; /* uid or gid */ - int cnt; - u32 carry; - le32 leauth; - u32 uauth; - u32 xlast; - u32 rlast; +static u32 findimplicit(const SID *xsid, const SID *pattern, int parity) +{ + BIGSID defsid; + SID *psid; + u32 xid; /* uid or gid */ + int cnt; + u32 carry; + le32 leauth; + u32 uauth; + u32 xlast; + u32 rlast; - memcpy(&defsid,pattern,ntfs_sid_size(pattern)); - psid = (SID*)&defsid; - cnt = psid->sub_authority_count; - xid = 0; - if (xsid->sub_authority_count == cnt) { - psid->sub_authority[cnt-1] = xsid->sub_authority[cnt-1]; - leauth = xsid->sub_authority[cnt-1]; - xlast = le32_to_cpu(leauth); - leauth = pattern->sub_authority[cnt-1]; - rlast = le32_to_cpu(leauth); + memcpy(&defsid,pattern,ntfs_sid_size(pattern)); + psid = (SID*)&defsid; + cnt = psid->sub_authority_count; + xid = 0; + if (xsid->sub_authority_count == cnt) { + psid->sub_authority[cnt-1] = xsid->sub_authority[cnt-1]; + leauth = xsid->sub_authority[cnt-1]; + xlast = le32_to_cpu(leauth); + leauth = pattern->sub_authority[cnt-1]; + rlast = le32_to_cpu(leauth); - if ((xlast > rlast) && !((xlast ^ rlast ^ parity) & 1)) { - /* direct check for basic situation */ - if (ntfs_same_sid(psid,xsid)) - xid = ((xlast - rlast) >> 1) & 0x3fffffff; - else { - /* - * check whether part of mapping had to be - * recorded in a higher level authority - */ - carry = 1; - do { - leauth = psid->sub_authority[cnt-2]; - uauth = le32_to_cpu(leauth) + 1; - psid->sub_authority[cnt-2] - = cpu_to_le32(uauth); - } while (!ntfs_same_sid(psid,xsid) - && (++carry < 4)); - if (carry < 4) - xid = (((xlast - rlast) >> 1) - & 0x3fffffff) | (carry << 30); - } - } - } - return (xid); + if ((xlast > rlast) && !((xlast ^ rlast ^ parity) & 1)) { + /* direct check for basic situation */ + if (ntfs_same_sid(psid,xsid)) + xid = ((xlast - rlast) >> 1) & 0x3fffffff; + else { + /* + * check whether part of mapping had to be + * recorded in a higher level authority + */ + carry = 1; + do { + leauth = psid->sub_authority[cnt-2]; + uauth = le32_to_cpu(leauth) + 1; + psid->sub_authority[cnt-2] + = cpu_to_le32(uauth); + } while (!ntfs_same_sid(psid,xsid) + && (++carry < 4)); + if (carry < 4) + xid = (((xlast - rlast) >> 1) + & 0x3fffffff) | (carry << 30); + } + } + } + return (xid); } /* @@ -400,41 +408,42 @@ static u32 findimplicit(const SID *xsid, const SID *pattern, int parity) { */ const SID *ntfs_find_usid(const struct MAPPING* usermapping, - uid_t uid, SID *defusid) { - const struct MAPPING *p; - const SID *sid; - le32 leauth; - u32 uauth; - int cnt; + uid_t uid, SID *defusid) +{ + const struct MAPPING *p; + const SID *sid; + le32 leauth; + u32 uauth; + int cnt; - if (!uid) - sid = adminsid; - else { - p = usermapping; - while (p && p->xid && ((uid_t)p->xid != uid)) - p = p->next; - if (p && !p->xid) { - /* - * default pattern has been reached : - * build an implicit SID according to pattern - * (the pattern format was checked while reading - * the mapping file) - */ - memcpy(defusid, p->sid, ntfs_sid_size(p->sid)); - cnt = defusid->sub_authority_count; - leauth = defusid->sub_authority[cnt-1]; - uauth = le32_to_cpu(leauth) + 2*(uid & 0x3fffffff); - defusid->sub_authority[cnt-1] = cpu_to_le32(uauth); - if (uid & 0xc0000000) { - leauth = defusid->sub_authority[cnt-2]; - uauth = le32_to_cpu(leauth) + ((uid >> 30) & 3); - defusid->sub_authority[cnt-2] = cpu_to_le32(uauth); - } - sid = defusid; - } else - sid = (p ? p->sid : (const SID*)NULL); - } - return (sid); + if (!uid) + sid = adminsid; + else { + p = usermapping; + while (p && p->xid && ((uid_t)p->xid != uid)) + p = p->next; + if (p && !p->xid) { + /* + * default pattern has been reached : + * build an implicit SID according to pattern + * (the pattern format was checked while reading + * the mapping file) + */ + memcpy(defusid, p->sid, ntfs_sid_size(p->sid)); + cnt = defusid->sub_authority_count; + leauth = defusid->sub_authority[cnt-1]; + uauth = le32_to_cpu(leauth) + 2*(uid & 0x3fffffff); + defusid->sub_authority[cnt-1] = cpu_to_le32(uauth); + if (uid & 0xc0000000) { + leauth = defusid->sub_authority[cnt-2]; + uauth = le32_to_cpu(leauth) + ((uid >> 30) & 3); + defusid->sub_authority[cnt-2] = cpu_to_le32(uauth); + } + sid = defusid; + } else + sid = (p ? p->sid : (const SID*)NULL); + } + return (sid); } /* @@ -443,41 +452,42 @@ const SID *ntfs_find_usid(const struct MAPPING* usermapping, */ const SID *ntfs_find_gsid(const struct MAPPING* groupmapping, - gid_t gid, SID *defgsid) { - const struct MAPPING *p; - const SID *sid; - le32 leauth; - u32 uauth; - int cnt; + gid_t gid, SID *defgsid) +{ + const struct MAPPING *p; + const SID *sid; + le32 leauth; + u32 uauth; + int cnt; - if (!gid) - sid = adminsid; - else { - p = groupmapping; - while (p && p->xid && ((gid_t)p->xid != gid)) - p = p->next; - if (p && !p->xid) { - /* - * default pattern has been reached : - * build an implicit SID according to pattern - * (the pattern format was checked while reading - * the mapping file) - */ - memcpy(defgsid, p->sid, ntfs_sid_size(p->sid)); - cnt = defgsid->sub_authority_count; - leauth = defgsid->sub_authority[cnt-1]; - uauth = le32_to_cpu(leauth) + 2*(gid & 0x3fffffff) + 1; - defgsid->sub_authority[cnt-1] = cpu_to_le32(uauth); - if (gid & 0xc0000000) { - leauth = defgsid->sub_authority[cnt-2]; - uauth = le32_to_cpu(leauth) + ((gid >> 30) & 3); - defgsid->sub_authority[cnt-2] = cpu_to_le32(uauth); - } - sid = defgsid; - } else - sid = (p ? p->sid : (const SID*)NULL); - } - return (sid); + if (!gid) + sid = adminsid; + else { + p = groupmapping; + while (p && p->xid && ((gid_t)p->xid != gid)) + p = p->next; + if (p && !p->xid) { + /* + * default pattern has been reached : + * build an implicit SID according to pattern + * (the pattern format was checked while reading + * the mapping file) + */ + memcpy(defgsid, p->sid, ntfs_sid_size(p->sid)); + cnt = defgsid->sub_authority_count; + leauth = defgsid->sub_authority[cnt-1]; + uauth = le32_to_cpu(leauth) + 2*(gid & 0x3fffffff) + 1; + defgsid->sub_authority[cnt-1] = cpu_to_le32(uauth); + if (gid & 0xc0000000) { + leauth = defgsid->sub_authority[cnt-2]; + uauth = le32_to_cpu(leauth) + ((gid >> 30) & 3); + defgsid->sub_authority[cnt-2] = cpu_to_le32(uauth); + } + sid = defgsid; + } else + sid = (p ? p->sid : (const SID*)NULL); + } + return (sid); } /* @@ -485,21 +495,22 @@ const SID *ntfs_find_gsid(const struct MAPPING* groupmapping, * Returns 0 (root) if not found */ -uid_t ntfs_find_user(const struct MAPPING* usermapping, const SID *usid) { - uid_t uid; - const struct MAPPING *p; +uid_t ntfs_find_user(const struct MAPPING* usermapping, const SID *usid) +{ + uid_t uid; + const struct MAPPING *p; - p = usermapping; - while (p && p->xid && !ntfs_same_sid(usid, p->sid)) - p = p->next; - if (p && !p->xid) - /* - * No explicit mapping found, try implicit mapping - */ - uid = findimplicit(usid,p->sid,0); - else - uid = (p ? p->xid : 0); - return (uid); + p = usermapping; + while (p && p->xid && !ntfs_same_sid(usid, p->sid)) + p = p->next; + if (p && !p->xid) + /* + * No explicit mapping found, try implicit mapping + */ + uid = findimplicit(usid,p->sid,0); + else + uid = (p ? p->xid : 0); + return (uid); } /* @@ -507,55 +518,57 @@ uid_t ntfs_find_user(const struct MAPPING* usermapping, const SID *usid) { * Returns 0 (root) if not found */ -gid_t ntfs_find_group(const struct MAPPING* groupmapping, const SID * gsid) { - gid_t gid; - const struct MAPPING *p; - int gsidsz; +gid_t ntfs_find_group(const struct MAPPING* groupmapping, const SID * gsid) +{ + gid_t gid; + const struct MAPPING *p; + int gsidsz; - gsidsz = ntfs_sid_size(gsid); - p = groupmapping; - while (p && p->xid && !ntfs_same_sid(gsid, p->sid)) - p = p->next; - if (p && !p->xid) - /* - * No explicit mapping found, try implicit mapping - */ - gid = findimplicit(gsid,p->sid,1); - else - gid = (p ? p->xid : 0); - return (gid); + gsidsz = ntfs_sid_size(gsid); + p = groupmapping; + while (p && p->xid && !ntfs_same_sid(gsid, p->sid)) + p = p->next; + if (p && !p->xid) + /* + * No explicit mapping found, try implicit mapping + */ + gid = findimplicit(gsid,p->sid,1); + else + gid = (p ? p->xid : 0); + return (gid); } /* * Check the validity of the ACEs in a DACL or SACL */ -static BOOL valid_acl(const ACL *pacl, unsigned int end) { - const ACCESS_ALLOWED_ACE *pace; - unsigned int offace; - unsigned int acecnt; - unsigned int acesz; - unsigned int nace; - BOOL ok; +static BOOL valid_acl(const ACL *pacl, unsigned int end) +{ + const ACCESS_ALLOWED_ACE *pace; + unsigned int offace; + unsigned int acecnt; + unsigned int acesz; + unsigned int nace; + BOOL ok; - ok = TRUE; - acecnt = le16_to_cpu(pacl->ace_count); - offace = sizeof(ACL); - for (nace = 0; (nace < acecnt) && ok; nace++) { - /* be sure the beginning is within range */ - if ((offace + sizeof(ACCESS_ALLOWED_ACE)) > end) - ok = FALSE; - else { - pace = (const ACCESS_ALLOWED_ACE*) - &((const char*)pacl)[offace]; - acesz = le16_to_cpu(pace->size); - if (((offace + acesz) > end) - || !ntfs_valid_sid(&pace->sid)) - ok = FALSE; - offace += acesz; - } - } - return (ok); + ok = TRUE; + acecnt = le16_to_cpu(pacl->ace_count); + offace = sizeof(ACL); + for (nace = 0; (nace < acecnt) && ok; nace++) { + /* be sure the beginning is within range */ + if ((offace + sizeof(ACCESS_ALLOWED_ACE)) > end) + ok = FALSE; + else { + pace = (const ACCESS_ALLOWED_ACE*) + &((const char*)pacl)[offace]; + acesz = le16_to_cpu(pace->size); + if (((offace + acesz) > end) + || !ntfs_valid_sid(&pace->sid)) + ok = FALSE; + offace += acesz; + } + } + return (ok); } /* @@ -567,80 +580,81 @@ static BOOL valid_acl(const ACL *pacl, unsigned int end) { * if not, error should be logged by caller */ -BOOL ntfs_valid_descr(const char *securattr, unsigned int attrsz) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const ACL *pdacl; - const ACL *psacl; - unsigned int offdacl; - unsigned int offsacl; - unsigned int offowner; - unsigned int offgroup; - BOOL ok; +BOOL ntfs_valid_descr(const char *securattr, unsigned int attrsz) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const ACL *pdacl; + const ACL *psacl; + unsigned int offdacl; + unsigned int offsacl; + unsigned int offowner; + unsigned int offgroup; + BOOL ok; - ok = TRUE; + ok = TRUE; - /* - * first check overall size if within allocation range - * and a DACL is present - * and owner and group SID are valid - */ + /* + * first check overall size if within allocation range + * and a DACL is present + * and owner and group SID are valid + */ - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - offdacl = le32_to_cpu(phead->dacl); - offsacl = le32_to_cpu(phead->sacl); - offowner = le32_to_cpu(phead->owner); - offgroup = le32_to_cpu(phead->group); - pdacl = (const ACL*)&securattr[offdacl]; - psacl = (const ACL*)&securattr[offsacl]; + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + offdacl = le32_to_cpu(phead->dacl); + offsacl = le32_to_cpu(phead->sacl); + offowner = le32_to_cpu(phead->owner); + offgroup = le32_to_cpu(phead->group); + pdacl = (const ACL*)&securattr[offdacl]; + psacl = (const ACL*)&securattr[offsacl]; - /* - * size check occurs before the above pointers are used - * - * "DR Watson" standard directory on WinXP has an - * old revision and no DACL though SE_DACL_PRESENT is set - */ - if ((attrsz >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) - && (ntfs_attr_size(securattr) <= attrsz) - && (phead->revision == SECURITY_DESCRIPTOR_REVISION) - && (offowner >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) - && ((offowner + 2) < attrsz) - && (offgroup >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) - && ((offgroup + 2) < attrsz) - && (!offdacl - || ((offdacl >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) - && (offdacl < attrsz))) - && (!offsacl - || ((offsacl >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) - && (offsacl < attrsz))) - && !(phead->owner & const_cpu_to_le32(3)) - && !(phead->group & const_cpu_to_le32(3)) - && !(phead->dacl & const_cpu_to_le32(3)) - && !(phead->sacl & const_cpu_to_le32(3)) - && ntfs_valid_sid((const SID*)&securattr[offowner]) - && ntfs_valid_sid((const SID*)&securattr[offgroup]) - /* - * if there is an ACL, as indicated by offdacl, - * require SE_DACL_PRESENT - * but "Dr Watson" has SE_DACL_PRESENT though no DACL - */ - && (!offdacl - || ((phead->control & SE_DACL_PRESENT) - && ((pdacl->revision == ACL_REVISION) - || (pdacl->revision == ACL_REVISION_DS)))) - /* same for SACL */ - && (!offsacl - || ((phead->control & SE_SACL_PRESENT) - && ((psacl->revision == ACL_REVISION) - || (psacl->revision == ACL_REVISION_DS))))) { - /* - * Check the DACL and SACL if present - */ - if ((offdacl && !valid_acl(pdacl,attrsz - offdacl)) - || (offsacl && !valid_acl(psacl,attrsz - offsacl))) - ok = FALSE; - } else - ok = FALSE; - return (ok); + /* + * size check occurs before the above pointers are used + * + * "DR Watson" standard directory on WinXP has an + * old revision and no DACL though SE_DACL_PRESENT is set + */ + if ((attrsz >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) + && (ntfs_attr_size(securattr) <= attrsz) + && (phead->revision == SECURITY_DESCRIPTOR_REVISION) + && (offowner >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) + && ((offowner + 2) < attrsz) + && (offgroup >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) + && ((offgroup + 2) < attrsz) + && (!offdacl + || ((offdacl >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) + && (offdacl < attrsz))) + && (!offsacl + || ((offsacl >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) + && (offsacl < attrsz))) + && !(phead->owner & const_cpu_to_le32(3)) + && !(phead->group & const_cpu_to_le32(3)) + && !(phead->dacl & const_cpu_to_le32(3)) + && !(phead->sacl & const_cpu_to_le32(3)) + && ntfs_valid_sid((const SID*)&securattr[offowner]) + && ntfs_valid_sid((const SID*)&securattr[offgroup]) + /* + * if there is an ACL, as indicated by offdacl, + * require SE_DACL_PRESENT + * but "Dr Watson" has SE_DACL_PRESENT though no DACL + */ + && (!offdacl + || ((phead->control & SE_DACL_PRESENT) + && ((pdacl->revision == ACL_REVISION) + || (pdacl->revision == ACL_REVISION_DS)))) + /* same for SACL */ + && (!offsacl + || ((phead->control & SE_SACL_PRESENT) + && ((psacl->revision == ACL_REVISION) + || (psacl->revision == ACL_REVISION_DS))))) { + /* + * Check the DACL and SACL if present + */ + if ((offdacl && !valid_acl(pdacl,attrsz - offdacl)) + || (offsacl && !valid_acl(psacl,attrsz - offsacl))) + ok = FALSE; + } else + ok = FALSE; + return (ok); } /* @@ -651,110 +665,111 @@ BOOL ntfs_valid_descr(const char *securattr, unsigned int attrsz) { */ int ntfs_inherit_acl(const ACL *oldacl, ACL *newacl, - const SID *usid, const SID *gsid, BOOL fordir) { - unsigned int src; - unsigned int dst; - int oldcnt; - int newcnt; - unsigned int selection; - int nace; - int acesz; - int usidsz; - int gsidsz; - const ACCESS_ALLOWED_ACE *poldace; - ACCESS_ALLOWED_ACE *pnewace; + const SID *usid, const SID *gsid, BOOL fordir) +{ + unsigned int src; + unsigned int dst; + int oldcnt; + int newcnt; + unsigned int selection; + int nace; + int acesz; + int usidsz; + int gsidsz; + const ACCESS_ALLOWED_ACE *poldace; + ACCESS_ALLOWED_ACE *pnewace; - usidsz = ntfs_sid_size(usid); - gsidsz = ntfs_sid_size(gsid); + usidsz = ntfs_sid_size(usid); + gsidsz = ntfs_sid_size(gsid); - /* ACL header */ + /* ACL header */ - newacl->revision = ACL_REVISION; - newacl->alignment1 = 0; - newacl->alignment2 = const_cpu_to_le16(0); - src = dst = sizeof(ACL); + newacl->revision = ACL_REVISION; + newacl->alignment1 = 0; + newacl->alignment2 = const_cpu_to_le16(0); + src = dst = sizeof(ACL); - selection = (fordir ? CONTAINER_INHERIT_ACE : OBJECT_INHERIT_ACE); - newcnt = 0; - oldcnt = le16_to_cpu(oldacl->ace_count); - for (nace = 0; nace < oldcnt; nace++) { - poldace = (const ACCESS_ALLOWED_ACE*)((const char*)oldacl + src); - acesz = le16_to_cpu(poldace->size); - /* inheritance for access */ - if (poldace->flags & selection) { - pnewace = (ACCESS_ALLOWED_ACE*) - ((char*)newacl + dst); - memcpy(pnewace,poldace,acesz); - /* - * Replace generic creator-owner and - * creator-group by owner and group - */ - if (ntfs_same_sid(&pnewace->sid, ownersid)) { - memcpy(&pnewace->sid, usid, usidsz); - acesz = usidsz + 8; - } - if (ntfs_same_sid(&pnewace->sid, groupsid)) { - memcpy(&pnewace->sid, gsid, gsidsz); - acesz = gsidsz + 8; - } - if (pnewace->mask & GENERIC_ALL) { - pnewace->mask &= ~GENERIC_ALL; - if (fordir) - pnewace->mask |= OWNER_RIGHTS - | DIR_READ - | DIR_WRITE - | DIR_EXEC; - else - /* - * The last flag is not defined for a file, - * however Windows sets it, so do the same - */ - pnewace->mask |= OWNER_RIGHTS - | FILE_READ - | FILE_WRITE - | FILE_EXEC - | cpu_to_le32(0x40); - } - /* remove inheritance flags */ - pnewace->flags &= ~(OBJECT_INHERIT_ACE - | CONTAINER_INHERIT_ACE - | INHERIT_ONLY_ACE); - dst += acesz; - newcnt++; - } - /* inheritance for further inheritance */ - if (fordir - && (poldace->flags - & (CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE))) { - pnewace = (ACCESS_ALLOWED_ACE*) - ((char*)newacl + dst); - memcpy(pnewace,poldace,acesz); - /* - * Replace generic creator-owner and - * creator-group by owner and group - */ - if (ntfs_same_sid(&pnewace->sid, ownersid)) { - memcpy(&pnewace->sid, usid, usidsz); - acesz = usidsz + 8; - } - if (ntfs_same_sid(&pnewace->sid, groupsid)) { - memcpy(&pnewace->sid, gsid, gsidsz); - acesz = gsidsz + 8; - } - dst += acesz; - newcnt++; - } - src += acesz; - } - /* - * Adjust header if something was inherited - */ - if (dst > sizeof(ACL)) { - newacl->ace_count = cpu_to_le16(newcnt); - newacl->size = cpu_to_le16(dst); - } else - dst = 0; - return (dst); + selection = (fordir ? CONTAINER_INHERIT_ACE : OBJECT_INHERIT_ACE); + newcnt = 0; + oldcnt = le16_to_cpu(oldacl->ace_count); + for (nace = 0; nace < oldcnt; nace++) { + poldace = (const ACCESS_ALLOWED_ACE*)((const char*)oldacl + src); + acesz = le16_to_cpu(poldace->size); + /* inheritance for access */ + if (poldace->flags & selection) { + pnewace = (ACCESS_ALLOWED_ACE*) + ((char*)newacl + dst); + memcpy(pnewace,poldace,acesz); + /* + * Replace generic creator-owner and + * creator-group by owner and group + */ + if (ntfs_same_sid(&pnewace->sid, ownersid)) { + memcpy(&pnewace->sid, usid, usidsz); + acesz = usidsz + 8; + } + if (ntfs_same_sid(&pnewace->sid, groupsid)) { + memcpy(&pnewace->sid, gsid, gsidsz); + acesz = gsidsz + 8; + } + if (pnewace->mask & GENERIC_ALL) { + pnewace->mask &= ~GENERIC_ALL; + if (fordir) + pnewace->mask |= OWNER_RIGHTS + | DIR_READ + | DIR_WRITE + | DIR_EXEC; + else + /* + * The last flag is not defined for a file, + * however Windows sets it, so do the same + */ + pnewace->mask |= OWNER_RIGHTS + | FILE_READ + | FILE_WRITE + | FILE_EXEC + | cpu_to_le32(0x40); + } + /* remove inheritance flags */ + pnewace->flags &= ~(OBJECT_INHERIT_ACE + | CONTAINER_INHERIT_ACE + | INHERIT_ONLY_ACE); + dst += acesz; + newcnt++; + } + /* inheritance for further inheritance */ + if (fordir + && (poldace->flags + & (CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE))) { + pnewace = (ACCESS_ALLOWED_ACE*) + ((char*)newacl + dst); + memcpy(pnewace,poldace,acesz); + /* + * Replace generic creator-owner and + * creator-group by owner and group + */ + if (ntfs_same_sid(&pnewace->sid, ownersid)) { + memcpy(&pnewace->sid, usid, usidsz); + acesz = usidsz + 8; + } + if (ntfs_same_sid(&pnewace->sid, groupsid)) { + memcpy(&pnewace->sid, gsid, gsidsz); + acesz = gsidsz + 8; + } + dst += acesz; + newcnt++; + } + src += acesz; + } + /* + * Adjust header if something was inherited + */ + if (dst > sizeof(ACL)) { + newacl->ace_count = cpu_to_le16(newcnt); + newacl->size = cpu_to_le16(dst); + } else + dst = 0; + return (dst); } #if POSIXACLS @@ -766,120 +781,121 @@ int ntfs_inherit_acl(const ACL *oldacl, ACL *newacl, * if not, error should be logged by caller */ -BOOL ntfs_valid_posix(const struct POSIX_SECURITY *pxdesc) { - const struct POSIX_ACL *pacl; - int i; - BOOL ok; - u16 tag; - u32 id; - int perms; - struct { - u16 previous; - u32 previousid; - u16 tagsset; - mode_t mode; - int owners; - int groups; - int others; - } checks[2], *pchk; +BOOL ntfs_valid_posix(const struct POSIX_SECURITY *pxdesc) +{ + const struct POSIX_ACL *pacl; + int i; + BOOL ok; + u16 tag; + u32 id; + int perms; + struct { + u16 previous; + u32 previousid; + u16 tagsset; + mode_t mode; + int owners; + int groups; + int others; + } checks[2], *pchk; - for (i=0; i<2; i++) { - checks[i].mode = 0; - checks[i].tagsset = 0; - checks[i].owners = 0; - checks[i].groups = 0; - checks[i].others = 0; - checks[i].previous = 0; - checks[i].previousid = 0; - } - ok = TRUE; - pacl = &pxdesc->acl; - /* - * header (strict for now) - */ - if ((pacl->version != POSIX_VERSION) - || (pacl->flags != 0) - || (pacl->filler != 0)) - ok = FALSE; - /* - * Reject multiple owner, group or other - * but do not require them to be present - * Also check the ACEs are in correct order - * which implies there is no duplicates - */ - for (i=0; iacccnt + pxdesc->defcnt; i++) { - if (i >= pxdesc->firstdef) - pchk = &checks[1]; - else - pchk = &checks[0]; - perms = pacl->ace[i].perms; - tag = pacl->ace[i].tag; - pchk->tagsset |= tag; - id = pacl->ace[i].id; - if (perms & ~7) ok = FALSE; - if ((tag < pchk->previous) - || ((tag == pchk->previous) - && (id <= pchk->previousid))) - ok = FALSE; - pchk->previous = tag; - pchk->previousid = id; - switch (tag) { - case POSIX_ACL_USER_OBJ : - if (pchk->owners++) - ok = FALSE; - if (id != (u32)-1) - ok = FALSE; - pchk->mode |= perms << 6; - break; - case POSIX_ACL_GROUP_OBJ : - if (pchk->groups++) - ok = FALSE; - if (id != (u32)-1) - ok = FALSE; - pchk->mode = (pchk->mode & 07707) | (perms << 3); - break; - case POSIX_ACL_OTHER : - if (pchk->others++) - ok = FALSE; - if (id != (u32)-1) - ok = FALSE; - pchk->mode |= perms; - break; - case POSIX_ACL_USER : - case POSIX_ACL_GROUP : - if (id == (u32)-1) - ok = FALSE; - break; - case POSIX_ACL_MASK : - if (id != (u32)-1) - ok = FALSE; - pchk->mode = (pchk->mode & 07707) | (perms << 3); - break; - default : - ok = FALSE; - break; - } - } - if ((pxdesc->acccnt > 0) - && ((checks[0].owners != 1) || (checks[0].groups != 1) - || (checks[0].others != 1))) - ok = FALSE; - /* do not check owner, group or other are present in */ - /* the default ACL, Windows does not necessarily set them */ - /* descriptor */ - if (pxdesc->defcnt && (pxdesc->acccnt > pxdesc->firstdef)) - ok = FALSE; - if ((pxdesc->acccnt < 0) || (pxdesc->defcnt < 0)) - ok = FALSE; - /* check mode, unless null or no tag set */ - if (pxdesc->mode - && checks[0].tagsset - && (checks[0].mode != (pxdesc->mode & 0777))) - ok = FALSE; - /* check tagsset */ - if (pxdesc->tagsset != checks[0].tagsset) - ok = FALSE; - return (ok); + for (i=0; i<2; i++) { + checks[i].mode = 0; + checks[i].tagsset = 0; + checks[i].owners = 0; + checks[i].groups = 0; + checks[i].others = 0; + checks[i].previous = 0; + checks[i].previousid = 0; + } + ok = TRUE; + pacl = &pxdesc->acl; + /* + * header (strict for now) + */ + if ((pacl->version != POSIX_VERSION) + || (pacl->flags != 0) + || (pacl->filler != 0)) + ok = FALSE; + /* + * Reject multiple owner, group or other + * but do not require them to be present + * Also check the ACEs are in correct order + * which implies there is no duplicates + */ + for (i=0; iacccnt + pxdesc->defcnt; i++) { + if (i >= pxdesc->firstdef) + pchk = &checks[1]; + else + pchk = &checks[0]; + perms = pacl->ace[i].perms; + tag = pacl->ace[i].tag; + pchk->tagsset |= tag; + id = pacl->ace[i].id; + if (perms & ~7) ok = FALSE; + if ((tag < pchk->previous) + || ((tag == pchk->previous) + && (id <= pchk->previousid))) + ok = FALSE; + pchk->previous = tag; + pchk->previousid = id; + switch (tag) { + case POSIX_ACL_USER_OBJ : + if (pchk->owners++) + ok = FALSE; + if (id != (u32)-1) + ok = FALSE; + pchk->mode |= perms << 6; + break; + case POSIX_ACL_GROUP_OBJ : + if (pchk->groups++) + ok = FALSE; + if (id != (u32)-1) + ok = FALSE; + pchk->mode = (pchk->mode & 07707) | (perms << 3); + break; + case POSIX_ACL_OTHER : + if (pchk->others++) + ok = FALSE; + if (id != (u32)-1) + ok = FALSE; + pchk->mode |= perms; + break; + case POSIX_ACL_USER : + case POSIX_ACL_GROUP : + if (id == (u32)-1) + ok = FALSE; + break; + case POSIX_ACL_MASK : + if (id != (u32)-1) + ok = FALSE; + pchk->mode = (pchk->mode & 07707) | (perms << 3); + break; + default : + ok = FALSE; + break; + } + } + if ((pxdesc->acccnt > 0) + && ((checks[0].owners != 1) || (checks[0].groups != 1) + || (checks[0].others != 1))) + ok = FALSE; + /* do not check owner, group or other are present in */ + /* the default ACL, Windows does not necessarily set them */ + /* descriptor */ + if (pxdesc->defcnt && (pxdesc->acccnt > pxdesc->firstdef)) + ok = FALSE; + if ((pxdesc->acccnt < 0) || (pxdesc->defcnt < 0)) + ok = FALSE; + /* check mode, unless null or no tag set */ + if (pxdesc->mode + && checks[0].tagsset + && (checks[0].mode != (pxdesc->mode & 0777))) + ok = FALSE; + /* check tagsset */ + if (pxdesc->tagsset != checks[0].tagsset) + ok = FALSE; + return (ok); } /* @@ -887,38 +903,39 @@ BOOL ntfs_valid_posix(const struct POSIX_SECURITY *pxdesc) { * The mode argument should provide the 3 upper bits of target mode */ -static mode_t posix_header(struct POSIX_SECURITY *pxdesc, mode_t basemode) { - mode_t mode; - u16 tagsset; - struct POSIX_ACE *pace; - int i; +static mode_t posix_header(struct POSIX_SECURITY *pxdesc, mode_t basemode) +{ + mode_t mode; + u16 tagsset; + struct POSIX_ACE *pace; + int i; - mode = basemode & 07000; - tagsset = 0; - for (i=0; iacccnt; i++) { - pace = &pxdesc->acl.ace[i]; - tagsset |= pace->tag; - switch (pace->tag) { - case POSIX_ACL_USER_OBJ : - mode |= (pace->perms & 7) << 6; - break; - case POSIX_ACL_GROUP_OBJ : - case POSIX_ACL_MASK : - mode = (mode & 07707) | ((pace->perms & 7) << 3); - break; - case POSIX_ACL_OTHER : - mode |= pace->perms & 7; - break; - default : - break; - } - } - pxdesc->tagsset = tagsset; - pxdesc->mode = mode; - pxdesc->acl.version = POSIX_VERSION; - pxdesc->acl.flags = 0; - pxdesc->acl.filler = 0; - return (mode); + mode = basemode & 07000; + tagsset = 0; + for (i=0; iacccnt; i++) { + pace = &pxdesc->acl.ace[i]; + tagsset |= pace->tag; + switch(pace->tag) { + case POSIX_ACL_USER_OBJ : + mode |= (pace->perms & 7) << 6; + break; + case POSIX_ACL_GROUP_OBJ : + case POSIX_ACL_MASK : + mode = (mode & 07707) | ((pace->perms & 7) << 3); + break; + case POSIX_ACL_OTHER : + mode |= pace->perms & 7; + break; + default : + break; + } + } + pxdesc->tagsset = tagsset; + pxdesc->mode = mode; + pxdesc->acl.version = POSIX_VERSION; + pxdesc->acl.flags = 0; + pxdesc->acl.filler = 0; + return (mode); } /* @@ -931,68 +948,69 @@ static mode_t posix_header(struct POSIX_SECURITY *pxdesc, mode_t basemode) { * ids should be in ascending sequence. */ -void ntfs_sort_posix(struct POSIX_SECURITY *pxdesc) { - struct POSIX_ACL *pacl; - struct POSIX_ACE ace; - int i; - int offs; - BOOL done; - u16 tag; - u16 previous; - u32 id; - u32 previousid; +void ntfs_sort_posix(struct POSIX_SECURITY *pxdesc) +{ + struct POSIX_ACL *pacl; + struct POSIX_ACE ace; + int i; + int offs; + BOOL done; + u16 tag; + u16 previous; + u32 id; + u32 previousid; - /* - * Check sequencing of tag+id in access ACE's - */ - pacl = &pxdesc->acl; - do { - done = TRUE; - previous = pacl->ace[0].tag; - previousid = pacl->ace[0].id; - for (i=1; iacccnt; i++) { - tag = pacl->ace[i].tag; - id = pacl->ace[i].id; + /* + * Check sequencing of tag+id in access ACE's + */ + pacl = &pxdesc->acl; + do { + done = TRUE; + previous = pacl->ace[0].tag; + previousid = pacl->ace[0].id; + for (i=1; iacccnt; i++) { + tag = pacl->ace[i].tag; + id = pacl->ace[i].id; - if ((tag < previous) - || ((tag == previous) && (id < previousid))) { - done = FALSE; - memcpy(&ace,&pacl->ace[i-1],sizeof(struct POSIX_ACE)); - memcpy(&pacl->ace[i-1],&pacl->ace[i],sizeof(struct POSIX_ACE)); - memcpy(&pacl->ace[i],&ace,sizeof(struct POSIX_ACE)); - } else { - previous = tag; - previousid = id; - } - } - } while (!done); - /* - * Same for default ACEs - */ - do { - done = TRUE; - if ((pxdesc->defcnt) > 1) { - offs = pxdesc->firstdef; - previous = pacl->ace[offs].tag; - previousid = pacl->ace[offs].id; - for (i=offs+1; idefcnt; i++) { - tag = pacl->ace[i].tag; - id = pacl->ace[i].id; + if ((tag < previous) + || ((tag == previous) && (id < previousid))) { + done = FALSE; + memcpy(&ace,&pacl->ace[i-1],sizeof(struct POSIX_ACE)); + memcpy(&pacl->ace[i-1],&pacl->ace[i],sizeof(struct POSIX_ACE)); + memcpy(&pacl->ace[i],&ace,sizeof(struct POSIX_ACE)); + } else { + previous = tag; + previousid = id; + } + } + } while (!done); + /* + * Same for default ACEs + */ + do { + done = TRUE; + if ((pxdesc->defcnt) > 1) { + offs = pxdesc->firstdef; + previous = pacl->ace[offs].tag; + previousid = pacl->ace[offs].id; + for (i=offs+1; idefcnt; i++) { + tag = pacl->ace[i].tag; + id = pacl->ace[i].id; - if ((tag < previous) - || ((tag == previous) && (id < previousid))) { - done = FALSE; - memcpy(&ace,&pacl->ace[i-1],sizeof(struct POSIX_ACE)); - memcpy(&pacl->ace[i-1],&pacl->ace[i],sizeof(struct POSIX_ACE)); - memcpy(&pacl->ace[i],&ace,sizeof(struct POSIX_ACE)); - } else { - previous = tag; - previousid = id; - } - } - } - } while (!done); + if ((tag < previous) + || ((tag == previous) && (id < previousid))) { + done = FALSE; + memcpy(&ace,&pacl->ace[i-1],sizeof(struct POSIX_ACE)); + memcpy(&pacl->ace[i-1],&pacl->ace[i],sizeof(struct POSIX_ACE)); + memcpy(&pacl->ace[i],&ace,sizeof(struct POSIX_ACE)); + } else { + previous = tag; + previousid = id; + } + } + } + } while (!done); } /* @@ -1002,40 +1020,41 @@ void ntfs_sort_posix(struct POSIX_SECURITY *pxdesc) { * returns 0 if ok */ -int ntfs_merge_mode_posix(struct POSIX_SECURITY *pxdesc, mode_t mode) { - int i; - BOOL maskfound; - struct POSIX_ACE *pace; - int todo; +int ntfs_merge_mode_posix(struct POSIX_SECURITY *pxdesc, mode_t mode) +{ + int i; + BOOL maskfound; + struct POSIX_ACE *pace; + int todo; - maskfound = FALSE; - todo = POSIX_ACL_USER_OBJ | POSIX_ACL_GROUP_OBJ | POSIX_ACL_OTHER; - for (i=pxdesc->acccnt-1; i>=0; i--) { - pace = &pxdesc->acl.ace[i]; - switch (pace->tag) { - case POSIX_ACL_USER_OBJ : - pace->perms = (mode >> 6) & 7; - todo &= ~POSIX_ACL_USER_OBJ; - break; - case POSIX_ACL_GROUP_OBJ : - if (!maskfound) - pace->perms = (mode >> 3) & 7; - todo &= ~POSIX_ACL_GROUP_OBJ; - break; - case POSIX_ACL_MASK : - pace->perms = (mode >> 3) & 7; - maskfound = TRUE; - break; - case POSIX_ACL_OTHER : - pace->perms = mode & 7; - todo &= ~POSIX_ACL_OTHER; - break; - default : - break; - } - } - pxdesc->mode = mode; - return (todo ? -1 : 0); + maskfound = FALSE; + todo = POSIX_ACL_USER_OBJ | POSIX_ACL_GROUP_OBJ | POSIX_ACL_OTHER; + for (i=pxdesc->acccnt-1; i>=0; i--) { + pace = &pxdesc->acl.ace[i]; + switch(pace->tag) { + case POSIX_ACL_USER_OBJ : + pace->perms = (mode >> 6) & 7; + todo &= ~POSIX_ACL_USER_OBJ; + break; + case POSIX_ACL_GROUP_OBJ : + if (!maskfound) + pace->perms = (mode >> 3) & 7; + todo &= ~POSIX_ACL_GROUP_OBJ; + break; + case POSIX_ACL_MASK : + pace->perms = (mode >> 3) & 7; + maskfound = TRUE; + break; + case POSIX_ACL_OTHER : + pace->perms = mode & 7; + todo &= ~POSIX_ACL_OTHER; + break; + default : + break; + } + } + pxdesc->mode = mode; + return (todo ? -1 : 0); } /* @@ -1046,56 +1065,57 @@ int ntfs_merge_mode_posix(struct POSIX_SECURITY *pxdesc, mode_t mode) { */ struct POSIX_SECURITY *ntfs_replace_acl(const struct POSIX_SECURITY *oldpxdesc, - const struct POSIX_ACL *newacl, int count, BOOL deflt) { - struct POSIX_SECURITY *newpxdesc; - size_t newsize; - int offset; - int oldoffset; - int i; + const struct POSIX_ACL *newacl, int count, BOOL deflt) +{ + struct POSIX_SECURITY *newpxdesc; + size_t newsize; + int offset; + int oldoffset; + int i; - if (deflt) - newsize = sizeof(struct POSIX_SECURITY) - + (oldpxdesc->acccnt + count)*sizeof(struct POSIX_ACE); - else - newsize = sizeof(struct POSIX_SECURITY) - + (oldpxdesc->defcnt + count)*sizeof(struct POSIX_ACE); - newpxdesc = (struct POSIX_SECURITY*)malloc(newsize); - if (newpxdesc) { - if (deflt) { - offset = oldpxdesc->acccnt; - newpxdesc->acccnt = oldpxdesc->acccnt; - newpxdesc->defcnt = count; - newpxdesc->firstdef = offset; - /* copy access ACEs */ - for (i=0; iacccnt; i++) - newpxdesc->acl.ace[i] = oldpxdesc->acl.ace[i]; - /* copy default ACEs */ - for (i=0; iacl.ace[i + offset] = newacl->ace[i]; - } else { - offset = count; - newpxdesc->acccnt = count; - newpxdesc->defcnt = oldpxdesc->defcnt; - newpxdesc->firstdef = count; - /* copy access ACEs */ - for (i=0; iacl.ace[i] = newacl->ace[i]; - /* copy default ACEs */ - oldoffset = oldpxdesc->firstdef; - for (i=0; idefcnt; i++) - newpxdesc->acl.ace[i + offset] = oldpxdesc->acl.ace[i + oldoffset]; - } - /* assume special flags unchanged */ - posix_header(newpxdesc, oldpxdesc->mode); - if (!ntfs_valid_posix(newpxdesc)) { - /* do not log, this is an application error */ - free(newpxdesc); - newpxdesc = (struct POSIX_SECURITY*)NULL; - errno = EINVAL; - } - } else - errno = ENOMEM; - return (newpxdesc); + if (deflt) + newsize = sizeof(struct POSIX_SECURITY) + + (oldpxdesc->acccnt + count)*sizeof(struct POSIX_ACE); + else + newsize = sizeof(struct POSIX_SECURITY) + + (oldpxdesc->defcnt + count)*sizeof(struct POSIX_ACE); + newpxdesc = (struct POSIX_SECURITY*)malloc(newsize); + if (newpxdesc) { + if (deflt) { + offset = oldpxdesc->acccnt; + newpxdesc->acccnt = oldpxdesc->acccnt; + newpxdesc->defcnt = count; + newpxdesc->firstdef = offset; + /* copy access ACEs */ + for (i=0; iacccnt; i++) + newpxdesc->acl.ace[i] = oldpxdesc->acl.ace[i]; + /* copy default ACEs */ + for (i=0; iacl.ace[i + offset] = newacl->ace[i]; + } else { + offset = count; + newpxdesc->acccnt = count; + newpxdesc->defcnt = oldpxdesc->defcnt; + newpxdesc->firstdef = count; + /* copy access ACEs */ + for (i=0; iacl.ace[i] = newacl->ace[i]; + /* copy default ACEs */ + oldoffset = oldpxdesc->firstdef; + for (i=0; idefcnt; i++) + newpxdesc->acl.ace[i + offset] = oldpxdesc->acl.ace[i + oldoffset]; + } + /* assume special flags unchanged */ + posix_header(newpxdesc, oldpxdesc->mode); + if (!ntfs_valid_posix(newpxdesc)) { + /* do not log, this is an application error */ + free(newpxdesc); + newpxdesc = (struct POSIX_SECURITY*)NULL; + errno = EINVAL; + } + } else + errno = ENOMEM; + return (newpxdesc); } /* @@ -1106,182 +1126,184 @@ struct POSIX_SECURITY *ntfs_replace_acl(const struct POSIX_SECURITY *oldpxdesc, */ struct POSIX_SECURITY *ntfs_build_inherited_posix( - const struct POSIX_SECURITY *pxdesc, mode_t mode, - mode_t mask, BOOL isdir) { - struct POSIX_SECURITY *pydesc; - struct POSIX_ACE *pyace; - int count; - int defcnt; - int size; - int i; - s16 tagsset; + const struct POSIX_SECURITY *pxdesc, mode_t mode, + mode_t mask, BOOL isdir) +{ + struct POSIX_SECURITY *pydesc; + struct POSIX_ACE *pyace; + int count; + int defcnt; + int size; + int i; + s16 tagsset; - if (pxdesc && pxdesc->defcnt) { - if (isdir) - count = 2*pxdesc->defcnt + 3; - else - count = pxdesc->defcnt + 3; - } else - count = 3; - pydesc = (struct POSIX_SECURITY*)malloc( - sizeof(struct POSIX_SECURITY) + count*sizeof(struct POSIX_ACE)); - if (pydesc) { - /* - * Copy inherited tags and adapt perms - * Use requested mode, ignoring umask - * (not possible with older versions of fuse) - */ - tagsset = 0; - defcnt = (pxdesc ? pxdesc->defcnt : 0); - for (i=defcnt-1; i>=0; i--) { - pyace = &pydesc->acl.ace[i]; - *pyace = pxdesc->acl.ace[pxdesc->firstdef + i]; - switch (pyace->tag) { - case POSIX_ACL_USER_OBJ : - pyace->perms &= (mode >> 6) & 7; - break; - case POSIX_ACL_GROUP_OBJ : - if (!(tagsset & POSIX_ACL_MASK)) - pyace->perms &= (mode >> 3) & 7; - break; - case POSIX_ACL_OTHER : - pyace->perms &= mode & 7; - break; - case POSIX_ACL_MASK : - pyace->perms &= (mode >> 3) & 7; - break; - default : - break; - } - tagsset |= pyace->tag; - } - pydesc->acccnt = defcnt; - /* - * If some standard tags were missing, append them from mode - * and sort the list - * Here we have to use the umask'ed mode - */ - if (~tagsset & (POSIX_ACL_USER_OBJ - | POSIX_ACL_GROUP_OBJ | POSIX_ACL_OTHER)) { - i = defcnt; - /* owner was missing */ - if (!(tagsset & POSIX_ACL_USER_OBJ)) { - pyace = &pydesc->acl.ace[i]; - pyace->tag = POSIX_ACL_USER_OBJ; - pyace->id = -1; - pyace->perms = ((mode & ~mask) >> 6) & 7; - tagsset |= POSIX_ACL_USER_OBJ; - i++; - } - /* owning group was missing */ - if (!(tagsset & POSIX_ACL_GROUP_OBJ)) { - pyace = &pydesc->acl.ace[i]; - pyace->tag = POSIX_ACL_GROUP_OBJ; - pyace->id = -1; - pyace->perms = ((mode & ~mask) >> 3) & 7; - tagsset |= POSIX_ACL_GROUP_OBJ; - i++; - } - /* other was missing */ - if (!(tagsset & POSIX_ACL_OTHER)) { - pyace = &pydesc->acl.ace[i]; - pyace->tag = POSIX_ACL_OTHER; - pyace->id = -1; - pyace->perms = mode & ~mask & 7; - tagsset |= POSIX_ACL_OTHER; - i++; - } - pydesc->acccnt = i; - pydesc->firstdef = i; - pydesc->defcnt = 0; - ntfs_sort_posix(pydesc); - } + if (pxdesc && pxdesc->defcnt) { + if (isdir) + count = 2*pxdesc->defcnt + 3; + else + count = pxdesc->defcnt + 3; + } else + count = 3; + pydesc = (struct POSIX_SECURITY*)malloc( + sizeof(struct POSIX_SECURITY) + count*sizeof(struct POSIX_ACE)); + if (pydesc) { + /* + * Copy inherited tags and adapt perms + * Use requested mode, ignoring umask + * (not possible with older versions of fuse) + */ + tagsset = 0; + defcnt = (pxdesc ? pxdesc->defcnt : 0); + for (i=defcnt-1; i>=0; i--) { + pyace = &pydesc->acl.ace[i]; + *pyace = pxdesc->acl.ace[pxdesc->firstdef + i]; + switch (pyace->tag) { + case POSIX_ACL_USER_OBJ : + pyace->perms &= (mode >> 6) & 7; + break; + case POSIX_ACL_GROUP_OBJ : + if (!(tagsset & POSIX_ACL_MASK)) + pyace->perms &= (mode >> 3) & 7; + break; + case POSIX_ACL_OTHER : + pyace->perms &= mode & 7; + break; + case POSIX_ACL_MASK : + pyace->perms &= (mode >> 3) & 7; + break; + default : + break; + } + tagsset |= pyace->tag; + } + pydesc->acccnt = defcnt; + /* + * If some standard tags were missing, append them from mode + * and sort the list + * Here we have to use the umask'ed mode + */ + if (~tagsset & (POSIX_ACL_USER_OBJ + | POSIX_ACL_GROUP_OBJ | POSIX_ACL_OTHER)) { + i = defcnt; + /* owner was missing */ + if (!(tagsset & POSIX_ACL_USER_OBJ)) { + pyace = &pydesc->acl.ace[i]; + pyace->tag = POSIX_ACL_USER_OBJ; + pyace->id = -1; + pyace->perms = ((mode & ~mask) >> 6) & 7; + tagsset |= POSIX_ACL_USER_OBJ; + i++; + } + /* owning group was missing */ + if (!(tagsset & POSIX_ACL_GROUP_OBJ)) { + pyace = &pydesc->acl.ace[i]; + pyace->tag = POSIX_ACL_GROUP_OBJ; + pyace->id = -1; + pyace->perms = ((mode & ~mask) >> 3) & 7; + tagsset |= POSIX_ACL_GROUP_OBJ; + i++; + } + /* other was missing */ + if (!(tagsset & POSIX_ACL_OTHER)) { + pyace = &pydesc->acl.ace[i]; + pyace->tag = POSIX_ACL_OTHER; + pyace->id = -1; + pyace->perms = mode & ~mask & 7; + tagsset |= POSIX_ACL_OTHER; + i++; + } + pydesc->acccnt = i; + pydesc->firstdef = i; + pydesc->defcnt = 0; + ntfs_sort_posix(pydesc); + } - /* - * append as a default ACL if a directory - */ - pydesc->firstdef = pydesc->acccnt; - if (defcnt && isdir) { - size = sizeof(struct POSIX_ACE)*defcnt; - memcpy(&pydesc->acl.ace[pydesc->firstdef], - &pxdesc->acl.ace[pxdesc->firstdef],size); - pydesc->defcnt = defcnt; - } else { - pydesc->defcnt = 0; - } - /* assume special bits are not inherited */ - posix_header(pydesc, mode & 07000); - if (!ntfs_valid_posix(pydesc)) { - ntfs_log_error("Error building an inherited Posix desc\n"); - errno = EIO; - free(pydesc); - pydesc = (struct POSIX_SECURITY*)NULL; - } - } else - errno = ENOMEM; - return (pydesc); + /* + * append as a default ACL if a directory + */ + pydesc->firstdef = pydesc->acccnt; + if (defcnt && isdir) { + size = sizeof(struct POSIX_ACE)*defcnt; + memcpy(&pydesc->acl.ace[pydesc->firstdef], + &pxdesc->acl.ace[pxdesc->firstdef],size); + pydesc->defcnt = defcnt; + } else { + pydesc->defcnt = 0; + } + /* assume special bits are not inherited */ + posix_header(pydesc, mode & 07000); + if (!ntfs_valid_posix(pydesc)) { + ntfs_log_error("Error building an inherited Posix desc\n"); + errno = EIO; + free(pydesc); + pydesc = (struct POSIX_SECURITY*)NULL; + } + } else + errno = ENOMEM; + return (pydesc); } static int merge_lists_posix(struct POSIX_ACE *targetace, - const struct POSIX_ACE *firstace, - const struct POSIX_ACE *secondace, - int firstcnt, int secondcnt) { - int k; + const struct POSIX_ACE *firstace, + const struct POSIX_ACE *secondace, + int firstcnt, int secondcnt) +{ + int k; - k = 0; - /* - * No list is exhausted : - * if same tag+id in both list : - * ignore ACE from second list - * else take the one with smaller tag+id - */ - while ((firstcnt > 0) && (secondcnt > 0)) - if ((firstace->tag == secondace->tag) - && (firstace->id == secondace->id)) { - secondace++; - secondcnt--; - } else - if ((firstace->tag < secondace->tag) - || ((firstace->tag == secondace->tag) - && (firstace->id < secondace->id))) { - targetace->tag = firstace->tag; - targetace->id = firstace->id; - targetace->perms = firstace->perms; - firstace++; - targetace++; - firstcnt--; - k++; - } else { - targetace->tag = secondace->tag; - targetace->id = secondace->id; - targetace->perms = secondace->perms; - secondace++; - targetace++; - secondcnt--; - k++; - } - /* - * One list is exhausted, copy the other one - */ - while (firstcnt > 0) { - targetace->tag = firstace->tag; - targetace->id = firstace->id; - targetace->perms = firstace->perms; - firstace++; - targetace++; - firstcnt--; - k++; - } - while (secondcnt > 0) { - targetace->tag = secondace->tag; - targetace->id = secondace->id; - targetace->perms = secondace->perms; - secondace++; - targetace++; - secondcnt--; - k++; - } - return (k); + k = 0; + /* + * No list is exhausted : + * if same tag+id in both list : + * ignore ACE from second list + * else take the one with smaller tag+id + */ + while ((firstcnt > 0) && (secondcnt > 0)) + if ((firstace->tag == secondace->tag) + && (firstace->id == secondace->id)) { + secondace++; + secondcnt--; + } else + if ((firstace->tag < secondace->tag) + || ((firstace->tag == secondace->tag) + && (firstace->id < secondace->id))) { + targetace->tag = firstace->tag; + targetace->id = firstace->id; + targetace->perms = firstace->perms; + firstace++; + targetace++; + firstcnt--; + k++; + } else { + targetace->tag = secondace->tag; + targetace->id = secondace->id; + targetace->perms = secondace->perms; + secondace++; + targetace++; + secondcnt--; + k++; + } + /* + * One list is exhausted, copy the other one + */ + while (firstcnt > 0) { + targetace->tag = firstace->tag; + targetace->id = firstace->id; + targetace->perms = firstace->perms; + firstace++; + targetace++; + firstcnt--; + k++; + } + while (secondcnt > 0) { + targetace->tag = secondace->tag; + targetace->id = secondace->id; + targetace->perms = secondace->perms; + secondace++; + targetace++; + secondcnt--; + k++; + } + return (k); } /* @@ -1293,474 +1315,478 @@ static int merge_lists_posix(struct POSIX_ACE *targetace, */ struct POSIX_SECURITY *ntfs_merge_descr_posix(const struct POSIX_SECURITY *first, - const struct POSIX_SECURITY *second) { - struct POSIX_SECURITY *pxdesc; - struct POSIX_ACE *targetace; - const struct POSIX_ACE *firstace; - const struct POSIX_ACE *secondace; - size_t size; - int k; + const struct POSIX_SECURITY *second) +{ + struct POSIX_SECURITY *pxdesc; + struct POSIX_ACE *targetace; + const struct POSIX_ACE *firstace; + const struct POSIX_ACE *secondace; + size_t size; + int k; - size = sizeof(struct POSIX_SECURITY) - + (first->acccnt + first->defcnt - + second->acccnt + second->defcnt)*sizeof(struct POSIX_ACE); - pxdesc = (struct POSIX_SECURITY*)malloc(size); - if (pxdesc) { - /* - * merge access ACEs - */ - firstace = first->acl.ace; - secondace = second->acl.ace; - targetace = pxdesc->acl.ace; - k = merge_lists_posix(targetace,firstace,secondace, - first->acccnt,second->acccnt); - pxdesc->acccnt = k; - /* - * merge default ACEs - */ - pxdesc->firstdef = k; - firstace = &first->acl.ace[first->firstdef]; - secondace = &second->acl.ace[second->firstdef]; - targetace = &pxdesc->acl.ace[k]; - k = merge_lists_posix(targetace,firstace,secondace, - first->defcnt,second->defcnt); - pxdesc->defcnt = k; - /* - * build header - */ - pxdesc->acl.version = POSIX_VERSION; - pxdesc->acl.flags = 0; - pxdesc->acl.filler = 0; - pxdesc->mode = 0; - pxdesc->tagsset = 0; - } else - errno = ENOMEM; - return (pxdesc); + size = sizeof(struct POSIX_SECURITY) + + (first->acccnt + first->defcnt + + second->acccnt + second->defcnt)*sizeof(struct POSIX_ACE); + pxdesc = (struct POSIX_SECURITY*)malloc(size); + if (pxdesc) { + /* + * merge access ACEs + */ + firstace = first->acl.ace; + secondace = second->acl.ace; + targetace = pxdesc->acl.ace; + k = merge_lists_posix(targetace,firstace,secondace, + first->acccnt,second->acccnt); + pxdesc->acccnt = k; + /* + * merge default ACEs + */ + pxdesc->firstdef = k; + firstace = &first->acl.ace[first->firstdef]; + secondace = &second->acl.ace[second->firstdef]; + targetace = &pxdesc->acl.ace[k]; + k = merge_lists_posix(targetace,firstace,secondace, + first->defcnt,second->defcnt); + pxdesc->defcnt = k; + /* + * build header + */ + pxdesc->acl.version = POSIX_VERSION; + pxdesc->acl.flags = 0; + pxdesc->acl.filler = 0; + pxdesc->mode = 0; + pxdesc->tagsset = 0; + } else + errno = ENOMEM; + return (pxdesc); } struct BUILD_CONTEXT { - BOOL isdir; - BOOL adminowns; - BOOL groupowns; - u16 selfuserperms; - u16 selfgrpperms; - u16 grpperms; - u16 othperms; - u16 mask; - u16 designates; - u16 withmask; - u16 rootspecial; + BOOL isdir; + BOOL adminowns; + BOOL groupowns; + u16 selfuserperms; + u16 selfgrpperms; + u16 grpperms; + u16 othperms; + u16 mask; + u16 designates; + u16 withmask; + u16 rootspecial; } ; static BOOL build_user_denials(ACL *pacl, - const SID *usid, struct MAPPING* const mapping[], - ACE_FLAGS flags, const struct POSIX_ACE *pxace, - struct BUILD_CONTEXT *pset) { - BIGSID defsid; - ACCESS_ALLOWED_ACE *pdace; - const SID *sid; - int sidsz; - int pos; - int acecnt; - le32 grants; - le32 denials; - u16 perms; - u16 mixperms; - u16 tag; - BOOL rejected; - BOOL rootuser; - BOOL avoidmask; + const SID *usid, struct MAPPING* const mapping[], + ACE_FLAGS flags, const struct POSIX_ACE *pxace, + struct BUILD_CONTEXT *pset) +{ + BIGSID defsid; + ACCESS_ALLOWED_ACE *pdace; + const SID *sid; + int sidsz; + int pos; + int acecnt; + le32 grants; + le32 denials; + u16 perms; + u16 mixperms; + u16 tag; + BOOL rejected; + BOOL rootuser; + BOOL avoidmask; - rejected = FALSE; - tag = pxace->tag; - perms = pxace->perms; - rootuser = FALSE; - pos = le16_to_cpu(pacl->size); - acecnt = le16_to_cpu(pacl->ace_count); - avoidmask = (pset->mask == (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X)) - && ((pset->designates && pset->withmask) - || (!pset->designates && !pset->withmask)); - if (tag == POSIX_ACL_USER_OBJ) { - sid = usid; - sidsz = ntfs_sid_size(sid); - grants = OWNER_RIGHTS; - } else { - if (pxace->id) { - sid = NTFS_FIND_USID(mapping[MAPUSERS], - pxace->id, (SID*)&defsid); - grants = WORLD_RIGHTS; - } else { - sid = adminsid; - rootuser = TRUE; - grants = WORLD_RIGHTS & ~ROOT_OWNER_UNMARK; - } - if (sid) { - sidsz = ntfs_sid_size(sid); - /* - * Insert denial of complement of mask for - * each designated user (except root) - * WRITE_OWNER is inserted so that - * the mask can be identified - */ - if (!avoidmask && !rootuser) { - denials = WRITE_OWNER; - pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; - if (pset->isdir) { - if (!(pset->mask & POSIX_PERM_X)) - denials |= DIR_EXEC; - if (!(pset->mask & POSIX_PERM_W)) - denials |= DIR_WRITE; - if (!(pset->mask & POSIX_PERM_R)) - denials |= DIR_READ; - } else { - if (!(pset->mask & POSIX_PERM_X)) - denials |= FILE_EXEC; - if (!(pset->mask & POSIX_PERM_W)) - denials |= FILE_WRITE; - if (!(pset->mask & POSIX_PERM_R)) - denials |= FILE_READ; - } - if (rootuser) - grants &= ~ROOT_OWNER_UNMARK; - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->flags = flags; - pdace->size = cpu_to_le16(sidsz + 8); - pdace->mask = denials; - memcpy((char*)&pdace->sid, sid, sidsz); - pos += sidsz + 8; - acecnt++; - } - } else - rejected = TRUE; - } - if (!rejected) { - if (pset->isdir) { - if (perms & POSIX_PERM_X) - grants |= DIR_EXEC; - if (perms & POSIX_PERM_W) - grants |= DIR_WRITE; - if (perms & POSIX_PERM_R) - grants |= DIR_READ; - } else { - if (perms & POSIX_PERM_X) - grants |= FILE_EXEC; - if (perms & POSIX_PERM_W) - grants |= FILE_WRITE; - if (perms & POSIX_PERM_R) - grants |= FILE_READ; - } + rejected = FALSE; + tag = pxace->tag; + perms = pxace->perms; + rootuser = FALSE; + pos = le16_to_cpu(pacl->size); + acecnt = le16_to_cpu(pacl->ace_count); + avoidmask = (pset->mask == (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X)) + && ((pset->designates && pset->withmask) + || (!pset->designates && !pset->withmask)); + if (tag == POSIX_ACL_USER_OBJ) { + sid = usid; + sidsz = ntfs_sid_size(sid); + grants = OWNER_RIGHTS; + } else { + if (pxace->id) { + sid = NTFS_FIND_USID(mapping[MAPUSERS], + pxace->id, (SID*)&defsid); + grants = WORLD_RIGHTS; + } else { + sid = adminsid; + rootuser = TRUE; + grants = WORLD_RIGHTS & ~ROOT_OWNER_UNMARK; + } + if (sid) { + sidsz = ntfs_sid_size(sid); + /* + * Insert denial of complement of mask for + * each designated user (except root) + * WRITE_OWNER is inserted so that + * the mask can be identified + */ + if (!avoidmask && !rootuser) { + denials = WRITE_OWNER; + pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; + if (pset->isdir) { + if (!(pset->mask & POSIX_PERM_X)) + denials |= DIR_EXEC; + if (!(pset->mask & POSIX_PERM_W)) + denials |= DIR_WRITE; + if (!(pset->mask & POSIX_PERM_R)) + denials |= DIR_READ; + } else { + if (!(pset->mask & POSIX_PERM_X)) + denials |= FILE_EXEC; + if (!(pset->mask & POSIX_PERM_W)) + denials |= FILE_WRITE; + if (!(pset->mask & POSIX_PERM_R)) + denials |= FILE_READ; + } + if (rootuser) + grants &= ~ROOT_OWNER_UNMARK; + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->flags = flags; + pdace->size = cpu_to_le16(sidsz + 8); + pdace->mask = denials; + memcpy((char*)&pdace->sid, sid, sidsz); + pos += sidsz + 8; + acecnt++; + } + } else + rejected = TRUE; + } + if (!rejected) { + if (pset->isdir) { + if (perms & POSIX_PERM_X) + grants |= DIR_EXEC; + if (perms & POSIX_PERM_W) + grants |= DIR_WRITE; + if (perms & POSIX_PERM_R) + grants |= DIR_READ; + } else { + if (perms & POSIX_PERM_X) + grants |= FILE_EXEC; + if (perms & POSIX_PERM_W) + grants |= FILE_WRITE; + if (perms & POSIX_PERM_R) + grants |= FILE_READ; + } - /* a possible ACE to deny owner what he/she would */ - /* induely get from administrator, group or world */ - /* unless owner is administrator or group */ + /* a possible ACE to deny owner what he/she would */ + /* induely get from administrator, group or world */ + /* unless owner is administrator or group */ - denials = const_cpu_to_le32(0); - pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; - if (!pset->adminowns && !rootuser) { - if (!pset->groupowns) { - mixperms = pset->grpperms | pset->othperms; - if (tag == POSIX_ACL_USER_OBJ) - mixperms |= pset->selfuserperms; - if (pset->isdir) { - if (mixperms & POSIX_PERM_X) - denials |= DIR_EXEC; - if (mixperms & POSIX_PERM_W) - denials |= DIR_WRITE; - if (mixperms & POSIX_PERM_R) - denials |= DIR_READ; - } else { - if (mixperms & POSIX_PERM_X) - denials |= FILE_EXEC; - if (mixperms & POSIX_PERM_W) - denials |= FILE_WRITE; - if (mixperms & POSIX_PERM_R) - denials |= FILE_READ; - } - } else { - mixperms = ~pset->grpperms & pset->othperms; - if (tag == POSIX_ACL_USER_OBJ) - mixperms |= pset->selfuserperms; - if (pset->isdir) { - if (mixperms & POSIX_PERM_X) - denials |= DIR_EXEC; - if (mixperms & POSIX_PERM_W) - denials |= DIR_WRITE; - if (mixperms & POSIX_PERM_R) - denials |= DIR_READ; - } else { - if (mixperms & POSIX_PERM_X) - denials |= FILE_EXEC; - if (mixperms & POSIX_PERM_W) - denials |= FILE_WRITE; - if (mixperms & POSIX_PERM_R) - denials |= FILE_READ; - } - } - denials &= ~grants; - if (denials) { - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->flags = flags; - pdace->size = cpu_to_le16(sidsz + 8); - pdace->mask = denials; - memcpy((char*)&pdace->sid, sid, sidsz); - pos += sidsz + 8; - acecnt++; - } - } - } - pacl->size = cpu_to_le16(pos); - pacl->ace_count = cpu_to_le16(acecnt); - return (!rejected); + denials = const_cpu_to_le32(0); + pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; + if (!pset->adminowns && !rootuser) { + if (!pset->groupowns) { + mixperms = pset->grpperms | pset->othperms; + if (tag == POSIX_ACL_USER_OBJ) + mixperms |= pset->selfuserperms; + if (pset->isdir) { + if (mixperms & POSIX_PERM_X) + denials |= DIR_EXEC; + if (mixperms & POSIX_PERM_W) + denials |= DIR_WRITE; + if (mixperms & POSIX_PERM_R) + denials |= DIR_READ; + } else { + if (mixperms & POSIX_PERM_X) + denials |= FILE_EXEC; + if (mixperms & POSIX_PERM_W) + denials |= FILE_WRITE; + if (mixperms & POSIX_PERM_R) + denials |= FILE_READ; + } + } else { + mixperms = ~pset->grpperms & pset->othperms; + if (tag == POSIX_ACL_USER_OBJ) + mixperms |= pset->selfuserperms; + if (pset->isdir) { + if (mixperms & POSIX_PERM_X) + denials |= DIR_EXEC; + if (mixperms & POSIX_PERM_W) + denials |= DIR_WRITE; + if (mixperms & POSIX_PERM_R) + denials |= DIR_READ; + } else { + if (mixperms & POSIX_PERM_X) + denials |= FILE_EXEC; + if (mixperms & POSIX_PERM_W) + denials |= FILE_WRITE; + if (mixperms & POSIX_PERM_R) + denials |= FILE_READ; + } + } + denials &= ~grants; + if (denials) { + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->flags = flags; + pdace->size = cpu_to_le16(sidsz + 8); + pdace->mask = denials; + memcpy((char*)&pdace->sid, sid, sidsz); + pos += sidsz + 8; + acecnt++; + } + } + } + pacl->size = cpu_to_le16(pos); + pacl->ace_count = cpu_to_le16(acecnt); + return (!rejected); } static BOOL build_user_grants(ACL *pacl, - const SID *usid, struct MAPPING* const mapping[], - ACE_FLAGS flags, const struct POSIX_ACE *pxace, - struct BUILD_CONTEXT *pset) { - BIGSID defsid; - ACCESS_ALLOWED_ACE *pgace; - const SID *sid; - int sidsz; - int pos; - int acecnt; - le32 grants; - u16 perms; - u16 tag; - BOOL rejected; - BOOL rootuser; + const SID *usid, struct MAPPING* const mapping[], + ACE_FLAGS flags, const struct POSIX_ACE *pxace, + struct BUILD_CONTEXT *pset) +{ + BIGSID defsid; + ACCESS_ALLOWED_ACE *pgace; + const SID *sid; + int sidsz; + int pos; + int acecnt; + le32 grants; + u16 perms; + u16 tag; + BOOL rejected; + BOOL rootuser; - rejected = FALSE; - tag = pxace->tag; - perms = pxace->perms; - rootuser = FALSE; - pos = le16_to_cpu(pacl->size); - acecnt = le16_to_cpu(pacl->ace_count); - if (tag == POSIX_ACL_USER_OBJ) { - sid = usid; - sidsz = ntfs_sid_size(sid); - grants = OWNER_RIGHTS; - } else { - if (pxace->id) { - sid = NTFS_FIND_USID(mapping[MAPUSERS], - pxace->id, (SID*)&defsid); - if (sid) - sidsz = ntfs_sid_size(sid); - else - rejected = TRUE; - grants = WORLD_RIGHTS; - } else { - sid = adminsid; - sidsz = ntfs_sid_size(sid); - rootuser = TRUE; - grants = WORLD_RIGHTS & ~ROOT_OWNER_UNMARK; - } - } - if (!rejected) { - if (pset->isdir) { - if (perms & POSIX_PERM_X) - grants |= DIR_EXEC; - if (perms & POSIX_PERM_W) - grants |= DIR_WRITE; - if (perms & POSIX_PERM_R) - grants |= DIR_READ; - } else { - if (perms & POSIX_PERM_X) - grants |= FILE_EXEC; - if (perms & POSIX_PERM_W) - grants |= FILE_WRITE; - if (perms & POSIX_PERM_R) - grants |= FILE_READ; - } - if (rootuser) - grants &= ~ROOT_OWNER_UNMARK; - pgace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->size = cpu_to_le16(sidsz + 8); - pgace->flags = flags; - pgace->mask = grants; - memcpy((char*)&pgace->sid, sid, sidsz); - pos += sidsz + 8; - acecnt = le16_to_cpu(pacl->ace_count) + 1; - pacl->ace_count = cpu_to_le16(acecnt); - pacl->size = cpu_to_le16(pos); - } - return (!rejected); + rejected = FALSE; + tag = pxace->tag; + perms = pxace->perms; + rootuser = FALSE; + pos = le16_to_cpu(pacl->size); + acecnt = le16_to_cpu(pacl->ace_count); + if (tag == POSIX_ACL_USER_OBJ) { + sid = usid; + sidsz = ntfs_sid_size(sid); + grants = OWNER_RIGHTS; + } else { + if (pxace->id) { + sid = NTFS_FIND_USID(mapping[MAPUSERS], + pxace->id, (SID*)&defsid); + if (sid) + sidsz = ntfs_sid_size(sid); + else + rejected = TRUE; + grants = WORLD_RIGHTS; + } else { + sid = adminsid; + sidsz = ntfs_sid_size(sid); + rootuser = TRUE; + grants = WORLD_RIGHTS & ~ROOT_OWNER_UNMARK; + } + } + if (!rejected) { + if (pset->isdir) { + if (perms & POSIX_PERM_X) + grants |= DIR_EXEC; + if (perms & POSIX_PERM_W) + grants |= DIR_WRITE; + if (perms & POSIX_PERM_R) + grants |= DIR_READ; + } else { + if (perms & POSIX_PERM_X) + grants |= FILE_EXEC; + if (perms & POSIX_PERM_W) + grants |= FILE_WRITE; + if (perms & POSIX_PERM_R) + grants |= FILE_READ; + } + if (rootuser) + grants &= ~ROOT_OWNER_UNMARK; + pgace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->size = cpu_to_le16(sidsz + 8); + pgace->flags = flags; + pgace->mask = grants; + memcpy((char*)&pgace->sid, sid, sidsz); + pos += sidsz + 8; + acecnt = le16_to_cpu(pacl->ace_count) + 1; + pacl->ace_count = cpu_to_le16(acecnt); + pacl->size = cpu_to_le16(pos); + } + return (!rejected); } -/* a grant ACE for group */ -/* unless group-obj has the same rights as world */ -/* but present if group is owner or owner is administrator */ -/* this ACE will be inserted after denials for group */ + /* a grant ACE for group */ + /* unless group-obj has the same rights as world */ + /* but present if group is owner or owner is administrator */ + /* this ACE will be inserted after denials for group */ static BOOL build_group_denials_grant(ACL *pacl, - const SID *gsid, struct MAPPING* const mapping[], - ACE_FLAGS flags, const struct POSIX_ACE *pxace, - struct BUILD_CONTEXT *pset) { - BIGSID defsid; - ACCESS_ALLOWED_ACE *pdace; - ACCESS_ALLOWED_ACE *pgace; - const SID *sid; - int sidsz; - int pos; - int acecnt; - le32 grants; - le32 denials; - u16 perms; - u16 mixperms; - u16 tag; - BOOL avoidmask; - BOOL rootgroup; - BOOL rejected; + const SID *gsid, struct MAPPING* const mapping[], + ACE_FLAGS flags, const struct POSIX_ACE *pxace, + struct BUILD_CONTEXT *pset) +{ + BIGSID defsid; + ACCESS_ALLOWED_ACE *pdace; + ACCESS_ALLOWED_ACE *pgace; + const SID *sid; + int sidsz; + int pos; + int acecnt; + le32 grants; + le32 denials; + u16 perms; + u16 mixperms; + u16 tag; + BOOL avoidmask; + BOOL rootgroup; + BOOL rejected; - rejected = FALSE; - tag = pxace->tag; - perms = pxace->perms; - pos = le16_to_cpu(pacl->size); - acecnt = le16_to_cpu(pacl->ace_count); - rootgroup = FALSE; - avoidmask = (pset->mask == (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X)) - && ((pset->designates && pset->withmask) - || (!pset->designates && !pset->withmask)); - if (tag == POSIX_ACL_GROUP_OBJ) - sid = gsid; - else - if (pxace->id) - sid = NTFS_FIND_GSID(mapping[MAPGROUPS], - pxace->id, (SID*)&defsid); - else { - sid = adminsid; - rootgroup = TRUE; - } - if (sid) { - sidsz = ntfs_sid_size(sid); - /* - * Insert denial of complement of mask for - * each group - * WRITE_OWNER is inserted so that - * the mask can be identified - * Note : this mask may lead on Windows to - * deny rights to administrators belonging - * to some user group - */ - if ((!avoidmask && !rootgroup) - || (pset->rootspecial - && (tag == POSIX_ACL_GROUP_OBJ))) { - denials = WRITE_OWNER; - pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; - if (pset->isdir) { - if (!(pset->mask & POSIX_PERM_X)) - denials |= DIR_EXEC; - if (!(pset->mask & POSIX_PERM_W)) - denials |= DIR_WRITE; - if (!(pset->mask & POSIX_PERM_R)) - denials |= DIR_READ; - } else { - if (!(pset->mask & POSIX_PERM_X)) - denials |= FILE_EXEC; - if (!(pset->mask & POSIX_PERM_W)) - denials |= FILE_WRITE; - if (!(pset->mask & POSIX_PERM_R)) - denials |= FILE_READ; - } - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->flags = flags; - pdace->size = cpu_to_le16(sidsz + 8); - pdace->mask = denials; - memcpy((char*)&pdace->sid, sid, sidsz); - pos += sidsz + 8; - acecnt++; - } - } else - rejected = TRUE; - if (!rejected - && (pset->adminowns - || pset->groupowns - || avoidmask - || rootgroup - || (perms != pset->othperms))) { - grants = WORLD_RIGHTS; - if (rootgroup) - grants &= ~ROOT_GROUP_UNMARK; - if (pset->isdir) { - if (perms & POSIX_PERM_X) - grants |= DIR_EXEC; - if (perms & POSIX_PERM_W) - grants |= DIR_WRITE; - if (perms & POSIX_PERM_R) - grants |= DIR_READ; - } else { - if (perms & POSIX_PERM_X) - grants |= FILE_EXEC; - if (perms & POSIX_PERM_W) - grants |= FILE_WRITE; - if (perms & POSIX_PERM_R) - grants |= FILE_READ; - } + rejected = FALSE; + tag = pxace->tag; + perms = pxace->perms; + pos = le16_to_cpu(pacl->size); + acecnt = le16_to_cpu(pacl->ace_count); + rootgroup = FALSE; + avoidmask = (pset->mask == (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X)) + && ((pset->designates && pset->withmask) + || (!pset->designates && !pset->withmask)); + if (tag == POSIX_ACL_GROUP_OBJ) + sid = gsid; + else + if (pxace->id) + sid = NTFS_FIND_GSID(mapping[MAPGROUPS], + pxace->id, (SID*)&defsid); + else { + sid = adminsid; + rootgroup = TRUE; + } + if (sid) { + sidsz = ntfs_sid_size(sid); + /* + * Insert denial of complement of mask for + * each group + * WRITE_OWNER is inserted so that + * the mask can be identified + * Note : this mask may lead on Windows to + * deny rights to administrators belonging + * to some user group + */ + if ((!avoidmask && !rootgroup) + || (pset->rootspecial + && (tag == POSIX_ACL_GROUP_OBJ))) { + denials = WRITE_OWNER; + pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; + if (pset->isdir) { + if (!(pset->mask & POSIX_PERM_X)) + denials |= DIR_EXEC; + if (!(pset->mask & POSIX_PERM_W)) + denials |= DIR_WRITE; + if (!(pset->mask & POSIX_PERM_R)) + denials |= DIR_READ; + } else { + if (!(pset->mask & POSIX_PERM_X)) + denials |= FILE_EXEC; + if (!(pset->mask & POSIX_PERM_W)) + denials |= FILE_WRITE; + if (!(pset->mask & POSIX_PERM_R)) + denials |= FILE_READ; + } + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->flags = flags; + pdace->size = cpu_to_le16(sidsz + 8); + pdace->mask = denials; + memcpy((char*)&pdace->sid, sid, sidsz); + pos += sidsz + 8; + acecnt++; + } + } else + rejected = TRUE; + if (!rejected + && (pset->adminowns + || pset->groupowns + || avoidmask + || rootgroup + || (perms != pset->othperms))) { + grants = WORLD_RIGHTS; + if (rootgroup) + grants &= ~ROOT_GROUP_UNMARK; + if (pset->isdir) { + if (perms & POSIX_PERM_X) + grants |= DIR_EXEC; + if (perms & POSIX_PERM_W) + grants |= DIR_WRITE; + if (perms & POSIX_PERM_R) + grants |= DIR_READ; + } else { + if (perms & POSIX_PERM_X) + grants |= FILE_EXEC; + if (perms & POSIX_PERM_W) + grants |= FILE_WRITE; + if (perms & POSIX_PERM_R) + grants |= FILE_READ; + } - /* a possible ACE to deny group what it would get from world */ - /* or administrator, unless owner is administrator or group */ + /* a possible ACE to deny group what it would get from world */ + /* or administrator, unless owner is administrator or group */ - denials = const_cpu_to_le32(0); - pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; - if (!pset->adminowns - && !pset->groupowns - && !rootgroup) { - mixperms = pset->othperms; - if (tag == POSIX_ACL_GROUP_OBJ) - mixperms |= pset->selfgrpperms; - if (pset->isdir) { - if (mixperms & POSIX_PERM_X) - denials |= DIR_EXEC; - if (mixperms & POSIX_PERM_W) - denials |= DIR_WRITE; - if (mixperms & POSIX_PERM_R) - denials |= DIR_READ; - } else { - if (mixperms & POSIX_PERM_X) - denials |= FILE_EXEC; - if (mixperms & POSIX_PERM_W) - denials |= FILE_WRITE; - if (mixperms & POSIX_PERM_R) - denials |= FILE_READ; - } - denials &= ~(grants | OWNER_RIGHTS); - if (denials) { - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->flags = flags; - pdace->size = cpu_to_le16(sidsz + 8); - pdace->mask = denials; - memcpy((char*)&pdace->sid, sid, sidsz); - pos += sidsz + 8; - acecnt++; - } - } + denials = const_cpu_to_le32(0); + pdace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; + if (!pset->adminowns + && !pset->groupowns + && !rootgroup) { + mixperms = pset->othperms; + if (tag == POSIX_ACL_GROUP_OBJ) + mixperms |= pset->selfgrpperms; + if (pset->isdir) { + if (mixperms & POSIX_PERM_X) + denials |= DIR_EXEC; + if (mixperms & POSIX_PERM_W) + denials |= DIR_WRITE; + if (mixperms & POSIX_PERM_R) + denials |= DIR_READ; + } else { + if (mixperms & POSIX_PERM_X) + denials |= FILE_EXEC; + if (mixperms & POSIX_PERM_W) + denials |= FILE_WRITE; + if (mixperms & POSIX_PERM_R) + denials |= FILE_READ; + } + denials &= ~(grants | OWNER_RIGHTS); + if (denials) { + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->flags = flags; + pdace->size = cpu_to_le16(sidsz + 8); + pdace->mask = denials; + memcpy((char*)&pdace->sid, sid, sidsz); + pos += sidsz + 8; + acecnt++; + } + } - /* now insert grants to group if more than world */ - if (pset->adminowns - || pset->groupowns - || (avoidmask && (pset->designates || pset->withmask)) - || (perms & ~pset->othperms) - || (pset->rootspecial - && (tag == POSIX_ACL_GROUP_OBJ)) - || (tag == POSIX_ACL_GROUP)) { - if (rootgroup) - grants &= ~ROOT_GROUP_UNMARK; - pgace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->flags = flags; - pgace->size = cpu_to_le16(sidsz + 8); - pgace->mask = grants; - memcpy((char*)&pgace->sid, sid, sidsz); - pos += sidsz + 8; - acecnt++; - } - } - pacl->size = cpu_to_le16(pos); - pacl->ace_count = cpu_to_le16(acecnt); - return (!rejected); + /* now insert grants to group if more than world */ + if (pset->adminowns + || pset->groupowns + || (avoidmask && (pset->designates || pset->withmask)) + || (perms & ~pset->othperms) + || (pset->rootspecial + && (tag == POSIX_ACL_GROUP_OBJ)) + || (tag == POSIX_ACL_GROUP)) { + if (rootgroup) + grants &= ~ROOT_GROUP_UNMARK; + pgace = (ACCESS_DENIED_ACE*)&((char*)pacl)[pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->flags = flags; + pgace->size = cpu_to_le16(sidsz + 8); + pgace->mask = grants; + memcpy((char*)&pgace->sid, sid, sidsz); + pos += sidsz + 8; + acecnt++; + } + } + pacl->size = cpu_to_le16(pos); + pacl->ace_count = cpu_to_le16(acecnt); + return (!rejected); } @@ -1777,7 +1803,7 @@ static BOOL build_group_denials_grant(ACL *pacl, * - grants to owner (always present - first grant) * + grants to designated user * + mask denial to group (unless mask allows all) - * - denials to group (preventing grants to world to apply) + * - denials to group (preventing grants to world to apply) * - grants to group (unless group has no more than world rights) * + mask denials to designated group (unless mask allows all) * + grants to designated group @@ -1850,637 +1876,639 @@ static BOOL build_group_denials_grant(ACL *pacl, */ static int buildacls_posix(struct MAPPING* const mapping[], - char *secattr, int offs, const struct POSIX_SECURITY *pxdesc, - int isdir, const SID *usid, const SID *gsid) { - struct BUILD_CONTEXT aceset[2], *pset; - BOOL adminowns; - BOOL groupowns; - ACL *pacl; - ACCESS_ALLOWED_ACE *pgace; - ACCESS_ALLOWED_ACE *pdace; - const struct POSIX_ACE *pxace; - BOOL ok; - mode_t mode; - u16 tag; - u16 perms; - ACE_FLAGS flags; - int pos; - int i; - int k; - BIGSID defsid; - const SID *sid; - int acecnt; - int usidsz; - int gsidsz; - int wsidsz; - int asidsz; - int ssidsz; - int nsidsz; - le32 grants; + char *secattr, int offs, const struct POSIX_SECURITY *pxdesc, + int isdir, const SID *usid, const SID *gsid) +{ + struct BUILD_CONTEXT aceset[2], *pset; + BOOL adminowns; + BOOL groupowns; + ACL *pacl; + ACCESS_ALLOWED_ACE *pgace; + ACCESS_ALLOWED_ACE *pdace; + const struct POSIX_ACE *pxace; + BOOL ok; + mode_t mode; + u16 tag; + u16 perms; + ACE_FLAGS flags; + int pos; + int i; + int k; + BIGSID defsid; + const SID *sid; + int acecnt; + int usidsz; + int gsidsz; + int wsidsz; + int asidsz; + int ssidsz; + int nsidsz; + le32 grants; - usidsz = ntfs_sid_size(usid); - gsidsz = ntfs_sid_size(gsid); - wsidsz = ntfs_sid_size(worldsid); - asidsz = ntfs_sid_size(adminsid); - ssidsz = ntfs_sid_size(systemsid); - mode = pxdesc->mode; - /* adminowns and groupowns are used for both lists */ - adminowns = ntfs_same_sid(usid, adminsid) - || ntfs_same_sid(gsid, adminsid); - groupowns = !adminowns && ntfs_same_sid(usid, gsid); + usidsz = ntfs_sid_size(usid); + gsidsz = ntfs_sid_size(gsid); + wsidsz = ntfs_sid_size(worldsid); + asidsz = ntfs_sid_size(adminsid); + ssidsz = ntfs_sid_size(systemsid); + mode = pxdesc->mode; + /* adminowns and groupowns are used for both lists */ + adminowns = ntfs_same_sid(usid, adminsid) + || ntfs_same_sid(gsid, adminsid); + groupowns = !adminowns && ntfs_same_sid(usid, gsid); - ok = TRUE; + ok = TRUE; - /* ACL header */ - pacl = (ACL*)&secattr[offs]; - pacl->revision = ACL_REVISION; - pacl->alignment1 = 0; - pacl->size = cpu_to_le16(sizeof(ACL) + usidsz + 8); - pacl->ace_count = const_cpu_to_le16(0); - pacl->alignment2 = const_cpu_to_le16(0); + /* ACL header */ + pacl = (ACL*)&secattr[offs]; + pacl->revision = ACL_REVISION; + pacl->alignment1 = 0; + pacl->size = cpu_to_le16(sizeof(ACL) + usidsz + 8); + pacl->ace_count = const_cpu_to_le16(0); + pacl->alignment2 = const_cpu_to_le16(0); - /* - * Determine what is allowed to some group or world - * to prevent designated users or other groups to get - * rights from groups or world - * Do the same if owner and group appear as designated - * user or group - * Also get global mask - */ - for (k=0; k<2; k++) { - pset = &aceset[k]; - pset->selfuserperms = 0; - pset->selfgrpperms = 0; - pset->grpperms = 0; - pset->othperms = 0; - pset->mask = (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X); - pset->designates = 0; - pset->withmask = 0; - pset->rootspecial = 0; - pset->adminowns = adminowns; - pset->groupowns = groupowns; - pset->isdir = isdir; - } + /* + * Determine what is allowed to some group or world + * to prevent designated users or other groups to get + * rights from groups or world + * Do the same if owner and group appear as designated + * user or group + * Also get global mask + */ + for (k=0; k<2; k++) { + pset = &aceset[k]; + pset->selfuserperms = 0; + pset->selfgrpperms = 0; + pset->grpperms = 0; + pset->othperms = 0; + pset->mask = (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X); + pset->designates = 0; + pset->withmask = 0; + pset->rootspecial = 0; + pset->adminowns = adminowns; + pset->groupowns = groupowns; + pset->isdir = isdir; + } - for (i=pxdesc->acccnt+pxdesc->defcnt-1; i>=0; i--) { - if (i >= pxdesc->acccnt) { - pset = &aceset[1]; - pxace = &pxdesc->acl.ace[i + pxdesc->firstdef - pxdesc->acccnt]; - } else { - pset = &aceset[0]; - pxace = &pxdesc->acl.ace[i]; - } - switch (pxace->tag) { - case POSIX_ACL_USER : - pset->designates++; - if (pxace->id) { - sid = NTFS_FIND_USID(mapping[MAPUSERS], - pxace->id, (SID*)&defsid); - if (sid && ntfs_same_sid(sid,usid)) - pset->selfuserperms |= pxace->perms; - } else - /* root as designated user is processed apart */ - pset->rootspecial = TRUE; - break; - case POSIX_ACL_GROUP : - pset->designates++; - if (pxace->id) { - sid = NTFS_FIND_GSID(mapping[MAPUSERS], - pxace->id, (SID*)&defsid); - if (sid && ntfs_same_sid(sid,gsid)) - pset->selfgrpperms |= pxace->perms; - } else - /* root as designated group is processed apart */ - pset->rootspecial = TRUE; - /* fall through */ - case POSIX_ACL_GROUP_OBJ : - pset->grpperms |= pxace->perms; - break; - case POSIX_ACL_OTHER : - pset->othperms = pxace->perms; - break; - case POSIX_ACL_MASK : - pset->withmask++; - pset->mask = pxace->perms; - default : - break; - } - } + for (i=pxdesc->acccnt+pxdesc->defcnt-1; i>=0; i--) { + if (i >= pxdesc->acccnt) { + pset = &aceset[1]; + pxace = &pxdesc->acl.ace[i + pxdesc->firstdef - pxdesc->acccnt]; + } else { + pset = &aceset[0]; + pxace = &pxdesc->acl.ace[i]; + } + switch (pxace->tag) { + case POSIX_ACL_USER : + pset->designates++; + if (pxace->id) { + sid = NTFS_FIND_USID(mapping[MAPUSERS], + pxace->id, (SID*)&defsid); + if (sid && ntfs_same_sid(sid,usid)) + pset->selfuserperms |= pxace->perms; + } else + /* root as designated user is processed apart */ + pset->rootspecial = TRUE; + break; + case POSIX_ACL_GROUP : + pset->designates++; + if (pxace->id) { + sid = NTFS_FIND_GSID(mapping[MAPUSERS], + pxace->id, (SID*)&defsid); + if (sid && ntfs_same_sid(sid,gsid)) + pset->selfgrpperms |= pxace->perms; + } else + /* root as designated group is processed apart */ + pset->rootspecial = TRUE; + /* fall through */ + case POSIX_ACL_GROUP_OBJ : + pset->grpperms |= pxace->perms; + break; + case POSIX_ACL_OTHER : + pset->othperms = pxace->perms; + break; + case POSIX_ACL_MASK : + pset->withmask++; + pset->mask = pxace->perms; + default : + break; + } + } - if (pxdesc->defcnt && (pxdesc->firstdef != pxdesc->acccnt)) { - ntfs_log_error("** error : access and default not consecutive\n"); - return (0); - } - /* - * First insert all denials for owner and each - * designated user (with mask if needed) - */ +if (pxdesc->defcnt && (pxdesc->firstdef != pxdesc->acccnt)) { +ntfs_log_error("** error : access and default not consecutive\n"); +return (0); +} + /* + * First insert all denials for owner and each + * designated user (with mask if needed) + */ - pacl->ace_count = const_cpu_to_le16(0); - pacl->size = const_cpu_to_le16(sizeof(ACL)); - for (i=0; (i<(pxdesc->acccnt + pxdesc->defcnt)) && ok; i++) { - if (i >= pxdesc->acccnt) { - flags = INHERIT_ONLY_ACE - | OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; - pset = &aceset[1]; - pxace = &pxdesc->acl.ace[i + pxdesc->firstdef - pxdesc->acccnt]; - } else { - if (pxdesc->defcnt) - flags = NO_PROPAGATE_INHERIT_ACE; - else - flags = (isdir ? DIR_INHERITANCE - : FILE_INHERITANCE); - pset = &aceset[0]; - pxace = &pxdesc->acl.ace[i]; - } - tag = pxace->tag; - perms = pxace->perms; - switch (tag) { + pacl->ace_count = const_cpu_to_le16(0); + pacl->size = const_cpu_to_le16(sizeof(ACL)); + for (i=0; (i<(pxdesc->acccnt + pxdesc->defcnt)) && ok; i++) { + if (i >= pxdesc->acccnt) { + flags = INHERIT_ONLY_ACE + | OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; + pset = &aceset[1]; + pxace = &pxdesc->acl.ace[i + pxdesc->firstdef - pxdesc->acccnt]; + } else { + if (pxdesc->defcnt) + flags = NO_PROPAGATE_INHERIT_ACE; + else + flags = (isdir ? DIR_INHERITANCE + : FILE_INHERITANCE); + pset = &aceset[0]; + pxace = &pxdesc->acl.ace[i]; + } + tag = pxace->tag; + perms = pxace->perms; + switch (tag) { - /* insert denial ACEs for each owner or allowed user */ + /* insert denial ACEs for each owner or allowed user */ - case POSIX_ACL_USER : - case POSIX_ACL_USER_OBJ : + case POSIX_ACL_USER : + case POSIX_ACL_USER_OBJ : - ok = build_user_denials(pacl, - usid, mapping, flags, pxace, pset); - break; - default : - break; - } - } + ok = build_user_denials(pacl, + usid, mapping, flags, pxace, pset); + break; + default : + break; + } + } - /* - * for directories, insert a world execution denial - * inherited to plain files. - * This is to prevent Windows from granting execution - * of files through inheritance from parent directory - */ + /* + * for directories, insert a world execution denial + * inherited to plain files. + * This is to prevent Windows from granting execution + * of files through inheritance from parent directory + */ - if (isdir && ok) { - pos = le16_to_cpu(pacl->size); - pdace = (ACCESS_DENIED_ACE*) &secattr[offs + pos]; - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->flags = INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE; - pdace->size = cpu_to_le16(wsidsz + 8); - pdace->mask = FILE_EXEC; - memcpy((char*)&pdace->sid, worldsid, wsidsz); - pos += wsidsz + 8; - acecnt = le16_to_cpu(pacl->ace_count) + 1; - pacl->ace_count = cpu_to_le16(acecnt); - pacl->size = cpu_to_le16(pos); - } + if (isdir && ok) { + pos = le16_to_cpu(pacl->size); + pdace = (ACCESS_DENIED_ACE*) &secattr[offs + pos]; + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->flags = INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE; + pdace->size = cpu_to_le16(wsidsz + 8); + pdace->mask = FILE_EXEC; + memcpy((char*)&pdace->sid, worldsid, wsidsz); + pos += wsidsz + 8; + acecnt = le16_to_cpu(pacl->ace_count) + 1; + pacl->ace_count = cpu_to_le16(acecnt); + pacl->size = cpu_to_le16(pos); + } - /* - * now insert (if needed) - * - grants to owner and designated users - * - mask and denials for all groups - * - grants to other - */ + /* + * now insert (if needed) + * - grants to owner and designated users + * - mask and denials for all groups + * - grants to other + */ - for (i=0; (i<(pxdesc->acccnt + pxdesc->defcnt)) && ok; i++) { - if (i >= pxdesc->acccnt) { - flags = INHERIT_ONLY_ACE - | OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; - pset = &aceset[1]; - pxace = &pxdesc->acl.ace[i + pxdesc->firstdef - pxdesc->acccnt]; - } else { - if (pxdesc->defcnt) - flags = NO_PROPAGATE_INHERIT_ACE; - else - flags = (isdir ? DIR_INHERITANCE - : FILE_INHERITANCE); - pset = &aceset[0]; - pxace = &pxdesc->acl.ace[i]; - } - tag = pxace->tag; - perms = pxace->perms; - switch (tag) { + for (i=0; (i<(pxdesc->acccnt + pxdesc->defcnt)) && ok; i++) { + if (i >= pxdesc->acccnt) { + flags = INHERIT_ONLY_ACE + | OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; + pset = &aceset[1]; + pxace = &pxdesc->acl.ace[i + pxdesc->firstdef - pxdesc->acccnt]; + } else { + if (pxdesc->defcnt) + flags = NO_PROPAGATE_INHERIT_ACE; + else + flags = (isdir ? DIR_INHERITANCE + : FILE_INHERITANCE); + pset = &aceset[0]; + pxace = &pxdesc->acl.ace[i]; + } + tag = pxace->tag; + perms = pxace->perms; + switch (tag) { - /* ACE for each owner or allowed user */ + /* ACE for each owner or allowed user */ - case POSIX_ACL_USER : - case POSIX_ACL_USER_OBJ : - ok = build_user_grants(pacl,usid, - mapping,flags,pxace,pset); - break; + case POSIX_ACL_USER : + case POSIX_ACL_USER_OBJ : + ok = build_user_grants(pacl,usid, + mapping,flags,pxace,pset); + break; - case POSIX_ACL_GROUP : - case POSIX_ACL_GROUP_OBJ : + case POSIX_ACL_GROUP : + case POSIX_ACL_GROUP_OBJ : - /* denials and grants for groups */ + /* denials and grants for groups */ - ok = build_group_denials_grant(pacl,gsid, - mapping,flags,pxace,pset); - break; + ok = build_group_denials_grant(pacl,gsid, + mapping,flags,pxace,pset); + break; - case POSIX_ACL_OTHER : + case POSIX_ACL_OTHER : - /* grants for other users */ + /* grants for other users */ - pos = le16_to_cpu(pacl->size); - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - grants = WORLD_RIGHTS; - if (isdir) { - if (perms & POSIX_PERM_X) - grants |= DIR_EXEC; - if (perms & POSIX_PERM_W) - grants |= DIR_WRITE; - if (perms & POSIX_PERM_R) - grants |= DIR_READ; - } else { - if (perms & POSIX_PERM_X) - grants |= FILE_EXEC; - if (perms & POSIX_PERM_W) - grants |= FILE_WRITE; - if (perms & POSIX_PERM_R) - grants |= FILE_READ; - } - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->flags = flags; - pgace->size = cpu_to_le16(wsidsz + 8); - pgace->mask = grants; - memcpy((char*)&pgace->sid, worldsid, wsidsz); - pos += wsidsz + 8; - acecnt = le16_to_cpu(pacl->ace_count) + 1; - pacl->ace_count = cpu_to_le16(acecnt); - pacl->size = cpu_to_le16(pos); - break; - } - } + pos = le16_to_cpu(pacl->size); + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + grants = WORLD_RIGHTS; + if (isdir) { + if (perms & POSIX_PERM_X) + grants |= DIR_EXEC; + if (perms & POSIX_PERM_W) + grants |= DIR_WRITE; + if (perms & POSIX_PERM_R) + grants |= DIR_READ; + } else { + if (perms & POSIX_PERM_X) + grants |= FILE_EXEC; + if (perms & POSIX_PERM_W) + grants |= FILE_WRITE; + if (perms & POSIX_PERM_R) + grants |= FILE_READ; + } + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->flags = flags; + pgace->size = cpu_to_le16(wsidsz + 8); + pgace->mask = grants; + memcpy((char*)&pgace->sid, worldsid, wsidsz); + pos += wsidsz + 8; + acecnt = le16_to_cpu(pacl->ace_count) + 1; + pacl->ace_count = cpu_to_le16(acecnt); + pacl->size = cpu_to_le16(pos); + break; + } + } - if (!ok) { - errno = EINVAL; - pos = 0; - } else { - /* an ACE for administrators */ - /* always full access */ + if (!ok) { + errno = EINVAL; + pos = 0; + } else { + /* an ACE for administrators */ + /* always full access */ - pos = le16_to_cpu(pacl->size); - acecnt = le16_to_cpu(pacl->ace_count); - if (isdir) - flags = OBJECT_INHERIT_ACE - | CONTAINER_INHERIT_ACE; - else - flags = NO_PROPAGATE_INHERIT_ACE; - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->flags = flags; - pgace->size = cpu_to_le16(asidsz + 8); - grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; - pgace->mask = grants; - memcpy((char*)&pgace->sid, adminsid, asidsz); - pos += asidsz + 8; - acecnt++; + pos = le16_to_cpu(pacl->size); + acecnt = le16_to_cpu(pacl->ace_count); + if (isdir) + flags = OBJECT_INHERIT_ACE + | CONTAINER_INHERIT_ACE; + else + flags = NO_PROPAGATE_INHERIT_ACE; + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->flags = flags; + pgace->size = cpu_to_le16(asidsz + 8); + grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; + pgace->mask = grants; + memcpy((char*)&pgace->sid, adminsid, asidsz); + pos += asidsz + 8; + acecnt++; - /* an ACE for system (needed ?) */ - /* always full access */ + /* an ACE for system (needed ?) */ + /* always full access */ - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->flags = flags; - pgace->size = cpu_to_le16(ssidsz + 8); - grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; - pgace->mask = grants; - memcpy((char*)&pgace->sid, systemsid, ssidsz); - pos += ssidsz + 8; - acecnt++; + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->flags = flags; + pgace->size = cpu_to_le16(ssidsz + 8); + grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; + pgace->mask = grants; + memcpy((char*)&pgace->sid, systemsid, ssidsz); + pos += ssidsz + 8; + acecnt++; - /* a null ACE to hold special flags */ - /* using the same representation as cygwin */ + /* a null ACE to hold special flags */ + /* using the same representation as cygwin */ - if (mode & (S_ISVTX | S_ISGID | S_ISUID)) { - nsidsz = ntfs_sid_size(nullsid); - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->flags = NO_PROPAGATE_INHERIT_ACE; - pgace->size = cpu_to_le16(nsidsz + 8); - grants = const_cpu_to_le32(0); - if (mode & S_ISUID) - grants |= FILE_APPEND_DATA; - if (mode & S_ISGID) - grants |= FILE_WRITE_DATA; - if (mode & S_ISVTX) - grants |= FILE_READ_DATA; - pgace->mask = grants; - memcpy((char*)&pgace->sid, nullsid, nsidsz); - pos += nsidsz + 8; - acecnt++; - } + if (mode & (S_ISVTX | S_ISGID | S_ISUID)) { + nsidsz = ntfs_sid_size(nullsid); + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->flags = NO_PROPAGATE_INHERIT_ACE; + pgace->size = cpu_to_le16(nsidsz + 8); + grants = const_cpu_to_le32(0); + if (mode & S_ISUID) + grants |= FILE_APPEND_DATA; + if (mode & S_ISGID) + grants |= FILE_WRITE_DATA; + if (mode & S_ISVTX) + grants |= FILE_READ_DATA; + pgace->mask = grants; + memcpy((char*)&pgace->sid, nullsid, nsidsz); + pos += nsidsz + 8; + acecnt++; + } - /* fix ACL header */ - pacl->size = cpu_to_le16(pos); - pacl->ace_count = cpu_to_le16(acecnt); - } - return (ok ? pos : 0); + /* fix ACL header */ + pacl->size = cpu_to_le16(pos); + pacl->ace_count = cpu_to_le16(acecnt); + } + return (ok ? pos : 0); } #endif /* POSIXACLS */ static int buildacls(char *secattr, int offs, mode_t mode, int isdir, - const SID * usid, const SID * gsid) { - ACL *pacl; - ACCESS_ALLOWED_ACE *pgace; - ACCESS_ALLOWED_ACE *pdace; - BOOL adminowns; - BOOL groupowns; - ACE_FLAGS gflags; - int pos; - int acecnt; - int usidsz; - int gsidsz; - int wsidsz; - int asidsz; - int ssidsz; - int nsidsz; - le32 grants; - le32 denials; + const SID * usid, const SID * gsid) +{ + ACL *pacl; + ACCESS_ALLOWED_ACE *pgace; + ACCESS_ALLOWED_ACE *pdace; + BOOL adminowns; + BOOL groupowns; + ACE_FLAGS gflags; + int pos; + int acecnt; + int usidsz; + int gsidsz; + int wsidsz; + int asidsz; + int ssidsz; + int nsidsz; + le32 grants; + le32 denials; - usidsz = ntfs_sid_size(usid); - gsidsz = ntfs_sid_size(gsid); - wsidsz = ntfs_sid_size(worldsid); - asidsz = ntfs_sid_size(adminsid); - ssidsz = ntfs_sid_size(systemsid); - adminowns = ntfs_same_sid(usid, adminsid) - || ntfs_same_sid(gsid, adminsid); - groupowns = !adminowns && ntfs_same_sid(usid, gsid); + usidsz = ntfs_sid_size(usid); + gsidsz = ntfs_sid_size(gsid); + wsidsz = ntfs_sid_size(worldsid); + asidsz = ntfs_sid_size(adminsid); + ssidsz = ntfs_sid_size(systemsid); + adminowns = ntfs_same_sid(usid, adminsid) + || ntfs_same_sid(gsid, adminsid); + groupowns = !adminowns && ntfs_same_sid(usid, gsid); - /* ACL header */ - pacl = (ACL*)&secattr[offs]; - pacl->revision = ACL_REVISION; - pacl->alignment1 = 0; - pacl->size = cpu_to_le16(sizeof(ACL) + usidsz + 8); - pacl->ace_count = const_cpu_to_le16(1); - pacl->alignment2 = const_cpu_to_le16(0); - pos = sizeof(ACL); - acecnt = 0; + /* ACL header */ + pacl = (ACL*)&secattr[offs]; + pacl->revision = ACL_REVISION; + pacl->alignment1 = 0; + pacl->size = cpu_to_le16(sizeof(ACL) + usidsz + 8); + pacl->ace_count = const_cpu_to_le16(1); + pacl->alignment2 = const_cpu_to_le16(0); + pos = sizeof(ACL); + acecnt = 0; - /* compute a grant ACE for owner */ - /* this ACE will be inserted after denial for owner */ + /* compute a grant ACE for owner */ + /* this ACE will be inserted after denial for owner */ - grants = OWNER_RIGHTS; - if (isdir) { - gflags = DIR_INHERITANCE; - if (mode & S_IXUSR) - grants |= DIR_EXEC; - if (mode & S_IWUSR) - grants |= DIR_WRITE; - if (mode & S_IRUSR) - grants |= DIR_READ; - } else { - gflags = FILE_INHERITANCE; - if (mode & S_IXUSR) - grants |= FILE_EXEC; - if (mode & S_IWUSR) - grants |= FILE_WRITE; - if (mode & S_IRUSR) - grants |= FILE_READ; - } + grants = OWNER_RIGHTS; + if (isdir) { + gflags = DIR_INHERITANCE; + if (mode & S_IXUSR) + grants |= DIR_EXEC; + if (mode & S_IWUSR) + grants |= DIR_WRITE; + if (mode & S_IRUSR) + grants |= DIR_READ; + } else { + gflags = FILE_INHERITANCE; + if (mode & S_IXUSR) + grants |= FILE_EXEC; + if (mode & S_IWUSR) + grants |= FILE_WRITE; + if (mode & S_IRUSR) + grants |= FILE_READ; + } - /* a possible ACE to deny owner what he/she would */ - /* induely get from administrator, group or world */ - /* unless owner is administrator or group */ + /* a possible ACE to deny owner what he/she would */ + /* induely get from administrator, group or world */ + /* unless owner is administrator or group */ - denials = const_cpu_to_le32(0); - pdace = (ACCESS_DENIED_ACE*) &secattr[offs + pos]; - if (!adminowns) { - if (!groupowns) { - if (isdir) { - pdace->flags = DIR_INHERITANCE; - if (mode & (S_IXGRP | S_IXOTH)) - denials |= DIR_EXEC; - if (mode & (S_IWGRP | S_IWOTH)) - denials |= DIR_WRITE; - if (mode & (S_IRGRP | S_IROTH)) - denials |= DIR_READ; - } else { - pdace->flags = FILE_INHERITANCE; - if (mode & (S_IXGRP | S_IXOTH)) - denials |= FILE_EXEC; - if (mode & (S_IWGRP | S_IWOTH)) - denials |= FILE_WRITE; - if (mode & (S_IRGRP | S_IROTH)) - denials |= FILE_READ; - } - } else { - if (isdir) { - pdace->flags = DIR_INHERITANCE; - if ((mode & S_IXOTH) && !(mode & S_IXGRP)) - denials |= DIR_EXEC; - if ((mode & S_IWOTH) && !(mode & S_IWGRP)) - denials |= DIR_WRITE; - if ((mode & S_IROTH) && !(mode & S_IRGRP)) - denials |= DIR_READ; - } else { - pdace->flags = FILE_INHERITANCE; - if ((mode & S_IXOTH) && !(mode & S_IXGRP)) - denials |= FILE_EXEC; - if ((mode & S_IWOTH) && !(mode & S_IWGRP)) - denials |= FILE_WRITE; - if ((mode & S_IROTH) && !(mode & S_IRGRP)) - denials |= FILE_READ; - } - } - denials &= ~grants; - if (denials) { - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->size = cpu_to_le16(usidsz + 8); - pdace->mask = denials; - memcpy((char*)&pdace->sid, usid, usidsz); - pos += usidsz + 8; - acecnt++; - } - } - /* - * for directories, a world execution denial - * inherited to plain files - */ + denials = const_cpu_to_le32(0); + pdace = (ACCESS_DENIED_ACE*) &secattr[offs + pos]; + if (!adminowns) { + if (!groupowns) { + if (isdir) { + pdace->flags = DIR_INHERITANCE; + if (mode & (S_IXGRP | S_IXOTH)) + denials |= DIR_EXEC; + if (mode & (S_IWGRP | S_IWOTH)) + denials |= DIR_WRITE; + if (mode & (S_IRGRP | S_IROTH)) + denials |= DIR_READ; + } else { + pdace->flags = FILE_INHERITANCE; + if (mode & (S_IXGRP | S_IXOTH)) + denials |= FILE_EXEC; + if (mode & (S_IWGRP | S_IWOTH)) + denials |= FILE_WRITE; + if (mode & (S_IRGRP | S_IROTH)) + denials |= FILE_READ; + } + } else { + if (isdir) { + pdace->flags = DIR_INHERITANCE; + if ((mode & S_IXOTH) && !(mode & S_IXGRP)) + denials |= DIR_EXEC; + if ((mode & S_IWOTH) && !(mode & S_IWGRP)) + denials |= DIR_WRITE; + if ((mode & S_IROTH) && !(mode & S_IRGRP)) + denials |= DIR_READ; + } else { + pdace->flags = FILE_INHERITANCE; + if ((mode & S_IXOTH) && !(mode & S_IXGRP)) + denials |= FILE_EXEC; + if ((mode & S_IWOTH) && !(mode & S_IWGRP)) + denials |= FILE_WRITE; + if ((mode & S_IROTH) && !(mode & S_IRGRP)) + denials |= FILE_READ; + } + } + denials &= ~grants; + if (denials) { + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->size = cpu_to_le16(usidsz + 8); + pdace->mask = denials; + memcpy((char*)&pdace->sid, usid, usidsz); + pos += usidsz + 8; + acecnt++; + } + } + /* + * for directories, a world execution denial + * inherited to plain files + */ - if (isdir) { - pdace = (ACCESS_DENIED_ACE*) &secattr[offs + pos]; - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->flags = INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE; - pdace->size = cpu_to_le16(wsidsz + 8); - pdace->mask = FILE_EXEC; - memcpy((char*)&pdace->sid, worldsid, wsidsz); - pos += wsidsz + 8; - acecnt++; - } + if (isdir) { + pdace = (ACCESS_DENIED_ACE*) &secattr[offs + pos]; + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->flags = INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE; + pdace->size = cpu_to_le16(wsidsz + 8); + pdace->mask = FILE_EXEC; + memcpy((char*)&pdace->sid, worldsid, wsidsz); + pos += wsidsz + 8; + acecnt++; + } - /* now insert grants to owner */ - pgace = (ACCESS_ALLOWED_ACE*) &secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->size = cpu_to_le16(usidsz + 8); - pgace->flags = gflags; - pgace->mask = grants; - memcpy((char*)&pgace->sid, usid, usidsz); - pos += usidsz + 8; - acecnt++; + /* now insert grants to owner */ + pgace = (ACCESS_ALLOWED_ACE*) &secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->size = cpu_to_le16(usidsz + 8); + pgace->flags = gflags; + pgace->mask = grants; + memcpy((char*)&pgace->sid, usid, usidsz); + pos += usidsz + 8; + acecnt++; - /* a grant ACE for group */ - /* unless group has the same rights as world */ - /* but present if group is owner or owner is administrator */ - /* this ACE will be inserted after denials for group */ + /* a grant ACE for group */ + /* unless group has the same rights as world */ + /* but present if group is owner or owner is administrator */ + /* this ACE will be inserted after denials for group */ - if (adminowns - || groupowns - || (((mode >> 3) ^ mode) & 7)) { - grants = WORLD_RIGHTS; - if (isdir) { - gflags = DIR_INHERITANCE; - if (mode & S_IXGRP) - grants |= DIR_EXEC; - if (mode & S_IWGRP) - grants |= DIR_WRITE; - if (mode & S_IRGRP) - grants |= DIR_READ; - } else { - gflags = FILE_INHERITANCE; - if (mode & S_IXGRP) - grants |= FILE_EXEC; - if (mode & S_IWGRP) - grants |= FILE_WRITE; - if (mode & S_IRGRP) - grants |= FILE_READ; - } + if (adminowns + || groupowns + || (((mode >> 3) ^ mode) & 7)) { + grants = WORLD_RIGHTS; + if (isdir) { + gflags = DIR_INHERITANCE; + if (mode & S_IXGRP) + grants |= DIR_EXEC; + if (mode & S_IWGRP) + grants |= DIR_WRITE; + if (mode & S_IRGRP) + grants |= DIR_READ; + } else { + gflags = FILE_INHERITANCE; + if (mode & S_IXGRP) + grants |= FILE_EXEC; + if (mode & S_IWGRP) + grants |= FILE_WRITE; + if (mode & S_IRGRP) + grants |= FILE_READ; + } - /* a possible ACE to deny group what it would get from world */ - /* or administrator, unless owner is administrator or group */ + /* a possible ACE to deny group what it would get from world */ + /* or administrator, unless owner is administrator or group */ - denials = const_cpu_to_le32(0); - pdace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - if (!adminowns && !groupowns) { - if (isdir) { - pdace->flags = DIR_INHERITANCE; - if (mode & S_IXOTH) - denials |= DIR_EXEC; - if (mode & S_IWOTH) - denials |= DIR_WRITE; - if (mode & S_IROTH) - denials |= DIR_READ; - } else { - pdace->flags = FILE_INHERITANCE; - if (mode & S_IXOTH) - denials |= FILE_EXEC; - if (mode & S_IWOTH) - denials |= FILE_WRITE; - if (mode & S_IROTH) - denials |= FILE_READ; - } - denials &= ~(grants | OWNER_RIGHTS); - if (denials) { - pdace->type = ACCESS_DENIED_ACE_TYPE; - pdace->size = cpu_to_le16(gsidsz + 8); - pdace->mask = denials; - memcpy((char*)&pdace->sid, gsid, gsidsz); - pos += gsidsz + 8; - acecnt++; - } - } + denials = const_cpu_to_le32(0); + pdace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + if (!adminowns && !groupowns) { + if (isdir) { + pdace->flags = DIR_INHERITANCE; + if (mode & S_IXOTH) + denials |= DIR_EXEC; + if (mode & S_IWOTH) + denials |= DIR_WRITE; + if (mode & S_IROTH) + denials |= DIR_READ; + } else { + pdace->flags = FILE_INHERITANCE; + if (mode & S_IXOTH) + denials |= FILE_EXEC; + if (mode & S_IWOTH) + denials |= FILE_WRITE; + if (mode & S_IROTH) + denials |= FILE_READ; + } + denials &= ~(grants | OWNER_RIGHTS); + if (denials) { + pdace->type = ACCESS_DENIED_ACE_TYPE; + pdace->size = cpu_to_le16(gsidsz + 8); + pdace->mask = denials; + memcpy((char*)&pdace->sid, gsid, gsidsz); + pos += gsidsz + 8; + acecnt++; + } + } - if (adminowns - || groupowns - || ((mode >> 3) & ~mode & 7)) { - /* now insert grants to group */ - /* if more rights than other */ - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->flags = gflags; - pgace->size = cpu_to_le16(gsidsz + 8); - pgace->mask = grants; - memcpy((char*)&pgace->sid, gsid, gsidsz); - pos += gsidsz + 8; - acecnt++; - } - } + if (adminowns + || groupowns + || ((mode >> 3) & ~mode & 7)) { + /* now insert grants to group */ + /* if more rights than other */ + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->flags = gflags; + pgace->size = cpu_to_le16(gsidsz + 8); + pgace->mask = grants; + memcpy((char*)&pgace->sid, gsid, gsidsz); + pos += gsidsz + 8; + acecnt++; + } + } - /* an ACE for world users */ + /* an ACE for world users */ - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - grants = WORLD_RIGHTS; - if (isdir) { - pgace->flags = DIR_INHERITANCE; - if (mode & S_IXOTH) - grants |= DIR_EXEC; - if (mode & S_IWOTH) - grants |= DIR_WRITE; - if (mode & S_IROTH) - grants |= DIR_READ; - } else { - pgace->flags = FILE_INHERITANCE; - if (mode & S_IXOTH) - grants |= FILE_EXEC; - if (mode & S_IWOTH) - grants |= FILE_WRITE; - if (mode & S_IROTH) - grants |= FILE_READ; - } - pgace->size = cpu_to_le16(wsidsz + 8); - pgace->mask = grants; - memcpy((char*)&pgace->sid, worldsid, wsidsz); - pos += wsidsz + 8; - acecnt++; + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + grants = WORLD_RIGHTS; + if (isdir) { + pgace->flags = DIR_INHERITANCE; + if (mode & S_IXOTH) + grants |= DIR_EXEC; + if (mode & S_IWOTH) + grants |= DIR_WRITE; + if (mode & S_IROTH) + grants |= DIR_READ; + } else { + pgace->flags = FILE_INHERITANCE; + if (mode & S_IXOTH) + grants |= FILE_EXEC; + if (mode & S_IWOTH) + grants |= FILE_WRITE; + if (mode & S_IROTH) + grants |= FILE_READ; + } + pgace->size = cpu_to_le16(wsidsz + 8); + pgace->mask = grants; + memcpy((char*)&pgace->sid, worldsid, wsidsz); + pos += wsidsz + 8; + acecnt++; - /* an ACE for administrators */ - /* always full access */ + /* an ACE for administrators */ + /* always full access */ - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - if (isdir) - pgace->flags = DIR_INHERITANCE; - else - pgace->flags = FILE_INHERITANCE; - pgace->size = cpu_to_le16(asidsz + 8); - grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; - pgace->mask = grants; - memcpy((char*)&pgace->sid, adminsid, asidsz); - pos += asidsz + 8; - acecnt++; + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + if (isdir) + pgace->flags = DIR_INHERITANCE; + else + pgace->flags = FILE_INHERITANCE; + pgace->size = cpu_to_le16(asidsz + 8); + grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; + pgace->mask = grants; + memcpy((char*)&pgace->sid, adminsid, asidsz); + pos += asidsz + 8; + acecnt++; - /* an ACE for system (needed ?) */ - /* always full access */ + /* an ACE for system (needed ?) */ + /* always full access */ - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - if (isdir) - pgace->flags = DIR_INHERITANCE; - else - pgace->flags = FILE_INHERITANCE; - pgace->size = cpu_to_le16(ssidsz + 8); - grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; - pgace->mask = grants; - memcpy((char*)&pgace->sid, systemsid, ssidsz); - pos += ssidsz + 8; - acecnt++; + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + if (isdir) + pgace->flags = DIR_INHERITANCE; + else + pgace->flags = FILE_INHERITANCE; + pgace->size = cpu_to_le16(ssidsz + 8); + grants = OWNER_RIGHTS | FILE_READ | FILE_WRITE | FILE_EXEC; + pgace->mask = grants; + memcpy((char*)&pgace->sid, systemsid, ssidsz); + pos += ssidsz + 8; + acecnt++; - /* a null ACE to hold special flags */ - /* using the same representation as cygwin */ + /* a null ACE to hold special flags */ + /* using the same representation as cygwin */ - if (mode & (S_ISVTX | S_ISGID | S_ISUID)) { - nsidsz = ntfs_sid_size(nullsid); - pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; - pgace->type = ACCESS_ALLOWED_ACE_TYPE; - pgace->flags = NO_PROPAGATE_INHERIT_ACE; - pgace->size = cpu_to_le16(nsidsz + 8); - grants = const_cpu_to_le32(0); - if (mode & S_ISUID) - grants |= FILE_APPEND_DATA; - if (mode & S_ISGID) - grants |= FILE_WRITE_DATA; - if (mode & S_ISVTX) - grants |= FILE_READ_DATA; - pgace->mask = grants; - memcpy((char*)&pgace->sid, nullsid, nsidsz); - pos += nsidsz + 8; - acecnt++; - } + if (mode & (S_ISVTX | S_ISGID | S_ISUID)) { + nsidsz = ntfs_sid_size(nullsid); + pgace = (ACCESS_ALLOWED_ACE*)&secattr[offs + pos]; + pgace->type = ACCESS_ALLOWED_ACE_TYPE; + pgace->flags = NO_PROPAGATE_INHERIT_ACE; + pgace->size = cpu_to_le16(nsidsz + 8); + grants = const_cpu_to_le32(0); + if (mode & S_ISUID) + grants |= FILE_APPEND_DATA; + if (mode & S_ISGID) + grants |= FILE_WRITE_DATA; + if (mode & S_ISVTX) + grants |= FILE_READ_DATA; + pgace->mask = grants; + memcpy((char*)&pgace->sid, nullsid, nsidsz); + pos += nsidsz + 8; + acecnt++; + } - /* fix ACL header */ - pacl->size = cpu_to_le16(pos); - pacl->ace_count = cpu_to_le16(acecnt); - return (pos); + /* fix ACL header */ + pacl->size = cpu_to_le16(pos); + pacl->ace_count = cpu_to_le16(acecnt); + return (pos); } #if POSIXACLS @@ -2491,96 +2519,97 @@ static int buildacls(char *secattr, int offs, mode_t mode, int isdir, */ char *ntfs_build_descr_posix(struct MAPPING* const mapping[], - struct POSIX_SECURITY *pxdesc, - int isdir, const SID *usid, const SID *gsid) { - int newattrsz; - SECURITY_DESCRIPTOR_RELATIVE *pnhead; - char *newattr; - int aclsz; - int usidsz; - int gsidsz; - int wsidsz; - int asidsz; - int ssidsz; - int k; + struct POSIX_SECURITY *pxdesc, + int isdir, const SID *usid, const SID *gsid) +{ + int newattrsz; + SECURITY_DESCRIPTOR_RELATIVE *pnhead; + char *newattr; + int aclsz; + int usidsz; + int gsidsz; + int wsidsz; + int asidsz; + int ssidsz; + int k; - usidsz = ntfs_sid_size(usid); - gsidsz = ntfs_sid_size(gsid); - wsidsz = ntfs_sid_size(worldsid); - asidsz = ntfs_sid_size(adminsid); - ssidsz = ntfs_sid_size(systemsid); + usidsz = ntfs_sid_size(usid); + gsidsz = ntfs_sid_size(gsid); + wsidsz = ntfs_sid_size(worldsid); + asidsz = ntfs_sid_size(adminsid); + ssidsz = ntfs_sid_size(systemsid); - /* allocate enough space for the new security attribute */ - newattrsz = sizeof(SECURITY_DESCRIPTOR_RELATIVE) /* header */ - + usidsz + gsidsz /* usid and gsid */ - + sizeof(ACL) /* acl header */ - + 2*(8 + usidsz) /* two possible ACE for user */ - + 3*(8 + gsidsz) /* three possible ACE for group and mask */ - + 8 + wsidsz /* one ACE for world */ - + 8 + asidsz /* one ACE for admin */ - + 8 + ssidsz; /* one ACE for system */ - if (isdir) /* a world denial for directories */ - newattrsz += 8 + wsidsz; - if (pxdesc->mode & 07000) /* a NULL ACE for special modes */ - newattrsz += 8 + ntfs_sid_size(nullsid); - /* account for non-owning users and groups */ - for (k=0; kacccnt; k++) { - if ((pxdesc->acl.ace[k].tag == POSIX_ACL_USER) - || (pxdesc->acl.ace[k].tag == POSIX_ACL_GROUP)) - newattrsz += 3*40; /* fixme : maximum size */ - } - /* account for default ACE's */ - newattrsz += 2*40*pxdesc->defcnt; /* fixme : maximum size */ - newattr = (char*)ntfs_malloc(newattrsz); - if (newattr) { - /* build the main header part */ - pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)newattr; - pnhead->revision = SECURITY_DESCRIPTOR_REVISION; - pnhead->alignment = 0; - /* - * The flag SE_DACL_PROTECTED prevents the ACL - * to be changed in an inheritance after creation - */ - pnhead->control = SE_DACL_PRESENT | SE_DACL_PROTECTED - | SE_SELF_RELATIVE; - /* - * Windows prefers ACL first, do the same to - * get the same hash value and avoid duplication - */ - /* build permissions */ - aclsz = buildacls_posix(mapping,newattr, - sizeof(SECURITY_DESCRIPTOR_RELATIVE), - pxdesc, isdir, usid, gsid); - if (aclsz && ((int)(sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz + usidsz + gsidsz) <= newattrsz)) { - /* append usid and gsid */ - memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz], usid, usidsz); - memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz + usidsz], gsid, gsidsz); - /* positions of ACL, USID and GSID into header */ - pnhead->owner = - cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz); - pnhead->group = - cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz + usidsz); - pnhead->sacl = const_cpu_to_le32(0); - pnhead->dacl = - const_cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE)); - } else { - /* ACL failure (errno set) or overflow */ - free(newattr); - newattr = (char*)NULL; - if (aclsz) { - /* hope error was detected before overflowing */ - ntfs_log_error("Security descriptor is longer than expected\n"); - errno = EIO; - } - } - } else - errno = ENOMEM; - return (newattr); + /* allocate enough space for the new security attribute */ + newattrsz = sizeof(SECURITY_DESCRIPTOR_RELATIVE) /* header */ + + usidsz + gsidsz /* usid and gsid */ + + sizeof(ACL) /* acl header */ + + 2*(8 + usidsz) /* two possible ACE for user */ + + 3*(8 + gsidsz) /* three possible ACE for group and mask */ + + 8 + wsidsz /* one ACE for world */ + + 8 + asidsz /* one ACE for admin */ + + 8 + ssidsz; /* one ACE for system */ + if (isdir) /* a world denial for directories */ + newattrsz += 8 + wsidsz; + if (pxdesc->mode & 07000) /* a NULL ACE for special modes */ + newattrsz += 8 + ntfs_sid_size(nullsid); + /* account for non-owning users and groups */ + for (k=0; kacccnt; k++) { + if ((pxdesc->acl.ace[k].tag == POSIX_ACL_USER) + || (pxdesc->acl.ace[k].tag == POSIX_ACL_GROUP)) + newattrsz += 3*40; /* fixme : maximum size */ + } + /* account for default ACE's */ + newattrsz += 2*40*pxdesc->defcnt; /* fixme : maximum size */ + newattr = (char*)ntfs_malloc(newattrsz); + if (newattr) { + /* build the main header part */ + pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)newattr; + pnhead->revision = SECURITY_DESCRIPTOR_REVISION; + pnhead->alignment = 0; + /* + * The flag SE_DACL_PROTECTED prevents the ACL + * to be changed in an inheritance after creation + */ + pnhead->control = SE_DACL_PRESENT | SE_DACL_PROTECTED + | SE_SELF_RELATIVE; + /* + * Windows prefers ACL first, do the same to + * get the same hash value and avoid duplication + */ + /* build permissions */ + aclsz = buildacls_posix(mapping,newattr, + sizeof(SECURITY_DESCRIPTOR_RELATIVE), + pxdesc, isdir, usid, gsid); + if (aclsz && ((int)(sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz + usidsz + gsidsz) <= newattrsz)) { + /* append usid and gsid */ + memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz], usid, usidsz); + memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz + usidsz], gsid, gsidsz); + /* positions of ACL, USID and GSID into header */ + pnhead->owner = + cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz); + pnhead->group = + cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz + usidsz); + pnhead->sacl = const_cpu_to_le32(0); + pnhead->dacl = + const_cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE)); + } else { + /* ACL failure (errno set) or overflow */ + free(newattr); + newattr = (char*)NULL; + if (aclsz) { + /* hope error was detected before overflowing */ + ntfs_log_error("Security descriptor is longer than expected\n"); + errno = EIO; + } + } + } else + errno = ENOMEM; + return (newattr); } #endif /* POSIXACLS */ @@ -2591,83 +2620,84 @@ char *ntfs_build_descr_posix(struct MAPPING* const mapping[], */ char *ntfs_build_descr(mode_t mode, - int isdir, const SID * usid, const SID * gsid) { - int newattrsz; - SECURITY_DESCRIPTOR_RELATIVE *pnhead; - char *newattr; - int aclsz; - int usidsz; - int gsidsz; - int wsidsz; - int asidsz; - int ssidsz; + int isdir, const SID * usid, const SID * gsid) +{ + int newattrsz; + SECURITY_DESCRIPTOR_RELATIVE *pnhead; + char *newattr; + int aclsz; + int usidsz; + int gsidsz; + int wsidsz; + int asidsz; + int ssidsz; - usidsz = ntfs_sid_size(usid); - gsidsz = ntfs_sid_size(gsid); - wsidsz = ntfs_sid_size(worldsid); - asidsz = ntfs_sid_size(adminsid); - ssidsz = ntfs_sid_size(systemsid); + usidsz = ntfs_sid_size(usid); + gsidsz = ntfs_sid_size(gsid); + wsidsz = ntfs_sid_size(worldsid); + asidsz = ntfs_sid_size(adminsid); + ssidsz = ntfs_sid_size(systemsid); - /* allocate enough space for the new security attribute */ - newattrsz = sizeof(SECURITY_DESCRIPTOR_RELATIVE) /* header */ - + usidsz + gsidsz /* usid and gsid */ - + sizeof(ACL) /* acl header */ - + 2*(8 + usidsz) /* two possible ACE for user */ - + 2*(8 + gsidsz) /* two possible ACE for group */ - + 8 + wsidsz /* one ACE for world */ - + 8 + asidsz /* one ACE for admin */ - + 8 + ssidsz; /* one ACE for system */ - if (isdir) /* a world denial for directories */ - newattrsz += 8 + wsidsz; - if (mode & 07000) /* a NULL ACE for special modes */ - newattrsz += 8 + ntfs_sid_size(nullsid); - newattr = (char*)ntfs_malloc(newattrsz); - if (newattr) { - /* build the main header part */ - pnhead = (SECURITY_DESCRIPTOR_RELATIVE*) newattr; - pnhead->revision = SECURITY_DESCRIPTOR_REVISION; - pnhead->alignment = 0; - /* - * The flag SE_DACL_PROTECTED prevents the ACL - * to be changed in an inheritance after creation - */ - pnhead->control = SE_DACL_PRESENT | SE_DACL_PROTECTED - | SE_SELF_RELATIVE; - /* - * Windows prefers ACL first, do the same to - * get the same hash value and avoid duplication - */ - /* build permissions */ - aclsz = buildacls(newattr, - sizeof(SECURITY_DESCRIPTOR_RELATIVE), - mode, isdir, usid, gsid); - if (((int)sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz + usidsz + gsidsz) <= newattrsz) { - /* append usid and gsid */ - memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz], usid, usidsz); - memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz + usidsz], gsid, gsidsz); - /* positions of ACL, USID and GSID into header */ - pnhead->owner = - cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz); - pnhead->group = - cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) - + aclsz + usidsz); - pnhead->sacl = const_cpu_to_le32(0); - pnhead->dacl = - const_cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE)); - } else { - /* hope error was detected before overflowing */ - free(newattr); - newattr = (char*)NULL; - ntfs_log_error("Security descriptor is longer than expected\n"); - errno = EIO; - } - } else - errno = ENOMEM; - return (newattr); + /* allocate enough space for the new security attribute */ + newattrsz = sizeof(SECURITY_DESCRIPTOR_RELATIVE) /* header */ + + usidsz + gsidsz /* usid and gsid */ + + sizeof(ACL) /* acl header */ + + 2*(8 + usidsz) /* two possible ACE for user */ + + 2*(8 + gsidsz) /* two possible ACE for group */ + + 8 + wsidsz /* one ACE for world */ + + 8 + asidsz /* one ACE for admin */ + + 8 + ssidsz; /* one ACE for system */ + if (isdir) /* a world denial for directories */ + newattrsz += 8 + wsidsz; + if (mode & 07000) /* a NULL ACE for special modes */ + newattrsz += 8 + ntfs_sid_size(nullsid); + newattr = (char*)ntfs_malloc(newattrsz); + if (newattr) { + /* build the main header part */ + pnhead = (SECURITY_DESCRIPTOR_RELATIVE*) newattr; + pnhead->revision = SECURITY_DESCRIPTOR_REVISION; + pnhead->alignment = 0; + /* + * The flag SE_DACL_PROTECTED prevents the ACL + * to be changed in an inheritance after creation + */ + pnhead->control = SE_DACL_PRESENT | SE_DACL_PROTECTED + | SE_SELF_RELATIVE; + /* + * Windows prefers ACL first, do the same to + * get the same hash value and avoid duplication + */ + /* build permissions */ + aclsz = buildacls(newattr, + sizeof(SECURITY_DESCRIPTOR_RELATIVE), + mode, isdir, usid, gsid); + if (((int)sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz + usidsz + gsidsz) <= newattrsz) { + /* append usid and gsid */ + memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz], usid, usidsz); + memcpy(&newattr[sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz + usidsz], gsid, gsidsz); + /* positions of ACL, USID and GSID into header */ + pnhead->owner = + cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz); + pnhead->group = + cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE) + + aclsz + usidsz); + pnhead->sacl = const_cpu_to_le32(0); + pnhead->dacl = + const_cpu_to_le32(sizeof(SECURITY_DESCRIPTOR_RELATIVE)); + } else { + /* hope error was detected before overflowing */ + free(newattr); + newattr = (char*)NULL; + ntfs_log_error("Security descriptor is longer than expected\n"); + errno = EIO; + } + } else + errno = ENOMEM; + return (newattr); } /* @@ -2676,94 +2706,94 @@ char *ntfs_build_descr(mode_t mode, */ static int merge_permissions(BOOL isdir, - le32 owner, le32 group, le32 world, le32 special) + le32 owner, le32 group, le32 world, le32 special) { - int perm; + int perm; - perm = 0; - /* build owner permission */ - if (owner) { - if (isdir) { - /* exec if any of list, traverse */ - if (owner & DIR_GEXEC) - perm |= S_IXUSR; - /* write if any of addfile, adddir, delchild */ - if (owner & DIR_GWRITE) - perm |= S_IWUSR; - /* read if any of list */ - if (owner & DIR_GREAD) - perm |= S_IRUSR; - } else { - /* exec if execute or generic execute */ - if (owner & FILE_GEXEC) - perm |= S_IXUSR; - /* write if any of writedata or generic write */ - if (owner & FILE_GWRITE) - perm |= S_IWUSR; - /* read if any of readdata or generic read */ - if (owner & FILE_GREAD) - perm |= S_IRUSR; - } - } - /* build group permission */ - if (group) { - if (isdir) { - /* exec if any of list, traverse */ - if (group & DIR_GEXEC) - perm |= S_IXGRP; - /* write if any of addfile, adddir, delchild */ - if (group & DIR_GWRITE) - perm |= S_IWGRP; - /* read if any of list */ - if (group & DIR_GREAD) - perm |= S_IRGRP; - } else { - /* exec if execute */ - if (group & FILE_GEXEC) - perm |= S_IXGRP; - /* write if any of writedata, appenddata */ - if (group & FILE_GWRITE) - perm |= S_IWGRP; - /* read if any of readdata */ - if (group & FILE_GREAD) - perm |= S_IRGRP; - } - } - /* build world permission */ - if (world) { - if (isdir) { - /* exec if any of list, traverse */ - if (world & DIR_GEXEC) - perm |= S_IXOTH; - /* write if any of addfile, adddir, delchild */ - if (world & DIR_GWRITE) - perm |= S_IWOTH; - /* read if any of list */ - if (world & DIR_GREAD) - perm |= S_IROTH; - } else { - /* exec if execute */ - if (world & FILE_GEXEC) - perm |= S_IXOTH; - /* write if any of writedata, appenddata */ - if (world & FILE_GWRITE) - perm |= S_IWOTH; - /* read if any of readdata */ - if (world & FILE_GREAD) - perm |= S_IROTH; - } - } - /* build special permission flags */ - if (special) { - if (special & FILE_APPEND_DATA) - perm |= S_ISUID; - if (special & FILE_WRITE_DATA) - perm |= S_ISGID; - if (special & FILE_READ_DATA) - perm |= S_ISVTX; - } - return (perm); + perm = 0; + /* build owner permission */ + if (owner) { + if (isdir) { + /* exec if any of list, traverse */ + if (owner & DIR_GEXEC) + perm |= S_IXUSR; + /* write if any of addfile, adddir, delchild */ + if (owner & DIR_GWRITE) + perm |= S_IWUSR; + /* read if any of list */ + if (owner & DIR_GREAD) + perm |= S_IRUSR; + } else { + /* exec if execute or generic execute */ + if (owner & FILE_GEXEC) + perm |= S_IXUSR; + /* write if any of writedata or generic write */ + if (owner & FILE_GWRITE) + perm |= S_IWUSR; + /* read if any of readdata or generic read */ + if (owner & FILE_GREAD) + perm |= S_IRUSR; + } + } + /* build group permission */ + if (group) { + if (isdir) { + /* exec if any of list, traverse */ + if (group & DIR_GEXEC) + perm |= S_IXGRP; + /* write if any of addfile, adddir, delchild */ + if (group & DIR_GWRITE) + perm |= S_IWGRP; + /* read if any of list */ + if (group & DIR_GREAD) + perm |= S_IRGRP; + } else { + /* exec if execute */ + if (group & FILE_GEXEC) + perm |= S_IXGRP; + /* write if any of writedata, appenddata */ + if (group & FILE_GWRITE) + perm |= S_IWGRP; + /* read if any of readdata */ + if (group & FILE_GREAD) + perm |= S_IRGRP; + } + } + /* build world permission */ + if (world) { + if (isdir) { + /* exec if any of list, traverse */ + if (world & DIR_GEXEC) + perm |= S_IXOTH; + /* write if any of addfile, adddir, delchild */ + if (world & DIR_GWRITE) + perm |= S_IWOTH; + /* read if any of list */ + if (world & DIR_GREAD) + perm |= S_IROTH; + } else { + /* exec if execute */ + if (world & FILE_GEXEC) + perm |= S_IXOTH; + /* write if any of writedata, appenddata */ + if (world & FILE_GWRITE) + perm |= S_IWOTH; + /* read if any of readdata */ + if (world & FILE_GREAD) + perm |= S_IROTH; + } + } + /* build special permission flags */ + if (special) { + if (special & FILE_APPEND_DATA) + perm |= S_ISUID; + if (special & FILE_WRITE_DATA) + perm |= S_ISGID; + if (special & FILE_READ_DATA) + perm |= S_ISVTX; + } + return (perm); } #if POSIXACLS @@ -2775,151 +2805,152 @@ static int merge_permissions(BOOL isdir, */ static int norm_std_permissions_posix(struct POSIX_SECURITY *posix_desc, - BOOL groupowns, int start, int count, int target) { - int j,k; - s32 id; - u16 tag; - u16 tagsset; - struct POSIX_ACE *pxace; - mode_t grantgrps; - mode_t grantwrld; - mode_t denywrld; - mode_t allow; - mode_t deny; - mode_t perms; - mode_t mode; + BOOL groupowns, int start, int count, int target) +{ + int j,k; + s32 id; + u16 tag; + u16 tagsset; + struct POSIX_ACE *pxace; + mode_t grantgrps; + mode_t grantwrld; + mode_t denywrld; + mode_t allow; + mode_t deny; + mode_t perms; + mode_t mode; - mode = 0; - tagsset = 0; - /* - * Determine what is granted to some group or world - * Also get denials to world which are meant to prevent - * execution flags to be inherited by plain files - */ - pxace = posix_desc->acl.ace; - grantgrps = 0; - grantwrld = 0; - denywrld = 0; - for (j=start; j<(start + count); j++) { - if (pxace[j].perms & POSIX_PERM_DENIAL) { - /* deny world exec unless for default */ - if ((pxace[j].tag == POSIX_ACL_OTHER) - && !start) - denywrld = pxace[j].perms; - } else { - switch (pxace[j].tag) { - case POSIX_ACL_GROUP_OBJ : - grantgrps |= pxace[j].perms; - break; - case POSIX_ACL_GROUP : - if (pxace[j].id) - grantgrps |= pxace[j].perms; - break; - case POSIX_ACL_OTHER : - grantwrld = pxace[j].perms; - break; - default : - break; - } - } - } - /* - * Collect groups of ACEs related to the same id - * and determine what is granted and what is denied. - * It is important the ACEs have been sorted - */ - j = start; - k = target; - while (j < (start + count)) { - tag = pxace[j].tag; - id = pxace[j].id; - if (pxace[j].perms & POSIX_PERM_DENIAL) { - deny = pxace[j].perms | denywrld; - allow = 0; - } else { - deny = denywrld; - allow = pxace[j].perms; - } - j++; - while ((j < (start + count)) - && (pxace[j].tag == tag) - && (pxace[j].id == id)) { - if (pxace[j].perms & POSIX_PERM_DENIAL) - deny |= pxace[j].perms; - else - allow |= pxace[j].perms; - j++; - } - /* - * Build the permissions equivalent to grants and denials - */ - if (groupowns) { - if (tag == POSIX_ACL_MASK) - perms = ~deny; - else - perms = allow & ~deny; - } else - switch (tag) { - case POSIX_ACL_USER_OBJ : - perms = (allow | grantgrps | grantwrld) & ~deny; - break; - case POSIX_ACL_USER : - if (id) - perms = (allow | grantgrps | grantwrld) - & ~deny; - else - perms = allow; - break; - case POSIX_ACL_GROUP_OBJ : - perms = (allow | grantwrld) & ~deny; - break; - case POSIX_ACL_GROUP : - if (id) - perms = (allow | grantwrld) & ~deny; - else - perms = allow; - break; - case POSIX_ACL_MASK : - perms = ~deny; - break; - default : - perms = allow & ~deny; - break; - } - /* - * Store into a Posix ACE - */ - if (tag != POSIX_ACL_SPECIAL) { - pxace[k].tag = tag; - pxace[k].id = id; - pxace[k].perms = perms - & (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X); - tagsset |= tag; - k++; - } - switch (tag) { - case POSIX_ACL_USER_OBJ : - mode |= ((perms & 7) << 6); - break; - case POSIX_ACL_GROUP_OBJ : - case POSIX_ACL_MASK : - mode = (mode & 07707) | ((perms & 7) << 3); - break; - case POSIX_ACL_OTHER : - mode |= perms & 7; - break; - case POSIX_ACL_SPECIAL : - mode |= (perms & (S_ISVTX | S_ISUID | S_ISGID)); - break; - default : - break; - } - } - if (!start) { /* not satisfactory */ - posix_desc->mode = mode; - posix_desc->tagsset = tagsset; - } - return (k - target); + mode = 0; + tagsset = 0; + /* + * Determine what is granted to some group or world + * Also get denials to world which are meant to prevent + * execution flags to be inherited by plain files + */ + pxace = posix_desc->acl.ace; + grantgrps = 0; + grantwrld = 0; + denywrld = 0; + for (j=start; j<(start + count); j++) { + if (pxace[j].perms & POSIX_PERM_DENIAL) { + /* deny world exec unless for default */ + if ((pxace[j].tag == POSIX_ACL_OTHER) + && !start) + denywrld = pxace[j].perms; + } else { + switch (pxace[j].tag) { + case POSIX_ACL_GROUP_OBJ : + grantgrps |= pxace[j].perms; + break; + case POSIX_ACL_GROUP : + if (pxace[j].id) + grantgrps |= pxace[j].perms; + break; + case POSIX_ACL_OTHER : + grantwrld = pxace[j].perms; + break; + default : + break; + } + } + } + /* + * Collect groups of ACEs related to the same id + * and determine what is granted and what is denied. + * It is important the ACEs have been sorted + */ + j = start; + k = target; + while (j < (start + count)) { + tag = pxace[j].tag; + id = pxace[j].id; + if (pxace[j].perms & POSIX_PERM_DENIAL) { + deny = pxace[j].perms | denywrld; + allow = 0; + } else { + deny = denywrld; + allow = pxace[j].perms; + } + j++; + while ((j < (start + count)) + && (pxace[j].tag == tag) + && (pxace[j].id == id)) { + if (pxace[j].perms & POSIX_PERM_DENIAL) + deny |= pxace[j].perms; + else + allow |= pxace[j].perms; + j++; + } + /* + * Build the permissions equivalent to grants and denials + */ + if (groupowns) { + if (tag == POSIX_ACL_MASK) + perms = ~deny; + else + perms = allow & ~deny; + } else + switch (tag) { + case POSIX_ACL_USER_OBJ : + perms = (allow | grantgrps | grantwrld) & ~deny; + break; + case POSIX_ACL_USER : + if (id) + perms = (allow | grantgrps | grantwrld) + & ~deny; + else + perms = allow; + break; + case POSIX_ACL_GROUP_OBJ : + perms = (allow | grantwrld) & ~deny; + break; + case POSIX_ACL_GROUP : + if (id) + perms = (allow | grantwrld) & ~deny; + else + perms = allow; + break; + case POSIX_ACL_MASK : + perms = ~deny; + break; + default : + perms = allow & ~deny; + break; + } + /* + * Store into a Posix ACE + */ + if (tag != POSIX_ACL_SPECIAL) { + pxace[k].tag = tag; + pxace[k].id = id; + pxace[k].perms = perms + & (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X); + tagsset |= tag; + k++; + } + switch (tag) { + case POSIX_ACL_USER_OBJ : + mode |= ((perms & 7) << 6); + break; + case POSIX_ACL_GROUP_OBJ : + case POSIX_ACL_MASK : + mode = (mode & 07707) | ((perms & 7) << 3); + break; + case POSIX_ACL_OTHER : + mode |= perms & 7; + break; + case POSIX_ACL_SPECIAL : + mode |= (perms & (S_ISVTX | S_ISUID | S_ISGID)); + break; + default : + break; + } + } + if (!start) { /* not satisfactory */ + posix_desc->mode = mode; + posix_desc->tagsset = tagsset; + } + return (k - target); } #endif /* POSIXACLS */ @@ -2930,82 +2961,83 @@ static int norm_std_permissions_posix(struct POSIX_SECURITY *posix_desc, */ static int build_std_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const ACL *pacl; - const ACCESS_ALLOWED_ACE *pace; - int offdacl; - int offace; - int acecnt; - int nace; - BOOL noown; - le32 special; - le32 allowown, allowgrp, allowall; - le32 denyown, denygrp, denyall; + const SID *usid, const SID *gsid, BOOL isdir) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const ACL *pacl; + const ACCESS_ALLOWED_ACE *pace; + int offdacl; + int offace; + int acecnt; + int nace; + BOOL noown; + le32 special; + le32 allowown, allowgrp, allowall; + le32 denyown, denygrp, denyall; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - offdacl = le32_to_cpu(phead->dacl); - pacl = (const ACL*)&securattr[offdacl]; - special = const_cpu_to_le32(0); - allowown = allowgrp = allowall = const_cpu_to_le32(0); - denyown = denygrp = denyall = const_cpu_to_le32(0); - noown = TRUE; - if (offdacl) { - acecnt = le16_to_cpu(pacl->ace_count); - offace = offdacl + sizeof(ACL); - } else - acecnt = 0; - for (nace = 0; nace < acecnt; nace++) { - pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; - if (!(pace->flags & INHERIT_ONLY_ACE)) { - if (ntfs_same_sid(usid, &pace->sid) - || ntfs_same_sid(ownersid, &pace->sid)) { - noown = FALSE; - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - allowown |= pace->mask; - else if (pace->type == ACCESS_DENIED_ACE_TYPE) - denyown |= pace->mask; - } else - if (ntfs_same_sid(gsid, &pace->sid) - && !(pace->mask & WRITE_OWNER)) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - allowgrp |= pace->mask; - else if (pace->type == ACCESS_DENIED_ACE_TYPE) - denygrp |= pace->mask; - } else - if (is_world_sid((const SID*)&pace->sid)) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - allowall |= pace->mask; - else - if (pace->type == ACCESS_DENIED_ACE_TYPE) - denyall |= pace->mask; - } else - if ((ntfs_same_sid((const SID*)&pace->sid,nullsid)) - && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) - special |= pace->mask; - } - offace += le16_to_cpu(pace->size); - } - /* - * No indication about owner's rights : grant basic rights - * This happens for files created by Windows in directories - * created by Linux and owned by root, because Windows - * merges the admin ACEs - */ - if (noown) - allowown = (FILE_READ_DATA | FILE_WRITE_DATA | FILE_EXECUTE); - /* - * Add to owner rights granted to group or world - * unless denied personaly, and add to group rights - * granted to world unless denied specifically - */ - allowown |= (allowgrp | allowall); - allowgrp |= allowall; - return (merge_permissions(isdir, - allowown & ~(denyown | denyall), - allowgrp & ~(denygrp | denyall), - allowall & ~denyall, - special)); + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + offdacl = le32_to_cpu(phead->dacl); + pacl = (const ACL*)&securattr[offdacl]; + special = const_cpu_to_le32(0); + allowown = allowgrp = allowall = const_cpu_to_le32(0); + denyown = denygrp = denyall = const_cpu_to_le32(0); + noown = TRUE; + if (offdacl) { + acecnt = le16_to_cpu(pacl->ace_count); + offace = offdacl + sizeof(ACL); + } else + acecnt = 0; + for (nace = 0; nace < acecnt; nace++) { + pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; + if (!(pace->flags & INHERIT_ONLY_ACE)) { + if (ntfs_same_sid(usid, &pace->sid) + || ntfs_same_sid(ownersid, &pace->sid)) { + noown = FALSE; + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + allowown |= pace->mask; + else if (pace->type == ACCESS_DENIED_ACE_TYPE) + denyown |= pace->mask; + } else + if (ntfs_same_sid(gsid, &pace->sid) + && !(pace->mask & WRITE_OWNER)) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + allowgrp |= pace->mask; + else if (pace->type == ACCESS_DENIED_ACE_TYPE) + denygrp |= pace->mask; + } else + if (is_world_sid((const SID*)&pace->sid)) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + allowall |= pace->mask; + else + if (pace->type == ACCESS_DENIED_ACE_TYPE) + denyall |= pace->mask; + } else + if ((ntfs_same_sid((const SID*)&pace->sid,nullsid)) + && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) + special |= pace->mask; + } + offace += le16_to_cpu(pace->size); + } + /* + * No indication about owner's rights : grant basic rights + * This happens for files created by Windows in directories + * created by Linux and owned by root, because Windows + * merges the admin ACEs + */ + if (noown) + allowown = (FILE_READ_DATA | FILE_WRITE_DATA | FILE_EXECUTE); + /* + * Add to owner rights granted to group or world + * unless denied personaly, and add to group rights + * granted to world unless denied specifically + */ + allowown |= (allowgrp | allowall); + allowgrp |= allowall; + return (merge_permissions(isdir, + allowown & ~(denyown | denyall), + allowgrp & ~(denygrp | denyall), + allowall & ~denyall, + special)); } /* @@ -3015,67 +3047,68 @@ static int build_std_permissions(const char *securattr, */ static int build_owngrp_permissions(const char *securattr, - const SID *usid, BOOL isdir) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const ACL *pacl; - const ACCESS_ALLOWED_ACE *pace; - int offdacl; - int offace; - int acecnt; - int nace; - le32 special; - BOOL grppresent; - le32 allowown, allowgrp, allowall; - le32 denyown, denygrp, denyall; + const SID *usid, BOOL isdir) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const ACL *pacl; + const ACCESS_ALLOWED_ACE *pace; + int offdacl; + int offace; + int acecnt; + int nace; + le32 special; + BOOL grppresent; + le32 allowown, allowgrp, allowall; + le32 denyown, denygrp, denyall; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - offdacl = le32_to_cpu(phead->dacl); - pacl = (const ACL*)&securattr[offdacl]; - special = const_cpu_to_le32(0); - allowown = allowgrp = allowall = const_cpu_to_le32(0); - denyown = denygrp = denyall = const_cpu_to_le32(0); - grppresent = FALSE; - if (offdacl) { - acecnt = le16_to_cpu(pacl->ace_count); - offace = offdacl + sizeof(ACL); - } else - acecnt = 0; - for (nace = 0; nace < acecnt; nace++) { - pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; - if (!(pace->flags & INHERIT_ONLY_ACE)) { - if ((ntfs_same_sid(usid, &pace->sid) - || ntfs_same_sid(ownersid, &pace->sid)) - && (pace->mask & WRITE_OWNER)) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - allowown |= pace->mask; - } else - if (ntfs_same_sid(usid, &pace->sid) - && (!(pace->mask & WRITE_OWNER))) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) { - allowgrp |= pace->mask; - grppresent = TRUE; - } - } else - if (is_world_sid((const SID*)&pace->sid)) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - allowall |= pace->mask; - else - if (pace->type == ACCESS_DENIED_ACE_TYPE) - denyall |= pace->mask; - } else - if ((ntfs_same_sid((const SID*)&pace->sid,nullsid)) - && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) - special |= pace->mask; - } - offace += le16_to_cpu(pace->size); - } - if (!grppresent) - allowgrp = allowall; - return (merge_permissions(isdir, - allowown & ~(denyown | denyall), - allowgrp & ~(denygrp | denyall), - allowall & ~denyall, - special)); + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + offdacl = le32_to_cpu(phead->dacl); + pacl = (const ACL*)&securattr[offdacl]; + special = const_cpu_to_le32(0); + allowown = allowgrp = allowall = const_cpu_to_le32(0); + denyown = denygrp = denyall = const_cpu_to_le32(0); + grppresent = FALSE; + if (offdacl) { + acecnt = le16_to_cpu(pacl->ace_count); + offace = offdacl + sizeof(ACL); + } else + acecnt = 0; + for (nace = 0; nace < acecnt; nace++) { + pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; + if (!(pace->flags & INHERIT_ONLY_ACE)) { + if ((ntfs_same_sid(usid, &pace->sid) + || ntfs_same_sid(ownersid, &pace->sid)) + && (pace->mask & WRITE_OWNER)) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + allowown |= pace->mask; + } else + if (ntfs_same_sid(usid, &pace->sid) + && (!(pace->mask & WRITE_OWNER))) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) { + allowgrp |= pace->mask; + grppresent = TRUE; + } + } else + if (is_world_sid((const SID*)&pace->sid)) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + allowall |= pace->mask; + else + if (pace->type == ACCESS_DENIED_ACE_TYPE) + denyall |= pace->mask; + } else + if ((ntfs_same_sid((const SID*)&pace->sid,nullsid)) + && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) + special |= pace->mask; + } + offace += le16_to_cpu(pace->size); + } + if (!grppresent) + allowgrp = allowall; + return (merge_permissions(isdir, + allowown & ~(denyown | denyall), + allowgrp & ~(denygrp | denyall), + allowall & ~denyall, + special)); } #if POSIXACLS @@ -3087,105 +3120,106 @@ static int build_owngrp_permissions(const char *securattr, */ static int norm_ownadmin_permissions_posix(struct POSIX_SECURITY *posix_desc, - int start, int count, int target) { - int j,k; - s32 id; - u16 tag; - u16 tagsset; - struct POSIX_ACE *pxace; - int acccnt; - mode_t denywrld; - mode_t allow; - mode_t deny; - mode_t perms; - mode_t mode; + int start, int count, int target) +{ + int j,k; + s32 id; + u16 tag; + u16 tagsset; + struct POSIX_ACE *pxace; + int acccnt; + mode_t denywrld; + mode_t allow; + mode_t deny; + mode_t perms; + mode_t mode; - mode = 0; - pxace = posix_desc->acl.ace; - acccnt = posix_desc->acccnt; - tagsset = 0; - denywrld = 0; - /* - * Get denials to world which are meant to prevent - * execution flags to be inherited by plain files - */ - for (j=start; j<(start + count); j++) { - if (pxace[j].perms & POSIX_PERM_DENIAL) { - /* deny world exec not for default */ - if ((pxace[j].tag == POSIX_ACL_OTHER) - && !start) - denywrld = pxace[j].perms; - } - } - /* - * Collect groups of ACEs related to the same id - * and determine what is granted (denials are ignored) - * It is important the ACEs have been sorted - */ - j = start; - k = target; - deny = 0; - while (j < (start + count)) { - allow = 0; - tag = pxace[j].tag; - id = pxace[j].id; - if (tag == POSIX_ACL_MASK) { - deny = pxace[j].perms; - j++; - while ((j < (start + count)) - && (pxace[j].tag == POSIX_ACL_MASK)) - j++; - } else { - if (!(pxace[j].perms & POSIX_PERM_DENIAL)) - allow = pxace[j].perms; - j++; - while ((j < (start + count)) - && (pxace[j].tag == tag) - && (pxace[j].id == id)) { - if (!(pxace[j].perms & POSIX_PERM_DENIAL)) - allow |= pxace[j].perms; - j++; - } - } + mode = 0; + pxace = posix_desc->acl.ace; + acccnt = posix_desc->acccnt; + tagsset = 0; + denywrld = 0; + /* + * Get denials to world which are meant to prevent + * execution flags to be inherited by plain files + */ + for (j=start; j<(start + count); j++) { + if (pxace[j].perms & POSIX_PERM_DENIAL) { + /* deny world exec not for default */ + if ((pxace[j].tag == POSIX_ACL_OTHER) + && !start) + denywrld = pxace[j].perms; + } + } + /* + * Collect groups of ACEs related to the same id + * and determine what is granted (denials are ignored) + * It is important the ACEs have been sorted + */ + j = start; + k = target; + deny = 0; + while (j < (start + count)) { + allow = 0; + tag = pxace[j].tag; + id = pxace[j].id; + if (tag == POSIX_ACL_MASK) { + deny = pxace[j].perms; + j++; + while ((j < (start + count)) + && (pxace[j].tag == POSIX_ACL_MASK)) + j++; + } else { + if (!(pxace[j].perms & POSIX_PERM_DENIAL)) + allow = pxace[j].perms; + j++; + while ((j < (start + count)) + && (pxace[j].tag == tag) + && (pxace[j].id == id)) { + if (!(pxace[j].perms & POSIX_PERM_DENIAL)) + allow |= pxace[j].perms; + j++; + } + } - /* - * Store the grants into a Posix ACE - */ - if (tag == POSIX_ACL_MASK) - perms = ~deny; - else - perms = allow & ~denywrld; - if (tag != POSIX_ACL_SPECIAL) { - pxace[k].tag = tag; - pxace[k].id = id; - pxace[k].perms = perms - & (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X); - tagsset |= tag; - k++; - } - switch (tag) { - case POSIX_ACL_USER_OBJ : - mode |= ((perms & 7) << 6); - break; - case POSIX_ACL_GROUP_OBJ : - case POSIX_ACL_MASK : - mode = (mode & 07707) | ((perms & 7) << 3); - break; - case POSIX_ACL_OTHER : - mode |= perms & 7; - break; - case POSIX_ACL_SPECIAL : - mode |= perms & (S_ISVTX | S_ISUID | S_ISGID); - break; - default : - break; - } - } - if (!start) { /* not satisfactory */ - posix_desc->mode = mode; - posix_desc->tagsset = tagsset; - } - return (k - target); + /* + * Store the grants into a Posix ACE + */ + if (tag == POSIX_ACL_MASK) + perms = ~deny; + else + perms = allow & ~denywrld; + if (tag != POSIX_ACL_SPECIAL) { + pxace[k].tag = tag; + pxace[k].id = id; + pxace[k].perms = perms + & (POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X); + tagsset |= tag; + k++; + } + switch (tag) { + case POSIX_ACL_USER_OBJ : + mode |= ((perms & 7) << 6); + break; + case POSIX_ACL_GROUP_OBJ : + case POSIX_ACL_MASK : + mode = (mode & 07707) | ((perms & 7) << 3); + break; + case POSIX_ACL_OTHER : + mode |= perms & 7; + break; + case POSIX_ACL_SPECIAL : + mode |= perms & (S_ISVTX | S_ISUID | S_ISGID); + break; + default : + break; + } + } + if (!start) { /* not satisfactory */ + posix_desc->mode = mode; + posix_desc->tagsset = tagsset; + } + return (k - target); } #endif /* POSIXACLS */ @@ -3197,79 +3231,80 @@ static int norm_ownadmin_permissions_posix(struct POSIX_SECURITY *posix_desc, static int build_ownadmin_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const ACL *pacl; - const ACCESS_ALLOWED_ACE *pace; - int offdacl; - int offace; - int acecnt; - int nace; - BOOL firstapply; - int isforeign; - le32 special; - le32 allowown, allowgrp, allowall; - le32 denyown, denygrp, denyall; + const SID *usid, const SID *gsid, BOOL isdir) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const ACL *pacl; + const ACCESS_ALLOWED_ACE *pace; + int offdacl; + int offace; + int acecnt; + int nace; + BOOL firstapply; + int isforeign; + le32 special; + le32 allowown, allowgrp, allowall; + le32 denyown, denygrp, denyall; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - offdacl = le32_to_cpu(phead->dacl); - pacl = (const ACL*)&securattr[offdacl]; - special = const_cpu_to_le32(0); - allowown = allowgrp = allowall = const_cpu_to_le32(0); - denyown = denygrp = denyall = const_cpu_to_le32(0); - if (offdacl) { - acecnt = le16_to_cpu(pacl->ace_count); - offace = offdacl + sizeof(ACL); - } else - acecnt = 0; - firstapply = TRUE; - isforeign = 3; - for (nace = 0; nace < acecnt; nace++) { - pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; - if (!(pace->flags & INHERIT_ONLY_ACE) - && !(~pace->mask & (ROOT_OWNER_UNMARK | ROOT_GROUP_UNMARK))) { - if ((ntfs_same_sid(usid, &pace->sid) - || ntfs_same_sid(ownersid, &pace->sid)) - && (((pace->mask & WRITE_OWNER) && firstapply))) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) { - allowown |= pace->mask; - isforeign &= ~1; - } else - if (pace->type == ACCESS_DENIED_ACE_TYPE) - denyown |= pace->mask; - } else - if (ntfs_same_sid(gsid, &pace->sid) - && (!(pace->mask & WRITE_OWNER))) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) { - allowgrp |= pace->mask; - isforeign &= ~2; - } else - if (pace->type == ACCESS_DENIED_ACE_TYPE) - denygrp |= pace->mask; - } else if (is_world_sid((const SID*)&pace->sid)) { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - allowall |= pace->mask; - else - if (pace->type == ACCESS_DENIED_ACE_TYPE) - denyall |= pace->mask; - } - firstapply = FALSE; - } else - if (!(pace->flags & INHERIT_ONLY_ACE)) - if ((ntfs_same_sid((const SID*)&pace->sid,nullsid)) - && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) - special |= pace->mask; - offace += le16_to_cpu(pace->size); - } - if (isforeign) { - allowown |= (allowgrp | allowall); - allowgrp |= allowall; - } - return (merge_permissions(isdir, - allowown & ~(denyown | denyall), - allowgrp & ~(denygrp | denyall), - allowall & ~denyall, - special)); + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + offdacl = le32_to_cpu(phead->dacl); + pacl = (const ACL*)&securattr[offdacl]; + special = const_cpu_to_le32(0); + allowown = allowgrp = allowall = const_cpu_to_le32(0); + denyown = denygrp = denyall = const_cpu_to_le32(0); + if (offdacl) { + acecnt = le16_to_cpu(pacl->ace_count); + offace = offdacl + sizeof(ACL); + } else + acecnt = 0; + firstapply = TRUE; + isforeign = 3; + for (nace = 0; nace < acecnt; nace++) { + pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; + if (!(pace->flags & INHERIT_ONLY_ACE) + && !(~pace->mask & (ROOT_OWNER_UNMARK | ROOT_GROUP_UNMARK))) { + if ((ntfs_same_sid(usid, &pace->sid) + || ntfs_same_sid(ownersid, &pace->sid)) + && (((pace->mask & WRITE_OWNER) && firstapply))) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) { + allowown |= pace->mask; + isforeign &= ~1; + } else + if (pace->type == ACCESS_DENIED_ACE_TYPE) + denyown |= pace->mask; + } else + if (ntfs_same_sid(gsid, &pace->sid) + && (!(pace->mask & WRITE_OWNER))) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) { + allowgrp |= pace->mask; + isforeign &= ~2; + } else + if (pace->type == ACCESS_DENIED_ACE_TYPE) + denygrp |= pace->mask; + } else if (is_world_sid((const SID*)&pace->sid)) { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + allowall |= pace->mask; + else + if (pace->type == ACCESS_DENIED_ACE_TYPE) + denyall |= pace->mask; + } + firstapply = FALSE; + } else + if (!(pace->flags & INHERIT_ONLY_ACE)) + if ((ntfs_same_sid((const SID*)&pace->sid,nullsid)) + && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) + special |= pace->mask; + offace += le16_to_cpu(pace->size); + } + if (isforeign) { + allowown |= (allowgrp | allowall); + allowgrp |= allowall; + } + return (merge_permissions(isdir, + allowown & ~(denyown | denyall), + allowgrp & ~(denygrp | denyall), + allowall & ~denyall, + special)); } #if OWNERFROMACL @@ -3287,39 +3322,40 @@ static int build_ownadmin_permissions(const char *securattr, * as owned by administrator. */ -const SID *ntfs_acl_owner(const char *securattr) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const SID *usid; - const ACL *pacl; - const ACCESS_ALLOWED_ACE *pace; - int offdacl; - int offace; - int acecnt; - int nace; - BOOL found; +const SID *ntfs_acl_owner(const char *securattr) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const SID *usid; + const ACL *pacl; + const ACCESS_ALLOWED_ACE *pace; + int offdacl; + int offace; + int acecnt; + int nace; + BOOL found; - found = FALSE; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - offdacl = le32_to_cpu(phead->dacl); - if (offdacl) { - pacl = (const ACL*)&securattr[offdacl]; - acecnt = le16_to_cpu(pacl->ace_count); - offace = offdacl + sizeof(ACL); - nace = 0; - do { - pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; - if ((pace->mask & WRITE_OWNER) - && (pace->type == ACCESS_ALLOWED_ACE_TYPE) - && ntfs_is_user_sid(&pace->sid)) - found = TRUE; - offace += le16_to_cpu(pace->size); - } while (!found && (++nace < acecnt)); - } - if (found) - usid = &pace->sid; - else - usid = (const SID*)&securattr[le32_to_cpu(phead->owner)]; - return (usid); + found = FALSE; + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + offdacl = le32_to_cpu(phead->dacl); + if (offdacl) { + pacl = (const ACL*)&securattr[offdacl]; + acecnt = le16_to_cpu(pacl->ace_count); + offace = offdacl + sizeof(ACL); + nace = 0; + do { + pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; + if ((pace->mask & WRITE_OWNER) + && (pace->type == ACCESS_ALLOWED_ACE_TYPE) + && ntfs_is_user_sid(&pace->sid)) + found = TRUE; + offace += le16_to_cpu(pace->size); + } while (!found && (++nace < acecnt)); + } + if (found) + usid = &pace->sid; + else + usid = (const SID*)&securattr[le32_to_cpu(phead->owner)]; + return (usid); } #else @@ -3342,36 +3378,37 @@ const SID *ntfs_acl_owner(const char *securattr) { static uid_t find_tenant(struct MAPPING *const mapping[], - const char *securattr) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const ACL *pacl; - const ACCESS_ALLOWED_ACE *pace; - int offdacl; - int offace; - int acecnt; - int nace; - uid_t tid; - uid_t xid; + const char *securattr) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const ACL *pacl; + const ACCESS_ALLOWED_ACE *pace; + int offdacl; + int offace; + int acecnt; + int nace; + uid_t tid; + uid_t xid; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - offdacl = le32_to_cpu(phead->dacl); - pacl = (const ACL*)&securattr[offdacl]; - tid = 0; - if (offdacl) { - acecnt = le16_to_cpu(pacl->ace_count); - offace = offdacl + sizeof(ACL); - } else - acecnt = 0; - for (nace = 0; nace < acecnt; nace++) { - pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; - if ((pace->type == ACCESS_ALLOWED_ACE_TYPE) - && (pace->mask & DIR_WRITE)) { - xid = NTFS_FIND_USER(mapping[MAPUSERS], &pace->sid); - if (xid) tid = xid; - } - offace += le16_to_cpu(pace->size); - } - return (tid); + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + offdacl = le32_to_cpu(phead->dacl); + pacl = (const ACL*)&securattr[offdacl]; + tid = 0; + if (offdacl) { + acecnt = le16_to_cpu(pacl->ace_count); + offace = offdacl + sizeof(ACL); + } else + acecnt = 0; + for (nace = 0; nace < acecnt; nace++) { + pace = (const ACCESS_ALLOWED_ACE*)&securattr[offace]; + if ((pace->type == ACCESS_ALLOWED_ACE_TYPE) + && (pace->mask & DIR_WRITE)) { + xid = NTFS_FIND_USER(mapping[MAPUSERS], &pace->sid); + if (xid) tid = xid; + } + offace += le16_to_cpu(pace->size); + } + return (tid); } #endif /* OWNERFROMACL */ @@ -3390,439 +3427,440 @@ static uid_t find_tenant(struct MAPPING *const mapping[], */ struct POSIX_SECURITY *ntfs_build_permissions_posix( - struct MAPPING *const mapping[], - const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - struct POSIX_SECURITY *pxdesc; - const ACL *pacl; - const ACCESS_ALLOWED_ACE *pace; - struct POSIX_ACE *pxace; - struct { - uid_t prevuid; - gid_t prevgid; - int groupmasks; - s16 tagsset; - BOOL gotowner; - BOOL gotownermask; - BOOL gotgroup; - mode_t permswrld; - } ctx[2], *pctx; - int offdacl; - int offace; - int alloccnt; - int acecnt; - uid_t uid; - gid_t gid; - int i,j; - int k,l; - BOOL ignore; - BOOL adminowns; - BOOL groupowns; - BOOL firstinh; - BOOL genericinh; + struct MAPPING *const mapping[], + const char *securattr, + const SID *usid, const SID *gsid, BOOL isdir) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + struct POSIX_SECURITY *pxdesc; + const ACL *pacl; + const ACCESS_ALLOWED_ACE *pace; + struct POSIX_ACE *pxace; + struct { + uid_t prevuid; + gid_t prevgid; + int groupmasks; + s16 tagsset; + BOOL gotowner; + BOOL gotownermask; + BOOL gotgroup; + mode_t permswrld; + } ctx[2], *pctx; + int offdacl; + int offace; + int alloccnt; + int acecnt; + uid_t uid; + gid_t gid; + int i,j; + int k,l; + BOOL ignore; + BOOL adminowns; + BOOL groupowns; + BOOL firstinh; + BOOL genericinh; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - offdacl = le32_to_cpu(phead->dacl); - if (offdacl) { - pacl = (const ACL*)&securattr[offdacl]; - acecnt = le16_to_cpu(pacl->ace_count); - offace = offdacl + sizeof(ACL); - } else { - acecnt = 0; - offace = 0; - } - adminowns = FALSE; - groupowns = ntfs_same_sid(gsid,usid); - firstinh = FALSE; - genericinh = FALSE; - /* - * Build a raw posix security descriptor - * by just translating permissions and ids - * Add 2 to the count of ACE to be able to insert - * a group ACE later in access and default ACLs - * and add 2 more to be able to insert ACEs for owner - * and 2 more for other - */ - alloccnt = acecnt + 6; - pxdesc = (struct POSIX_SECURITY*)malloc( - sizeof(struct POSIX_SECURITY) - + alloccnt*sizeof(struct POSIX_ACE)); - k = 0; - l = alloccnt; - for (i=0; i<2; i++) { - pctx = &ctx[i]; - pctx->permswrld = 0; - pctx->prevuid = -1; - pctx->prevgid = -1; - pctx->groupmasks = 0; - pctx->tagsset = 0; - pctx->gotowner = FALSE; - pctx->gotgroup = FALSE; - pctx->gotownermask = FALSE; - } - for (j=0; jflags & INHERIT_ONLY_ACE) { - pxace = &pxdesc->acl.ace[l - 1]; - pctx = &ctx[1]; - } else { - pxace = &pxdesc->acl.ace[k]; - pctx = &ctx[0]; - } - ignore = FALSE; - /* - * grants for root as a designated user or group - */ - if ((~pace->mask & (ROOT_OWNER_UNMARK | ROOT_GROUP_UNMARK)) - && (pace->type == ACCESS_ALLOWED_ACE_TYPE) - && ntfs_same_sid(&pace->sid, adminsid)) { - pxace->tag = (pace->mask & ROOT_OWNER_UNMARK ? POSIX_ACL_GROUP : POSIX_ACL_USER); - pxace->id = 0; - if ((pace->mask & (GENERIC_ALL | WRITE_OWNER)) - && (pace->flags & INHERIT_ONLY_ACE)) - ignore = genericinh = TRUE; - } else - if (ntfs_same_sid(usid, &pace->sid)) { - pxace->id = -1; - /* - * Owner has no write-owner right : - * a group was defined same as owner - * or admin was owner or group : - * denials are meant to owner - * and grants are meant to group - */ - if (!(pace->mask & (WRITE_OWNER | GENERIC_ALL)) - && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) { - if (ntfs_same_sid(gsid,usid)) { - pxace->tag = POSIX_ACL_GROUP_OBJ; - pxace->id = -1; - } else { - if (ntfs_same_sid(&pace->sid,usid)) - groupowns = TRUE; - gid = NTFS_FIND_GROUP(mapping[MAPGROUPS],&pace->sid); - if (gid) { - pxace->tag = POSIX_ACL_GROUP; - pxace->id = gid; - pctx->prevgid = gid; - } else { - uid = NTFS_FIND_USER(mapping[MAPUSERS],&pace->sid); - if (uid) { - pxace->tag = POSIX_ACL_USER; - pxace->id = uid; - } else - ignore = TRUE; - } - } - } else { - /* - * when group owns, late denials for owner - * mean group mask - */ - if ((pace->type == ACCESS_DENIED_ACE_TYPE) - && (pace->mask & WRITE_OWNER)) { - pxace->tag = POSIX_ACL_MASK; - pctx->gotownermask = TRUE; - if (pctx->gotowner) - pctx->groupmasks++; - } else { - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - pctx->gotowner = TRUE; - if (pctx->gotownermask && !pctx->gotowner) { - uid = NTFS_FIND_USER(mapping[MAPUSERS],&pace->sid); - pxace->id = uid; - pxace->tag = POSIX_ACL_USER; - } else - pxace->tag = POSIX_ACL_USER_OBJ; - /* system ignored, and admin */ - /* ignored at first position */ - if (pace->flags & INHERIT_ONLY_ACE) { - if ((firstinh && ntfs_same_sid(&pace->sid,adminsid)) - || ntfs_same_sid(&pace->sid,systemsid)) - ignore = TRUE; - if (!firstinh) { - firstinh = TRUE; - } - } else { - if ((adminowns && ntfs_same_sid(&pace->sid,adminsid)) - || ntfs_same_sid(&pace->sid,systemsid)) - ignore = TRUE; - if (ntfs_same_sid(usid,adminsid)) - adminowns = TRUE; - } - } - } - } else if (ntfs_same_sid(gsid, &pace->sid)) { - if ((pace->type == ACCESS_DENIED_ACE_TYPE) - && (pace->mask & WRITE_OWNER)) { - pxace->tag = POSIX_ACL_MASK; - pxace->id = -1; - if (pctx->gotowner) - pctx->groupmasks++; - } else { - if (pctx->gotgroup || (pctx->groupmasks > 1)) { - gid = NTFS_FIND_GROUP(mapping[MAPGROUPS],&pace->sid); - if (gid) { - pxace->id = gid; - pxace->tag = POSIX_ACL_GROUP; - pctx->prevgid = gid; - } else - ignore = TRUE; - } else { - pxace->id = -1; - pxace->tag = POSIX_ACL_GROUP_OBJ; - if (pace->type == ACCESS_ALLOWED_ACE_TYPE) - pctx->gotgroup = TRUE; - } + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + offdacl = le32_to_cpu(phead->dacl); + if (offdacl) { + pacl = (const ACL*)&securattr[offdacl]; + acecnt = le16_to_cpu(pacl->ace_count); + offace = offdacl + sizeof(ACL); + } else { + acecnt = 0; + offace = 0; + } + adminowns = FALSE; + groupowns = ntfs_same_sid(gsid,usid); + firstinh = FALSE; + genericinh = FALSE; + /* + * Build a raw posix security descriptor + * by just translating permissions and ids + * Add 2 to the count of ACE to be able to insert + * a group ACE later in access and default ACLs + * and add 2 more to be able to insert ACEs for owner + * and 2 more for other + */ + alloccnt = acecnt + 6; + pxdesc = (struct POSIX_SECURITY*)malloc( + sizeof(struct POSIX_SECURITY) + + alloccnt*sizeof(struct POSIX_ACE)); + k = 0; + l = alloccnt; + for (i=0; i<2; i++) { + pctx = &ctx[i]; + pctx->permswrld = 0; + pctx->prevuid = -1; + pctx->prevgid = -1; + pctx->groupmasks = 0; + pctx->tagsset = 0; + pctx->gotowner = FALSE; + pctx->gotgroup = FALSE; + pctx->gotownermask = FALSE; + } + for (j=0; jflags & INHERIT_ONLY_ACE) { + pxace = &pxdesc->acl.ace[l - 1]; + pctx = &ctx[1]; + } else { + pxace = &pxdesc->acl.ace[k]; + pctx = &ctx[0]; + } + ignore = FALSE; + /* + * grants for root as a designated user or group + */ + if ((~pace->mask & (ROOT_OWNER_UNMARK | ROOT_GROUP_UNMARK)) + && (pace->type == ACCESS_ALLOWED_ACE_TYPE) + && ntfs_same_sid(&pace->sid, adminsid)) { + pxace->tag = (pace->mask & ROOT_OWNER_UNMARK ? POSIX_ACL_GROUP : POSIX_ACL_USER); + pxace->id = 0; + if ((pace->mask & (GENERIC_ALL | WRITE_OWNER)) + && (pace->flags & INHERIT_ONLY_ACE)) + ignore = genericinh = TRUE; + } else + if (ntfs_same_sid(usid, &pace->sid)) { + pxace->id = -1; + /* + * Owner has no write-owner right : + * a group was defined same as owner + * or admin was owner or group : + * denials are meant to owner + * and grants are meant to group + */ + if (!(pace->mask & (WRITE_OWNER | GENERIC_ALL)) + && (pace->type == ACCESS_ALLOWED_ACE_TYPE)) { + if (ntfs_same_sid(gsid,usid)) { + pxace->tag = POSIX_ACL_GROUP_OBJ; + pxace->id = -1; + } else { + if (ntfs_same_sid(&pace->sid,usid)) + groupowns = TRUE; + gid = NTFS_FIND_GROUP(mapping[MAPGROUPS],&pace->sid); + if (gid) { + pxace->tag = POSIX_ACL_GROUP; + pxace->id = gid; + pctx->prevgid = gid; + } else { + uid = NTFS_FIND_USER(mapping[MAPUSERS],&pace->sid); + if (uid) { + pxace->tag = POSIX_ACL_USER; + pxace->id = uid; + } else + ignore = TRUE; + } + } + } else { + /* + * when group owns, late denials for owner + * mean group mask + */ + if ((pace->type == ACCESS_DENIED_ACE_TYPE) + && (pace->mask & WRITE_OWNER)) { + pxace->tag = POSIX_ACL_MASK; + pctx->gotownermask = TRUE; + if (pctx->gotowner) + pctx->groupmasks++; + } else { + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + pctx->gotowner = TRUE; + if (pctx->gotownermask && !pctx->gotowner) { + uid = NTFS_FIND_USER(mapping[MAPUSERS],&pace->sid); + pxace->id = uid; + pxace->tag = POSIX_ACL_USER; + } else + pxace->tag = POSIX_ACL_USER_OBJ; + /* system ignored, and admin */ + /* ignored at first position */ + if (pace->flags & INHERIT_ONLY_ACE) { + if ((firstinh && ntfs_same_sid(&pace->sid,adminsid)) + || ntfs_same_sid(&pace->sid,systemsid)) + ignore = TRUE; + if (!firstinh) { + firstinh = TRUE; + } + } else { + if ((adminowns && ntfs_same_sid(&pace->sid,adminsid)) + || ntfs_same_sid(&pace->sid,systemsid)) + ignore = TRUE; + if (ntfs_same_sid(usid,adminsid)) + adminowns = TRUE; + } + } + } + } else if (ntfs_same_sid(gsid, &pace->sid)) { + if ((pace->type == ACCESS_DENIED_ACE_TYPE) + && (pace->mask & WRITE_OWNER)) { + pxace->tag = POSIX_ACL_MASK; + pxace->id = -1; + if (pctx->gotowner) + pctx->groupmasks++; + } else { + if (pctx->gotgroup || (pctx->groupmasks > 1)) { + gid = NTFS_FIND_GROUP(mapping[MAPGROUPS],&pace->sid); + if (gid) { + pxace->id = gid; + pxace->tag = POSIX_ACL_GROUP; + pctx->prevgid = gid; + } else + ignore = TRUE; + } else { + pxace->id = -1; + pxace->tag = POSIX_ACL_GROUP_OBJ; + if (pace->type == ACCESS_ALLOWED_ACE_TYPE) + pctx->gotgroup = TRUE; + } - if (ntfs_same_sid(gsid,adminsid) - || ntfs_same_sid(gsid,systemsid)) { - if (pace->mask & (WRITE_OWNER | GENERIC_ALL)) - ignore = TRUE; - if (ntfs_same_sid(gsid,adminsid)) - adminowns = TRUE; - else - genericinh = ignore; - } - } - } else if (is_world_sid((const SID*)&pace->sid)) { - pxace->id = -1; - pxace->tag = POSIX_ACL_OTHER; - if ((pace->type == ACCESS_DENIED_ACE_TYPE) - && (pace->flags & INHERIT_ONLY_ACE)) - ignore = TRUE; - } else if (ntfs_same_sid((const SID*)&pace->sid,nullsid)) { - pxace->id = -1; - pxace->tag = POSIX_ACL_SPECIAL; - } else { - uid = NTFS_FIND_USER(mapping[MAPUSERS],&pace->sid); - if (uid) { - if ((pace->type == ACCESS_DENIED_ACE_TYPE) - && (pace->mask & WRITE_OWNER) - && (pctx->prevuid != uid)) { - pxace->id = -1; - pxace->tag = POSIX_ACL_MASK; - } else { - pxace->id = uid; - pxace->tag = POSIX_ACL_USER; - } - pctx->prevuid = uid; - } else { - gid = NTFS_FIND_GROUP(mapping[MAPGROUPS],&pace->sid); - if (gid) { - if ((pace->type == ACCESS_DENIED_ACE_TYPE) - && (pace->mask & WRITE_OWNER) - && (pctx->prevgid != gid)) { - pxace->tag = POSIX_ACL_MASK; - pctx->groupmasks++; - } else { - pxace->tag = POSIX_ACL_GROUP; - } - pxace->id = gid; - pctx->prevgid = gid; - } else { - /* - * do not grant rights to unknown - * people and do not define root as a - * designated user or group - */ - ignore = TRUE; - } - } - } - if (!ignore) { - pxace->perms = 0; - /* specific decoding for vtx/uid/gid */ - if (pxace->tag == POSIX_ACL_SPECIAL) { - if (pace->mask & FILE_APPEND_DATA) - pxace->perms |= S_ISUID; - if (pace->mask & FILE_WRITE_DATA) - pxace->perms |= S_ISGID; - if (pace->mask & FILE_READ_DATA) - pxace->perms |= S_ISVTX; - } else - if (isdir) { - if (pace->mask & DIR_GEXEC) - pxace->perms |= POSIX_PERM_X; - if (pace->mask & DIR_GWRITE) - pxace->perms |= POSIX_PERM_W; - if (pace->mask & DIR_GREAD) - pxace->perms |= POSIX_PERM_R; - if ((pace->mask & GENERIC_ALL) - && (pace->flags & INHERIT_ONLY_ACE)) - pxace->perms |= POSIX_PERM_X - | POSIX_PERM_W - | POSIX_PERM_R; - } else { - if (pace->mask & FILE_GEXEC) - pxace->perms |= POSIX_PERM_X; - if (pace->mask & FILE_GWRITE) - pxace->perms |= POSIX_PERM_W; - if (pace->mask & FILE_GREAD) - pxace->perms |= POSIX_PERM_R; - } + if (ntfs_same_sid(gsid,adminsid) + || ntfs_same_sid(gsid,systemsid)) { + if (pace->mask & (WRITE_OWNER | GENERIC_ALL)) + ignore = TRUE; + if (ntfs_same_sid(gsid,adminsid)) + adminowns = TRUE; + else + genericinh = ignore; + } + } + } else if (is_world_sid((const SID*)&pace->sid)) { + pxace->id = -1; + pxace->tag = POSIX_ACL_OTHER; + if ((pace->type == ACCESS_DENIED_ACE_TYPE) + && (pace->flags & INHERIT_ONLY_ACE)) + ignore = TRUE; + } else if (ntfs_same_sid((const SID*)&pace->sid,nullsid)) { + pxace->id = -1; + pxace->tag = POSIX_ACL_SPECIAL; + } else { + uid = NTFS_FIND_USER(mapping[MAPUSERS],&pace->sid); + if (uid) { + if ((pace->type == ACCESS_DENIED_ACE_TYPE) + && (pace->mask & WRITE_OWNER) + && (pctx->prevuid != uid)) { + pxace->id = -1; + pxace->tag = POSIX_ACL_MASK; + } else { + pxace->id = uid; + pxace->tag = POSIX_ACL_USER; + } + pctx->prevuid = uid; + } else { + gid = NTFS_FIND_GROUP(mapping[MAPGROUPS],&pace->sid); + if (gid) { + if ((pace->type == ACCESS_DENIED_ACE_TYPE) + && (pace->mask & WRITE_OWNER) + && (pctx->prevgid != gid)) { + pxace->tag = POSIX_ACL_MASK; + pctx->groupmasks++; + } else { + pxace->tag = POSIX_ACL_GROUP; + } + pxace->id = gid; + pctx->prevgid = gid; + } else { + /* + * do not grant rights to unknown + * people and do not define root as a + * designated user or group + */ + ignore = TRUE; + } + } + } + if (!ignore) { + pxace->perms = 0; + /* specific decoding for vtx/uid/gid */ + if (pxace->tag == POSIX_ACL_SPECIAL) { + if (pace->mask & FILE_APPEND_DATA) + pxace->perms |= S_ISUID; + if (pace->mask & FILE_WRITE_DATA) + pxace->perms |= S_ISGID; + if (pace->mask & FILE_READ_DATA) + pxace->perms |= S_ISVTX; + } else + if (isdir) { + if (pace->mask & DIR_GEXEC) + pxace->perms |= POSIX_PERM_X; + if (pace->mask & DIR_GWRITE) + pxace->perms |= POSIX_PERM_W; + if (pace->mask & DIR_GREAD) + pxace->perms |= POSIX_PERM_R; + if ((pace->mask & GENERIC_ALL) + && (pace->flags & INHERIT_ONLY_ACE)) + pxace->perms |= POSIX_PERM_X + | POSIX_PERM_W + | POSIX_PERM_R; + } else { + if (pace->mask & FILE_GEXEC) + pxace->perms |= POSIX_PERM_X; + if (pace->mask & FILE_GWRITE) + pxace->perms |= POSIX_PERM_W; + if (pace->mask & FILE_GREAD) + pxace->perms |= POSIX_PERM_R; + } - if (pace->type != ACCESS_ALLOWED_ACE_TYPE) - pxace->perms |= POSIX_PERM_DENIAL; - else - if (pxace->tag == POSIX_ACL_OTHER) - pctx->permswrld = pxace->perms; - pctx->tagsset |= pxace->tag; - if (pace->flags & INHERIT_ONLY_ACE) { - l--; - } else { - k++; - } - } - offace += le16_to_cpu(pace->size); - } - /* - * Create world perms if none (both lists) - */ - for (i=0; i<2; i++) - if ((genericinh || !i) - && !(ctx[i].tagsset & POSIX_ACL_OTHER)) { - if (i) - pxace = &pxdesc->acl.ace[--l]; - else - pxace = &pxdesc->acl.ace[k++]; - pxace->tag = POSIX_ACL_OTHER; - pxace->id = -1; - pxace->perms = 0; - ctx[i].tagsset |= POSIX_ACL_OTHER; - ctx[i].permswrld = 0; - } - /* - * Set basic owner perms if none (both lists) - * This happens for files created by Windows in directories - * created by Linux and owned by root, because Windows - * merges the admin ACEs - */ - for (i=0; i<2; i++) - if (!(ctx[i].tagsset & POSIX_ACL_USER_OBJ) - && (ctx[i].tagsset & POSIX_ACL_OTHER)) { - if (i) - pxace = &pxdesc->acl.ace[--l]; - else - pxace = &pxdesc->acl.ace[k++]; - pxace->tag = POSIX_ACL_USER_OBJ; - pxace->id = -1; - pxace->perms = POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X; - ctx[i].tagsset |= POSIX_ACL_USER_OBJ; - } - /* - * Duplicate world perms as group_obj perms if none - */ - for (i=0; i<2; i++) - if ((ctx[i].tagsset & POSIX_ACL_OTHER) - && !(ctx[i].tagsset & POSIX_ACL_GROUP_OBJ)) { - if (i) - pxace = &pxdesc->acl.ace[--l]; - else - pxace = &pxdesc->acl.ace[k++]; - pxace->tag = POSIX_ACL_GROUP_OBJ; - pxace->id = -1; - pxace->perms = ctx[i].permswrld; - ctx[i].tagsset |= POSIX_ACL_GROUP_OBJ; - } - /* - * Also duplicate world perms as group perms if they - * were converted to mask and not followed by a group entry - */ - if (ctx[0].groupmasks) { - for (j=k-2; j>=0; j--) { - if ((pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) - && (pxdesc->acl.ace[j].id != -1) - && ((pxdesc->acl.ace[j+1].tag != POSIX_ACL_GROUP) - || (pxdesc->acl.ace[j+1].id - != pxdesc->acl.ace[j].id))) { - pxace = &pxdesc->acl.ace[k]; - pxace->tag = POSIX_ACL_GROUP; - pxace->id = pxdesc->acl.ace[j].id; - pxace->perms = ctx[0].permswrld; - ctx[0].tagsset |= POSIX_ACL_GROUP; - k++; - } - if (pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) - pxdesc->acl.ace[j].id = -1; - } - } - if (ctx[1].groupmasks) { - for (j=l; j<(alloccnt-1); j++) { - if ((pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) - && (pxdesc->acl.ace[j].id != -1) - && ((pxdesc->acl.ace[j+1].tag != POSIX_ACL_GROUP) - || (pxdesc->acl.ace[j+1].id - != pxdesc->acl.ace[j].id))) { - pxace = &pxdesc->acl.ace[l - 1]; - pxace->tag = POSIX_ACL_GROUP; - pxace->id = pxdesc->acl.ace[j].id; - pxace->perms = ctx[1].permswrld; - ctx[1].tagsset |= POSIX_ACL_GROUP; - l--; - } - if (pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) - pxdesc->acl.ace[j].id = -1; - } - } + if (pace->type != ACCESS_ALLOWED_ACE_TYPE) + pxace->perms |= POSIX_PERM_DENIAL; + else + if (pxace->tag == POSIX_ACL_OTHER) + pctx->permswrld = pxace->perms; + pctx->tagsset |= pxace->tag; + if (pace->flags & INHERIT_ONLY_ACE) { + l--; + } else { + k++; + } + } + offace += le16_to_cpu(pace->size); + } + /* + * Create world perms if none (both lists) + */ + for (i=0; i<2; i++) + if ((genericinh || !i) + && !(ctx[i].tagsset & POSIX_ACL_OTHER)) { + if (i) + pxace = &pxdesc->acl.ace[--l]; + else + pxace = &pxdesc->acl.ace[k++]; + pxace->tag = POSIX_ACL_OTHER; + pxace->id = -1; + pxace->perms = 0; + ctx[i].tagsset |= POSIX_ACL_OTHER; + ctx[i].permswrld = 0; + } + /* + * Set basic owner perms if none (both lists) + * This happens for files created by Windows in directories + * created by Linux and owned by root, because Windows + * merges the admin ACEs + */ + for (i=0; i<2; i++) + if (!(ctx[i].tagsset & POSIX_ACL_USER_OBJ) + && (ctx[i].tagsset & POSIX_ACL_OTHER)) { + if (i) + pxace = &pxdesc->acl.ace[--l]; + else + pxace = &pxdesc->acl.ace[k++]; + pxace->tag = POSIX_ACL_USER_OBJ; + pxace->id = -1; + pxace->perms = POSIX_PERM_R | POSIX_PERM_W | POSIX_PERM_X; + ctx[i].tagsset |= POSIX_ACL_USER_OBJ; + } + /* + * Duplicate world perms as group_obj perms if none + */ + for (i=0; i<2; i++) + if ((ctx[i].tagsset & POSIX_ACL_OTHER) + && !(ctx[i].tagsset & POSIX_ACL_GROUP_OBJ)) { + if (i) + pxace = &pxdesc->acl.ace[--l]; + else + pxace = &pxdesc->acl.ace[k++]; + pxace->tag = POSIX_ACL_GROUP_OBJ; + pxace->id = -1; + pxace->perms = ctx[i].permswrld; + ctx[i].tagsset |= POSIX_ACL_GROUP_OBJ; + } + /* + * Also duplicate world perms as group perms if they + * were converted to mask and not followed by a group entry + */ + if (ctx[0].groupmasks) { + for (j=k-2; j>=0; j--) { + if ((pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) + && (pxdesc->acl.ace[j].id != -1) + && ((pxdesc->acl.ace[j+1].tag != POSIX_ACL_GROUP) + || (pxdesc->acl.ace[j+1].id + != pxdesc->acl.ace[j].id))) { + pxace = &pxdesc->acl.ace[k]; + pxace->tag = POSIX_ACL_GROUP; + pxace->id = pxdesc->acl.ace[j].id; + pxace->perms = ctx[0].permswrld; + ctx[0].tagsset |= POSIX_ACL_GROUP; + k++; + } + if (pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) + pxdesc->acl.ace[j].id = -1; + } + } + if (ctx[1].groupmasks) { + for (j=l; j<(alloccnt-1); j++) { + if ((pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) + && (pxdesc->acl.ace[j].id != -1) + && ((pxdesc->acl.ace[j+1].tag != POSIX_ACL_GROUP) + || (pxdesc->acl.ace[j+1].id + != pxdesc->acl.ace[j].id))) { + pxace = &pxdesc->acl.ace[l - 1]; + pxace->tag = POSIX_ACL_GROUP; + pxace->id = pxdesc->acl.ace[j].id; + pxace->perms = ctx[1].permswrld; + ctx[1].tagsset |= POSIX_ACL_GROUP; + l--; + } + if (pxdesc->acl.ace[j].tag == POSIX_ACL_MASK) + pxdesc->acl.ace[j].id = -1; + } + } - /* - * Insert default mask if none present and - * there are designated users or groups - * (the space for it has not beed used) - */ - for (i=0; i<2; i++) - if ((ctx[i].tagsset & (POSIX_ACL_USER | POSIX_ACL_GROUP)) - && !(ctx[i].tagsset & POSIX_ACL_MASK)) { - if (i) - pxace = &pxdesc->acl.ace[--l]; - else - pxace = &pxdesc->acl.ace[k++]; - pxace->tag = POSIX_ACL_MASK; - pxace->id = -1; - pxace->perms = POSIX_PERM_DENIAL; - ctx[i].tagsset |= POSIX_ACL_MASK; - } + /* + * Insert default mask if none present and + * there are designated users or groups + * (the space for it has not beed used) + */ + for (i=0; i<2; i++) + if ((ctx[i].tagsset & (POSIX_ACL_USER | POSIX_ACL_GROUP)) + && !(ctx[i].tagsset & POSIX_ACL_MASK)) { + if (i) + pxace = &pxdesc->acl.ace[--l]; + else + pxace = &pxdesc->acl.ace[k++]; + pxace->tag = POSIX_ACL_MASK; + pxace->id = -1; + pxace->perms = POSIX_PERM_DENIAL; + ctx[i].tagsset |= POSIX_ACL_MASK; + } - if (k > l) { - ntfs_log_error("Posix descriptor is longer than expected\n"); - errno = EIO; - free(pxdesc); - pxdesc = (struct POSIX_SECURITY*)NULL; - } else { - pxdesc->acccnt = k; - pxdesc->defcnt = alloccnt - l; - pxdesc->firstdef = l; - pxdesc->tagsset = ctx[0].tagsset; - pxdesc->acl.version = POSIX_VERSION; - pxdesc->acl.flags = 0; - pxdesc->acl.filler = 0; - ntfs_sort_posix(pxdesc); - if (adminowns) { - k = norm_ownadmin_permissions_posix(pxdesc, - 0, pxdesc->acccnt, 0); - pxdesc->acccnt = k; - l = norm_ownadmin_permissions_posix(pxdesc, - pxdesc->firstdef, pxdesc->defcnt, k); - pxdesc->firstdef = k; - pxdesc->defcnt = l; - } else { - k = norm_std_permissions_posix(pxdesc,groupowns, - 0, pxdesc->acccnt, 0); - pxdesc->acccnt = k; - l = norm_std_permissions_posix(pxdesc,groupowns, - pxdesc->firstdef, pxdesc->defcnt, k); - pxdesc->firstdef = k; - pxdesc->defcnt = l; - } - } - if (pxdesc && !ntfs_valid_posix(pxdesc)) { - ntfs_log_error("Invalid Posix descriptor built\n"); - errno = EIO; - free(pxdesc); - pxdesc = (struct POSIX_SECURITY*)NULL; - } - return (pxdesc); + if (k > l) { + ntfs_log_error("Posix descriptor is longer than expected\n"); + errno = EIO; + free(pxdesc); + pxdesc = (struct POSIX_SECURITY*)NULL; + } else { + pxdesc->acccnt = k; + pxdesc->defcnt = alloccnt - l; + pxdesc->firstdef = l; + pxdesc->tagsset = ctx[0].tagsset; + pxdesc->acl.version = POSIX_VERSION; + pxdesc->acl.flags = 0; + pxdesc->acl.filler = 0; + ntfs_sort_posix(pxdesc); + if (adminowns) { + k = norm_ownadmin_permissions_posix(pxdesc, + 0, pxdesc->acccnt, 0); + pxdesc->acccnt = k; + l = norm_ownadmin_permissions_posix(pxdesc, + pxdesc->firstdef, pxdesc->defcnt, k); + pxdesc->firstdef = k; + pxdesc->defcnt = l; + } else { + k = norm_std_permissions_posix(pxdesc,groupowns, + 0, pxdesc->acccnt, 0); + pxdesc->acccnt = k; + l = norm_std_permissions_posix(pxdesc,groupowns, + pxdesc->firstdef, pxdesc->defcnt, k); + pxdesc->firstdef = k; + pxdesc->defcnt = l; + } + } + if (pxdesc && !ntfs_valid_posix(pxdesc)) { + ntfs_log_error("Invalid Posix descriptor built\n"); + errno = EIO; + free(pxdesc); + pxdesc = (struct POSIX_SECURITY*)NULL; + } + return (pxdesc); } #endif /* POSIXACLS */ @@ -3834,37 +3872,39 @@ struct POSIX_SECURITY *ntfs_build_permissions_posix( */ int ntfs_build_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - int perm; - BOOL adminowns; - BOOL groupowns; + const SID *usid, const SID *gsid, BOOL isdir) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + int perm; + BOOL adminowns; + BOOL groupowns; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - adminowns = ntfs_same_sid(usid,adminsid) - || ntfs_same_sid(gsid,adminsid); - groupowns = !adminowns && ntfs_same_sid(gsid,usid); - if (adminowns) - perm = build_ownadmin_permissions(securattr, usid, gsid, isdir); - else - if (groupowns) - perm = build_owngrp_permissions(securattr, usid, isdir); - else - perm = build_std_permissions(securattr, usid, gsid, isdir); - return (perm); + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + adminowns = ntfs_same_sid(usid,adminsid) + || ntfs_same_sid(gsid,adminsid); + groupowns = !adminowns && ntfs_same_sid(gsid,usid); + if (adminowns) + perm = build_ownadmin_permissions(securattr, usid, gsid, isdir); + else + if (groupowns) + perm = build_owngrp_permissions(securattr, usid, isdir); + else + perm = build_std_permissions(securattr, usid, gsid, isdir); + return (perm); } /* * The following must be in some library... */ -static unsigned long atoul(const char *p) { /* must be somewhere ! */ - unsigned long v; +static unsigned long atoul(const char *p) +{ /* must be somewhere ! */ + unsigned long v; - v = 0; - while ((*p >= '0') && (*p <= '9')) - v = v * 10 + (*p++) - '0'; - return (v); + v = 0; + while ((*p >= '0') && (*p <= '9')) + v = v * 10 + (*p++) - '0'; + return (v); } /* @@ -3873,39 +3913,40 @@ static unsigned long atoul(const char *p) { /* must be somewhere ! */ * The SID is checked to be a valid user one. */ -static SID *encodesid(const char *sidstr) { - SID *sid; - int cnt; - BIGSID bigsid; - SID *bsid; - u32 auth; - const char *p; +static SID *encodesid(const char *sidstr) +{ + SID *sid; + int cnt; + BIGSID bigsid; + SID *bsid; + u32 auth; + const char *p; - sid = (SID*) NULL; - if (!strncmp(sidstr, "S-1-", 4)) { - bsid = (SID*)&bigsid; - bsid->revision = SID_REVISION; - p = &sidstr[4]; - auth = atoul(p); - bsid->identifier_authority.high_part = const_cpu_to_be16(0); - bsid->identifier_authority.low_part = cpu_to_be32(auth); - cnt = 0; - p = strchr(p, '-'); - while (p && (cnt < 8)) { - p++; - auth = atoul(p); - bsid->sub_authority[cnt] = cpu_to_le32(auth); - p = strchr(p, '-'); - cnt++; - } - bsid->sub_authority_count = cnt; - if ((cnt > 0) && ntfs_valid_sid(bsid) && ntfs_is_user_sid(bsid)) { - sid = (SID*) ntfs_malloc(4 * cnt + 8); - if (sid) - memcpy(sid, bsid, 4 * cnt + 8); - } - } - return (sid); + sid = (SID*) NULL; + if (!strncmp(sidstr, "S-1-", 4)) { + bsid = (SID*)&bigsid; + bsid->revision = SID_REVISION; + p = &sidstr[4]; + auth = atoul(p); + bsid->identifier_authority.high_part = const_cpu_to_be16(0); + bsid->identifier_authority.low_part = cpu_to_be32(auth); + cnt = 0; + p = strchr(p, '-'); + while (p && (cnt < 8)) { + p++; + auth = atoul(p); + bsid->sub_authority[cnt] = cpu_to_le32(auth); + p = strchr(p, '-'); + cnt++; + } + bsid->sub_authority_count = cnt; + if ((cnt > 0) && ntfs_valid_sid(bsid) && ntfs_is_user_sid(bsid)) { + sid = (SID*) ntfs_malloc(4 * cnt + 8); + if (sid) + memcpy(sid, bsid, 4 * cnt + 8); + } + } + return (sid); } /* @@ -3916,21 +3957,22 @@ static SID *encodesid(const char *sidstr) { */ static void log_early_error(const char *format, ...) -__attribute__((format(printf, 1, 2))); + __attribute__((format(printf, 1, 2))); -static void log_early_error(const char *format, ...) { - va_list args; +static void log_early_error(const char *format, ...) +{ + va_list args; - va_start(args, format); + va_start(args, format); #ifdef HAVE_SYSLOG_H - openlog("ntfs-3g", LOG_PID, LOG_USER); - ntfs_log_handler_syslog(NULL, NULL, 0, - NTFS_LOG_LEVEL_ERROR, NULL, - format, args); + openlog("ntfs-3g", LOG_PID, LOG_USER); + ntfs_log_handler_syslog(NULL, NULL, 0, + NTFS_LOG_LEVEL_ERROR, NULL, + format, args); #else - vfprintf(stderr,format,args); + vfprintf(stderr,format,args); #endif - va_end(args); + va_end(args); } @@ -3943,70 +3985,71 @@ static void log_early_error(const char *format, ...) { */ static struct MAPLIST *getmappingitem(FILEREADER reader, void *fileid, - off_t *poffs, char *buf, int *psrc, s64 *psize) { - int src; - int dst; - char *p; - char *q; - char *pu; - char *pg; - int gotend; - struct MAPLIST *item; + off_t *poffs, char *buf, int *psrc, s64 *psize) +{ + int src; + int dst; + char *p; + char *q; + char *pu; + char *pg; + int gotend; + struct MAPLIST *item; - src = *psrc; - dst = 0; - /* allocate and get a full line */ - item = (struct MAPLIST*)ntfs_malloc(sizeof(struct MAPLIST)); - if (item) { - do { - gotend = 0; - while ((src < *psize) - && (buf[src] != '\n')) { - if (dst < LINESZ) - item->maptext[dst++] = buf[src]; - src++; - } - if (src >= *psize) { - *poffs += *psize; - *psize = reader(fileid, buf, (size_t)BUFSZ, *poffs); - src = 0; - } else { - gotend = 1; - src++; - item->maptext[dst] = '\0'; - dst = 0; - } - } while (*psize && ((item->maptext[0] == '#') || !gotend)); - if (gotend) { - pu = pg = (char*)NULL; - /* decompose into uid, gid and sid */ - p = item->maptext; - item->uidstr = item->maptext; - item->gidstr = strchr(item->uidstr, ':'); - if (item->gidstr) { - pu = item->gidstr++; - item->sidstr = strchr(item->gidstr, ':'); - if (item->sidstr) { - pg = item->sidstr++; - q = strchr(item->sidstr, ':'); - if (q) *q = 0; - } - } - if (pu && pg) - *pu = *pg = '\0'; - else { - log_early_error("Bad mapping item \"%s\"\n", - item->maptext); - free(item); - item = (struct MAPLIST*)NULL; - } - } else { - free(item); /* free unused item */ - item = (struct MAPLIST*)NULL; - } - } - *psrc = src; - return (item); + src = *psrc; + dst = 0; + /* allocate and get a full line */ + item = (struct MAPLIST*)ntfs_malloc(sizeof(struct MAPLIST)); + if (item) { + do { + gotend = 0; + while ((src < *psize) + && (buf[src] != '\n')) { + if (dst < LINESZ) + item->maptext[dst++] = buf[src]; + src++; + } + if (src >= *psize) { + *poffs += *psize; + *psize = reader(fileid, buf, (size_t)BUFSZ, *poffs); + src = 0; + } else { + gotend = 1; + src++; + item->maptext[dst] = '\0'; + dst = 0; + } + } while (*psize && ((item->maptext[0] == '#') || !gotend)); + if (gotend) { + pu = pg = (char*)NULL; + /* decompose into uid, gid and sid */ + p = item->maptext; + item->uidstr = item->maptext; + item->gidstr = strchr(item->uidstr, ':'); + if (item->gidstr) { + pu = item->gidstr++; + item->sidstr = strchr(item->gidstr, ':'); + if (item->sidstr) { + pg = item->sidstr++; + q = strchr(item->sidstr, ':'); + if (q) *q = 0; + } + } + if (pu && pg) + *pu = *pg = '\0'; + else { + log_early_error("Bad mapping item \"%s\"\n", + item->maptext); + free(item); + item = (struct MAPLIST*)NULL; + } + } else { + free(item); /* free unused item */ + item = (struct MAPLIST*)NULL; + } + } + *psrc = src; + return (item); } /* @@ -4024,35 +4067,36 @@ static struct MAPLIST *getmappingitem(FILEREADER reader, void *fileid, * entered the fuse loop yet. */ -struct MAPLIST *ntfs_read_mapping(FILEREADER reader, void *fileid) { - char buf[BUFSZ]; - struct MAPLIST *item; - struct MAPLIST *firstitem; - struct MAPLIST *lastitem; - int src; - off_t offs; - s64 size; +struct MAPLIST *ntfs_read_mapping(FILEREADER reader, void *fileid) +{ + char buf[BUFSZ]; + struct MAPLIST *item; + struct MAPLIST *firstitem; + struct MAPLIST *lastitem; + int src; + off_t offs; + s64 size; - firstitem = (struct MAPLIST*)NULL; - lastitem = (struct MAPLIST*)NULL; - offs = 0; - size = reader(fileid, buf, (size_t)BUFSZ, (off_t)0); - if (size > 0) { - src = 0; - do { - item = getmappingitem(reader, fileid, &offs, - buf, &src, &size); - if (item) { - item->next = (struct MAPLIST*)NULL; - if (lastitem) - lastitem->next = item; - else - firstitem = item; - lastitem = item; - } - } while (item); - } - return (firstitem); + firstitem = (struct MAPLIST*)NULL; + lastitem = (struct MAPLIST*)NULL; + offs = 0; + size = reader(fileid, buf, (size_t)BUFSZ, (off_t)0); + if (size > 0) { + src = 0; + do { + item = getmappingitem(reader, fileid, &offs, + buf, &src, &size); + if (item) { + item->next = (struct MAPLIST*)NULL; + if (lastitem) + lastitem->next = item; + else + firstitem = item; + lastitem = item; + } + } while (item); + } + return (firstitem); } /* @@ -4060,34 +4104,35 @@ struct MAPLIST *ntfs_read_mapping(FILEREADER reader, void *fileid) { * The only purpose is to facilitate the detection of memory leaks */ -void ntfs_free_mapping(struct MAPPING *mapping[]) { - struct MAPPING *user; - struct MAPPING *group; +void ntfs_free_mapping(struct MAPPING *mapping[]) +{ + struct MAPPING *user; + struct MAPPING *group; - /* free user mappings */ - while (mapping[MAPUSERS]) { - user = mapping[MAPUSERS]; - /* do not free SIDs used for group mappings */ - group = mapping[MAPGROUPS]; - while (group && (group->sid != user->sid)) - group = group->next; - if (!group) - free(user->sid); - /* free group list if any */ - if (user->grcnt) - free(user->groups); - /* unchain item and free */ - mapping[MAPUSERS] = user->next; - free(user); - } - /* free group mappings */ - while (mapping[MAPGROUPS]) { - group = mapping[MAPGROUPS]; - free(group->sid); - /* unchain item and free */ - mapping[MAPGROUPS] = group->next; - free(group); - } + /* free user mappings */ + while (mapping[MAPUSERS]) { + user = mapping[MAPUSERS]; + /* do not free SIDs used for group mappings */ + group = mapping[MAPGROUPS]; + while (group && (group->sid != user->sid)) + group = group->next; + if (!group) + free(user->sid); + /* free group list if any */ + if (user->grcnt) + free(user->groups); + /* unchain item and free */ + mapping[MAPUSERS] = user->next; + free(user); + } + /* free group mappings */ + while (mapping[MAPGROUPS]) { + group = mapping[MAPGROUPS]; + free(group->sid); + /* unchain item and free */ + mapping[MAPGROUPS] = group->next; + free(group); + } } @@ -4100,63 +4145,64 @@ void ntfs_free_mapping(struct MAPPING *mapping[]) { * file is on NTFS, and fuse is not recursion safe. */ -struct MAPPING *ntfs_do_user_mapping(struct MAPLIST *firstitem) { - struct MAPLIST *item; - struct MAPPING *firstmapping; - struct MAPPING *lastmapping; - struct MAPPING *mapping; - struct passwd *pwd; - SID *sid; - int uid; +struct MAPPING *ntfs_do_user_mapping(struct MAPLIST *firstitem) +{ + struct MAPLIST *item; + struct MAPPING *firstmapping; + struct MAPPING *lastmapping; + struct MAPPING *mapping; + struct passwd *pwd; + SID *sid; + int uid; - firstmapping = (struct MAPPING*)NULL; - lastmapping = (struct MAPPING*)NULL; - for (item = firstitem; item; item = item->next) { - if ((item->uidstr[0] >= '0') && (item->uidstr[0] <= '9')) - uid = atoi(item->uidstr); - else { - uid = 0; - if (item->uidstr[0]) { - pwd = getpwnam(item->uidstr); - if (pwd) - uid = pwd->pw_uid; - else - log_early_error("Invalid user \"%s\"\n", - item->uidstr); - } - } - /* - * Records with no uid and no gid are inserted - * to define the implicit mapping pattern - */ - if (uid - || (!item->uidstr[0] && !item->gidstr[0])) { - sid = encodesid(item->sidstr); - if (sid && !item->uidstr[0] && !item->gidstr[0] - && !ntfs_valid_pattern(sid)) { - ntfs_log_error("Bad implicit SID pattern %s\n", - item->sidstr); - sid = (SID*)NULL; - } - if (sid) { - mapping = - (struct MAPPING*) - ntfs_malloc(sizeof(struct MAPPING)); - if (mapping) { - mapping->sid = sid; - mapping->xid = uid; - mapping->grcnt = 0; - mapping->next = (struct MAPPING*)NULL; - if (lastmapping) - lastmapping->next = mapping; - else - firstmapping = mapping; - lastmapping = mapping; - } - } - } - } - return (firstmapping); + firstmapping = (struct MAPPING*)NULL; + lastmapping = (struct MAPPING*)NULL; + for (item = firstitem; item; item = item->next) { + if ((item->uidstr[0] >= '0') && (item->uidstr[0] <= '9')) + uid = atoi(item->uidstr); + else { + uid = 0; + if (item->uidstr[0]) { + pwd = getpwnam(item->uidstr); + if (pwd) + uid = pwd->pw_uid; + else + log_early_error("Invalid user \"%s\"\n", + item->uidstr); + } + } + /* + * Records with no uid and no gid are inserted + * to define the implicit mapping pattern + */ + if (uid + || (!item->uidstr[0] && !item->gidstr[0])) { + sid = encodesid(item->sidstr); + if (sid && !item->uidstr[0] && !item->gidstr[0] + && !ntfs_valid_pattern(sid)) { + ntfs_log_error("Bad implicit SID pattern %s\n", + item->sidstr); + sid = (SID*)NULL; + } + if (sid) { + mapping = + (struct MAPPING*) + ntfs_malloc(sizeof(struct MAPPING)); + if (mapping) { + mapping->sid = sid; + mapping->xid = uid; + mapping->grcnt = 0; + mapping->next = (struct MAPPING*)NULL; + if (lastmapping) + lastmapping->next = mapping; + else + firstmapping = mapping; + lastmapping = mapping; + } + } + } + } + return (firstmapping); } /* @@ -4171,69 +4217,70 @@ struct MAPPING *ntfs_do_user_mapping(struct MAPLIST *firstitem) { * file is on NTFS, and fuse is not recursion safe. */ -struct MAPPING *ntfs_do_group_mapping(struct MAPLIST *firstitem) { - struct MAPLIST *item; - struct MAPPING *firstmapping; - struct MAPPING *lastmapping; - struct MAPPING *mapping; - struct group *grp; - BOOL secondstep; - BOOL ok; - int step; - SID *sid; - int gid; +struct MAPPING *ntfs_do_group_mapping(struct MAPLIST *firstitem) +{ + struct MAPLIST *item; + struct MAPPING *firstmapping; + struct MAPPING *lastmapping; + struct MAPPING *mapping; + struct group *grp; + BOOL secondstep; + BOOL ok; + int step; + SID *sid; + int gid; - firstmapping = (struct MAPPING*)NULL; - lastmapping = (struct MAPPING*)NULL; - for (step=1; step<=2; step++) { - for (item = firstitem; item; item = item->next) { - secondstep = (item->uidstr[0] != '\0') - || !item->gidstr[0]; - ok = (step == 1 ? !secondstep : secondstep); - if ((item->gidstr[0] >= '0') - && (item->gidstr[0] <= '9')) - gid = atoi(item->gidstr); - else { - gid = 0; - if (item->gidstr[0]) { - grp = getgrnam(item->gidstr); - if (grp) - gid = grp->gr_gid; - else - log_early_error("Invalid group \"%s\"\n", - item->gidstr); - } - } - /* - * Records with no uid and no gid are inserted in the - * second step to define the implicit mapping pattern - */ - if (ok - && (gid - || (!item->uidstr[0] && !item->gidstr[0]))) { - sid = encodesid(item->sidstr); - if (sid && !item->uidstr[0] && !item->gidstr[0] - && !ntfs_valid_pattern(sid)) { - /* error already logged */ - sid = (SID*)NULL; - } - if (sid) { - mapping = (struct MAPPING*) - ntfs_malloc(sizeof(struct MAPPING)); - if (mapping) { - mapping->sid = sid; - mapping->xid = gid; - mapping->grcnt = 0; - mapping->next = (struct MAPPING*)NULL; - if (lastmapping) - lastmapping->next = mapping; - else - firstmapping = mapping; - lastmapping = mapping; - } - } - } - } - } - return (firstmapping); + firstmapping = (struct MAPPING*)NULL; + lastmapping = (struct MAPPING*)NULL; + for (step=1; step<=2; step++) { + for (item = firstitem; item; item = item->next) { + secondstep = (item->uidstr[0] != '\0') + || !item->gidstr[0]; + ok = (step == 1 ? !secondstep : secondstep); + if ((item->gidstr[0] >= '0') + && (item->gidstr[0] <= '9')) + gid = atoi(item->gidstr); + else { + gid = 0; + if (item->gidstr[0]) { + grp = getgrnam(item->gidstr); + if (grp) + gid = grp->gr_gid; + else + log_early_error("Invalid group \"%s\"\n", + item->gidstr); + } + } + /* + * Records with no uid and no gid are inserted in the + * second step to define the implicit mapping pattern + */ + if (ok + && (gid + || (!item->uidstr[0] && !item->gidstr[0]))) { + sid = encodesid(item->sidstr); + if (sid && !item->uidstr[0] && !item->gidstr[0] + && !ntfs_valid_pattern(sid)) { + /* error already logged */ + sid = (SID*)NULL; + } + if (sid) { + mapping = (struct MAPPING*) + ntfs_malloc(sizeof(struct MAPPING)); + if (mapping) { + mapping->sid = sid; + mapping->xid = gid; + mapping->grcnt = 0; + mapping->next = (struct MAPPING*)NULL; + if (lastmapping) + lastmapping->next = mapping; + else + firstmapping = mapping; + lastmapping = mapping; + } + } + } + } + } + return (firstmapping); } diff --git a/source/libntfs/acls.h b/source/libntfs/acls.h index 7e9e41cc..13e5dbd1 100644 --- a/source/libntfs/acls.h +++ b/source/libntfs/acls.h @@ -66,7 +66,7 @@ * when checking, check one is present */ -/* flags which are set to mean exec, write or read */ + /* flags which are set to mean exec, write or read */ #define FILE_READ (FILE_READ_DATA) #define FILE_WRITE (FILE_WRITE_DATA | FILE_APPEND_DATA \ @@ -77,8 +77,8 @@ | READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA) #define DIR_EXEC (FILE_TRAVERSE) -/* flags tested for meaning exec, write or read */ -/* tests for write allow for interpretation of a sticky bit */ + /* flags tested for meaning exec, write or read */ + /* tests for write allow for interpretation of a sticky bit */ #define FILE_GREAD (FILE_READ_DATA | GENERIC_READ) #define FILE_GWRITE (FILE_WRITE_DATA | FILE_APPEND_DATA | GENERIC_WRITE) @@ -87,19 +87,19 @@ #define DIR_GWRITE (FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY | GENERIC_WRITE) #define DIR_GEXEC (FILE_TRAVERSE | GENERIC_EXECUTE) -/* standard owner (and administrator) rights */ + /* standard owner (and administrator) rights */ #define OWNER_RIGHTS (DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER \ | SYNCHRONIZE \ | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES \ | FILE_READ_EA | FILE_WRITE_EA) -/* standard world rights */ + /* standard world rights */ #define WORLD_RIGHTS (READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_READ_EA \ | SYNCHRONIZE) -/* inheritance flags for files and directories */ + /* inheritance flags for files and directories */ #define FILE_INHERITANCE NO_PROPAGATE_INHERIT_ACE #define DIR_INHERITANCE (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE) @@ -125,11 +125,11 @@ typedef char BIGSID[40]; */ struct MAPLIST { - struct MAPLIST *next; - char *uidstr; /* uid text from the same record */ - char *gidstr; /* gid text from the same record */ - char *sidstr; /* sid text from the same record */ - char maptext[LINESZ + 1]; + struct MAPLIST *next; + char *uidstr; /* uid text from the same record */ + char *gidstr; /* gid text from the same record */ + char *sidstr; /* sid text from the same record */ + char maptext[LINESZ + 1]; }; typedef int (*FILEREADER)(void *fileid, char *buf, size_t size, off_t pos); @@ -157,9 +157,9 @@ int ntfs_sid_size(const SID * sid); unsigned int ntfs_attr_size(const char *attr); const SID *ntfs_find_usid(const struct MAPPING *usermapping, - uid_t uid, SID *pdefsid); + uid_t uid, SID *pdefsid); const SID *ntfs_find_gsid(const struct MAPPING *groupmapping, - gid_t gid, SID *pdefsid); + gid_t gid, SID *pdefsid); uid_t ntfs_find_user(const struct MAPPING *usermapping, const SID *usid); gid_t ntfs_find_group(const struct MAPPING *groupmapping, const SID * gsid); const SID *ntfs_acl_owner(const char *secattr); @@ -170,28 +170,28 @@ BOOL ntfs_valid_posix(const struct POSIX_SECURITY *pxdesc); void ntfs_sort_posix(struct POSIX_SECURITY *pxdesc); int ntfs_merge_mode_posix(struct POSIX_SECURITY *pxdesc, mode_t mode); struct POSIX_SECURITY *ntfs_build_inherited_posix( - const struct POSIX_SECURITY *pxdesc, mode_t mode, - mode_t umask, BOOL isdir); + const struct POSIX_SECURITY *pxdesc, mode_t mode, + mode_t umask, BOOL isdir); struct POSIX_SECURITY *ntfs_replace_acl(const struct POSIX_SECURITY *oldpxdesc, - const struct POSIX_ACL *newacl, int count, BOOL deflt); + const struct POSIX_ACL *newacl, int count, BOOL deflt); struct POSIX_SECURITY *ntfs_build_permissions_posix( - struct MAPPING* const mapping[], - const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir); + struct MAPPING* const mapping[], + const char *securattr, + const SID *usid, const SID *gsid, BOOL isdir); struct POSIX_SECURITY *ntfs_merge_descr_posix(const struct POSIX_SECURITY *first, - const struct POSIX_SECURITY *second); + const struct POSIX_SECURITY *second); char *ntfs_build_descr_posix(struct MAPPING* const mapping[], - struct POSIX_SECURITY *pxdesc, - int isdir, const SID *usid, const SID *gsid); + struct POSIX_SECURITY *pxdesc, + int isdir, const SID *usid, const SID *gsid); #endif /* POSIXACLS */ int ntfs_inherit_acl(const ACL *oldacl, ACL *newacl, - const SID *usid, const SID *gsid, BOOL fordir); + const SID *usid, const SID *gsid, BOOL fordir); int ntfs_build_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir); + const SID *usid, const SID *gsid, BOOL isdir); char *ntfs_build_descr(mode_t mode, - int isdir, const SID * usid, const SID * gsid); + int isdir, const SID * usid, const SID * gsid); struct MAPLIST *ntfs_read_mapping(FILEREADER reader, void *fileid); struct MAPPING *ntfs_do_user_mapping(struct MAPLIST *firstitem); struct MAPPING *ntfs_do_group_mapping(struct MAPLIST *firstitem); diff --git a/source/libntfs/attrib.c b/source/libntfs/attrib.c index bb3bce9c..41e4dcf0 100644 --- a/source/libntfs/attrib.c +++ b/source/libntfs/attrib.c @@ -68,41 +68,42 @@ ntfschar AT_UNNAMED[] = { const_cpu_to_le16('\0') }; ntfschar STREAM_SDS[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('S'), - const_cpu_to_le16('D'), - const_cpu_to_le16('S'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('S'), + const_cpu_to_le16('D'), + const_cpu_to_le16('S'), + const_cpu_to_le16('\0') }; ntfschar TXF_DATA[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('T'), - const_cpu_to_le16('X'), - const_cpu_to_le16('F'), - const_cpu_to_le16('_'), - const_cpu_to_le16('D'), - const_cpu_to_le16('A'), - const_cpu_to_le16('T'), - const_cpu_to_le16('A'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('T'), + const_cpu_to_le16('X'), + const_cpu_to_le16('F'), + const_cpu_to_le16('_'), + const_cpu_to_le16('D'), + const_cpu_to_le16('A'), + const_cpu_to_le16('T'), + const_cpu_to_le16('A'), + const_cpu_to_le16('\0') }; -static int NAttrFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) { - if (na->type == AT_DATA && na->name == AT_UNNAMED) - return (na->ni->flags & flag); - return 0; +static int NAttrFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) +{ + if (na->type == AT_DATA && na->name == AT_UNNAMED) + return (na->ni->flags & flag); + return 0; } -static void NAttrSetFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) { - if (na->type == AT_DATA && na->name == AT_UNNAMED) - na->ni->flags |= flag; - else - ntfs_log_trace("Denied setting flag %d for not unnamed data " - "attribute\n", flag); +static void NAttrSetFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) +{ + if (na->type == AT_DATA && na->name == AT_UNNAMED) + na->ni->flags |= flag; + else + ntfs_log_trace("Denied setting flag %d for not unnamed data " + "attribute\n", flag); } -static void NAttrClearFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) { - if (na->type == AT_DATA && na->name == AT_UNNAMED) - na->ni->flags &= ~flag; +static void NAttrClearFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) +{ + if (na->type == AT_DATA && na->name == AT_UNNAMED) + na->ni->flags &= ~flag; } #define GenNAttrIno(func_name, flag) \ @@ -122,186 +123,188 @@ GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) * * Returns: */ -s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a) { - if (!a) { - errno = EINVAL; - return 0; - } - errno = 0; - if (a->non_resident) - return sle64_to_cpu(a->data_size); - - return (s64)le32_to_cpu(a->value_length); +s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a) +{ + if (!a) { + errno = EINVAL; + return 0; + } + errno = 0; + if (a->non_resident) + return sle64_to_cpu(a->data_size); + + return (s64)le32_to_cpu(a->value_length); } /** * ntfs_get_attribute_value - Get a copy of an attribute - * @vol: - * @a: - * @b: + * @vol: + * @a: + * @b: * * Description... * * Returns: */ s64 ntfs_get_attribute_value(const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b) { - runlist *rl; - s64 total, r; - int i; + const ATTR_RECORD *a, u8 *b) +{ + runlist *rl; + s64 total, r; + int i; - /* Sanity checks. */ - if (!vol || !a || !b) { - errno = EINVAL; - return 0; - } - /* Complex attribute? */ - /* - * Ignore the flags in case they are not zero for an attribute list - * attribute. Windows does not complain about invalid flags and chkdsk - * does not detect or fix them so we need to cope with it, too. - */ - if (a->type != AT_ATTRIBUTE_LIST && a->flags) { - ntfs_log_error("Non-zero (%04x) attribute flags. Cannot handle " - "this yet.\n", le16_to_cpu(a->flags)); - errno = EOPNOTSUPP; - return 0; - } - if (!a->non_resident) { - /* Attribute is resident. */ + /* Sanity checks. */ + if (!vol || !a || !b) { + errno = EINVAL; + return 0; + } + /* Complex attribute? */ + /* + * Ignore the flags in case they are not zero for an attribute list + * attribute. Windows does not complain about invalid flags and chkdsk + * does not detect or fix them so we need to cope with it, too. + */ + if (a->type != AT_ATTRIBUTE_LIST && a->flags) { + ntfs_log_error("Non-zero (%04x) attribute flags. Cannot handle " + "this yet.\n", le16_to_cpu(a->flags)); + errno = EOPNOTSUPP; + return 0; + } + if (!a->non_resident) { + /* Attribute is resident. */ - /* Sanity check. */ - if (le32_to_cpu(a->value_length) + le16_to_cpu(a->value_offset) - > le32_to_cpu(a->length)) { - return 0; - } + /* Sanity check. */ + if (le32_to_cpu(a->value_length) + le16_to_cpu(a->value_offset) + > le32_to_cpu(a->length)) { + return 0; + } - memcpy(b, (const char*)a + le16_to_cpu(a->value_offset), - le32_to_cpu(a->value_length)); - errno = 0; - return (s64)le32_to_cpu(a->value_length); - } + memcpy(b, (const char*)a + le16_to_cpu(a->value_offset), + le32_to_cpu(a->value_length)); + errno = 0; + return (s64)le32_to_cpu(a->value_length); + } - /* Attribute is not resident. */ + /* Attribute is not resident. */ - /* If no data, return 0. */ - if (!(a->data_size)) { - errno = 0; - return 0; - } - /* - * FIXME: What about attribute lists?!? (AIA) - */ - /* Decompress the mapping pairs array into a runlist. */ - rl = ntfs_mapping_pairs_decompress(vol, a, NULL); - if (!rl) { - errno = EINVAL; - return 0; - } - /* - * FIXED: We were overflowing here in a nasty fashion when we - * reach the last cluster in the runlist as the buffer will - * only be big enough to hold data_size bytes while we are - * reading in allocated_size bytes which is usually larger - * than data_size, since the actual data is unlikely to have a - * size equal to a multiple of the cluster size! - * FIXED2: We were also overflowing here in the same fashion - * when the data_size was more than one run smaller than the - * allocated size which happens with Windows XP sometimes. - */ - /* Now load all clusters in the runlist into b. */ - for (i = 0, total = 0; rl[i].length; i++) { - if (total + (rl[i].length << vol->cluster_size_bits) >= - sle64_to_cpu(a->data_size)) { - unsigned char *intbuf = NULL; - /* - * We have reached the last run so we were going to - * overflow when executing the ntfs_pread() which is - * BAAAAAAAD! - * Temporary fix: - * Allocate a new buffer with size: - * rl[i].length << vol->cluster_size_bits, do the - * read into our buffer, then memcpy the correct - * amount of data into the caller supplied buffer, - * free our buffer, and continue. - * We have reached the end of data size so we were - * going to overflow in the same fashion. - * Temporary fix: same as above. - */ - intbuf = ntfs_malloc(rl[i].length << vol->cluster_size_bits); - if (!intbuf) { - free(rl); - return 0; - } - /* - * FIXME: If compressed file: Only read if lcn != -1. - * Otherwise, we are dealing with a sparse run and we - * just memset the user buffer to 0 for the length of - * the run, which should be 16 (= compression unit - * size). - * FIXME: Really only when file is compressed, or can - * we have sparse runs in uncompressed files as well? - * - Yes we can, in sparse files! But not necessarily - * size of 16, just run length. - */ - r = ntfs_pread(vol->dev, rl[i].lcn << - vol->cluster_size_bits, rl[i].length << - vol->cluster_size_bits, intbuf); - if (r != rl[i].length << vol->cluster_size_bits) { + /* If no data, return 0. */ + if (!(a->data_size)) { + errno = 0; + return 0; + } + /* + * FIXME: What about attribute lists?!? (AIA) + */ + /* Decompress the mapping pairs array into a runlist. */ + rl = ntfs_mapping_pairs_decompress(vol, a, NULL); + if (!rl) { + errno = EINVAL; + return 0; + } + /* + * FIXED: We were overflowing here in a nasty fashion when we + * reach the last cluster in the runlist as the buffer will + * only be big enough to hold data_size bytes while we are + * reading in allocated_size bytes which is usually larger + * than data_size, since the actual data is unlikely to have a + * size equal to a multiple of the cluster size! + * FIXED2: We were also overflowing here in the same fashion + * when the data_size was more than one run smaller than the + * allocated size which happens with Windows XP sometimes. + */ + /* Now load all clusters in the runlist into b. */ + for (i = 0, total = 0; rl[i].length; i++) { + if (total + (rl[i].length << vol->cluster_size_bits) >= + sle64_to_cpu(a->data_size)) { + unsigned char *intbuf = NULL; + /* + * We have reached the last run so we were going to + * overflow when executing the ntfs_pread() which is + * BAAAAAAAD! + * Temporary fix: + * Allocate a new buffer with size: + * rl[i].length << vol->cluster_size_bits, do the + * read into our buffer, then memcpy the correct + * amount of data into the caller supplied buffer, + * free our buffer, and continue. + * We have reached the end of data size so we were + * going to overflow in the same fashion. + * Temporary fix: same as above. + */ + intbuf = ntfs_malloc(rl[i].length << vol->cluster_size_bits); + if (!intbuf) { + free(rl); + return 0; + } + /* + * FIXME: If compressed file: Only read if lcn != -1. + * Otherwise, we are dealing with a sparse run and we + * just memset the user buffer to 0 for the length of + * the run, which should be 16 (= compression unit + * size). + * FIXME: Really only when file is compressed, or can + * we have sparse runs in uncompressed files as well? + * - Yes we can, in sparse files! But not necessarily + * size of 16, just run length. + */ + r = ntfs_pread(vol->dev, rl[i].lcn << + vol->cluster_size_bits, rl[i].length << + vol->cluster_size_bits, intbuf); + if (r != rl[i].length << vol->cluster_size_bits) { #define ESTR "Error reading attribute value" - if (r == -1) - ntfs_log_perror(ESTR); - else if (r < rl[i].length << - vol->cluster_size_bits) { - ntfs_log_debug(ESTR ": Ran out of input data.\n"); - errno = EIO; - } else { - ntfs_log_debug(ESTR ": unknown error\n"); - errno = EIO; - } + if (r == -1) + ntfs_log_perror(ESTR); + else if (r < rl[i].length << + vol->cluster_size_bits) { + ntfs_log_debug(ESTR ": Ran out of input data.\n"); + errno = EIO; + } else { + ntfs_log_debug(ESTR ": unknown error\n"); + errno = EIO; + } #undef ESTR - free(rl); - free(intbuf); - return 0; - } - memcpy(b + total, intbuf, sle64_to_cpu(a->data_size) - - total); - free(intbuf); - total = sle64_to_cpu(a->data_size); - break; - } - /* - * FIXME: If compressed file: Only read if lcn != -1. - * Otherwise, we are dealing with a sparse run and we just - * memset the user buffer to 0 for the length of the run, which - * should be 16 (= compression unit size). - * FIXME: Really only when file is compressed, or can - * we have sparse runs in uncompressed files as well? - * - Yes we can, in sparse files! But not necessarily size of - * 16, just run length. - */ - r = ntfs_pread(vol->dev, rl[i].lcn << vol->cluster_size_bits, - rl[i].length << vol->cluster_size_bits, - b + total); - if (r != rl[i].length << vol->cluster_size_bits) { + free(rl); + free(intbuf); + return 0; + } + memcpy(b + total, intbuf, sle64_to_cpu(a->data_size) - + total); + free(intbuf); + total = sle64_to_cpu(a->data_size); + break; + } + /* + * FIXME: If compressed file: Only read if lcn != -1. + * Otherwise, we are dealing with a sparse run and we just + * memset the user buffer to 0 for the length of the run, which + * should be 16 (= compression unit size). + * FIXME: Really only when file is compressed, or can + * we have sparse runs in uncompressed files as well? + * - Yes we can, in sparse files! But not necessarily size of + * 16, just run length. + */ + r = ntfs_pread(vol->dev, rl[i].lcn << vol->cluster_size_bits, + rl[i].length << vol->cluster_size_bits, + b + total); + if (r != rl[i].length << vol->cluster_size_bits) { #define ESTR "Error reading attribute value" - if (r == -1) - ntfs_log_perror(ESTR); - else if (r < rl[i].length << vol->cluster_size_bits) { - ntfs_log_debug(ESTR ": Ran out of input data.\n"); - errno = EIO; - } else { - ntfs_log_debug(ESTR ": unknown error\n"); - errno = EIO; - } + if (r == -1) + ntfs_log_perror(ESTR); + else if (r < rl[i].length << vol->cluster_size_bits) { + ntfs_log_debug(ESTR ": Ran out of input data.\n"); + errno = EIO; + } else { + ntfs_log_debug(ESTR ": unknown error\n"); + errno = EIO; + } #undef ESTR - free(rl); - return 0; - } - total += r; - } - free(rl); - return total; + free(rl); + return 0; + } + total += r; + } + free(rl); + return total; } /* Already cleaned up code below, but still look for FIXME:... */ @@ -317,15 +320,16 @@ s64 ntfs_get_attribute_value(const ntfs_volume *vol, * Initialize the ntfs attribute @na with @ni, @type, @name, and @name_len. */ static void __ntfs_attr_init(ntfs_attr *na, ntfs_inode *ni, - const ATTR_TYPES type, ntfschar *name, const u32 name_len) { - na->rl = NULL; - na->ni = ni; - na->type = type; - na->name = name; - if (name) - na->name_len = name_len; - else - na->name_len = 0; + const ATTR_TYPES type, ntfschar *name, const u32 name_len) +{ + na->rl = NULL; + na->ni = ni; + na->type = type; + na->name = name; + if (name) + na->name_len = name_len; + else + na->name_len = 0; } /** @@ -344,36 +348,37 @@ static void __ntfs_attr_init(ntfs_attr *na, ntfs_inode *ni, * Final initialization for an ntfs attribute. */ void ntfs_attr_init(ntfs_attr *na, const BOOL non_resident, - const ATTR_FLAGS data_flags, - const BOOL encrypted, const BOOL sparse, - const s64 allocated_size, const s64 data_size, - const s64 initialized_size, const s64 compressed_size, - const u8 compression_unit) { - if (!NAttrInitialized(na)) { - na->data_flags = data_flags; - if (non_resident) - NAttrSetNonResident(na); - if (data_flags & ATTR_COMPRESSION_MASK) - NAttrSetCompressed(na); - if (encrypted) - NAttrSetEncrypted(na); - if (sparse) - NAttrSetSparse(na); - na->allocated_size = allocated_size; - na->data_size = data_size; - na->initialized_size = initialized_size; - if ((data_flags & ATTR_COMPRESSION_MASK) || sparse) { - ntfs_volume *vol = na->ni->vol; + const ATTR_FLAGS data_flags, + const BOOL encrypted, const BOOL sparse, + const s64 allocated_size, const s64 data_size, + const s64 initialized_size, const s64 compressed_size, + const u8 compression_unit) +{ + if (!NAttrInitialized(na)) { + na->data_flags = data_flags; + if (non_resident) + NAttrSetNonResident(na); + if (data_flags & ATTR_COMPRESSION_MASK) + NAttrSetCompressed(na); + if (encrypted) + NAttrSetEncrypted(na); + if (sparse) + NAttrSetSparse(na); + na->allocated_size = allocated_size; + na->data_size = data_size; + na->initialized_size = initialized_size; + if ((data_flags & ATTR_COMPRESSION_MASK) || sparse) { + ntfs_volume *vol = na->ni->vol; - na->compressed_size = compressed_size; - na->compression_block_clusters = 1 << compression_unit; - na->compression_block_size = 1 << (compression_unit + - vol->cluster_size_bits); - na->compression_block_size_bits = ffs( - na->compression_block_size) - 1; - } - NAttrSetInitialized(na); - } + na->compressed_size = compressed_size; + na->compression_block_clusters = 1 << compression_unit; + na->compression_block_size = 1 << (compression_unit + + vol->cluster_size_bits); + na->compression_block_size_bits = ffs( + na->compression_block_size) - 1; + } + NAttrSetInitialized(na); + } } /** @@ -392,125 +397,126 @@ void ntfs_attr_init(ntfs_attr *na, const BOOL non_resident, * both those cases @name_len is not used at all. */ ntfs_attr *ntfs_attr_open(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len) { - ntfs_attr_search_ctx *ctx; - ntfs_attr *na = NULL; - ntfschar *newname = NULL; - ATTR_RECORD *a; - BOOL cs; + ntfschar *name, u32 name_len) +{ + ntfs_attr_search_ctx *ctx; + ntfs_attr *na = NULL; + ntfschar *newname = NULL; + ATTR_RECORD *a; + BOOL cs; - ntfs_log_enter("Entering for inode %lld, attr 0x%x.\n", - (unsigned long long)ni->mft_no, type); + ntfs_log_enter("Entering for inode %lld, attr 0x%x.\n", + (unsigned long long)ni->mft_no, type); + + if (!ni || !ni->vol || !ni->mrec) { + errno = EINVAL; + goto out; + } + na = ntfs_calloc(sizeof(ntfs_attr)); + if (!na) + goto out; + if (name && name != AT_UNNAMED && name != NTFS_INDEX_I30) { + name = ntfs_ucsndup(name, name_len); + if (!name) + goto err_out; + newname = name; + } - if (!ni || !ni->vol || !ni->mrec) { - errno = EINVAL; - goto out; - } - na = ntfs_calloc(sizeof(ntfs_attr)); - if (!na) - goto out; - if (name && name != AT_UNNAMED && name != NTFS_INDEX_I30) { - name = ntfs_ucsndup(name, name_len); - if (!name) - goto err_out; - newname = name; - } + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + goto err_out; - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - goto err_out; + if (ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx)) + goto put_err_out; - if (ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx)) - goto put_err_out; + a = ctx->attr; + + if (!name) { + if (a->name_length) { + name = ntfs_ucsndup((ntfschar*)((u8*)a + le16_to_cpu( + a->name_offset)), a->name_length); + if (!name) + goto put_err_out; + newname = name; + name_len = a->name_length; + } else { + name = AT_UNNAMED; + name_len = 0; + } + } + + __ntfs_attr_init(na, ni, type, name, name_len); + + /* + * Wipe the flags in case they are not zero for an attribute list + * attribute. Windows does not complain about invalid flags and chkdsk + * does not detect or fix them so we need to cope with it, too. + */ + if (type == AT_ATTRIBUTE_LIST) + a->flags = 0; - a = ctx->attr; + if ((type == AT_DATA) && !a->initialized_size) { + /* + * Define/redefine the compression state if stream is + * empty, based on the compression mark on parent + * directory (for unnamed data streams) or on current + * inode (for named data streams). The compression mark + * may change any time, the compression state can only + * change when stream is wiped out. + */ + a->flags &= ~ATTR_COMPRESSION_MASK; + if (na->ni->flags & FILE_ATTR_COMPRESSED) + a->flags |= ATTR_IS_COMPRESSED; + } + + cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE); + + if (na->type == AT_DATA && na->name == AT_UNNAMED && + ((!(a->flags & ATTR_IS_SPARSE) != !NAttrSparse(na)) || + (!(a->flags & ATTR_IS_ENCRYPTED) != !NAttrEncrypted(na)))) { + errno = EIO; + ntfs_log_perror("Inode %lld has corrupt attribute flags " + "(0x%x <> 0x%x)",(unsigned long long)ni->mft_no, + a->flags, na->ni->flags); + goto put_err_out; + } - if (!name) { - if (a->name_length) { - name = ntfs_ucsndup((ntfschar*)((u8*)a + le16_to_cpu( - a->name_offset)), a->name_length); - if (!name) - goto put_err_out; - newname = name; - name_len = a->name_length; - } else { - name = AT_UNNAMED; - name_len = 0; - } - } - - __ntfs_attr_init(na, ni, type, name, name_len); - - /* - * Wipe the flags in case they are not zero for an attribute list - * attribute. Windows does not complain about invalid flags and chkdsk - * does not detect or fix them so we need to cope with it, too. - */ - if (type == AT_ATTRIBUTE_LIST) - a->flags = 0; - - if ((type == AT_DATA) && !a->initialized_size) { - /* - * Define/redefine the compression state if stream is - * empty, based on the compression mark on parent - * directory (for unnamed data streams) or on current - * inode (for named data streams). The compression mark - * may change any time, the compression state can only - * change when stream is wiped out. - */ - a->flags &= ~ATTR_COMPRESSION_MASK; - if (na->ni->flags & FILE_ATTR_COMPRESSED) - a->flags |= ATTR_IS_COMPRESSED; - } - - cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE); - - if (na->type == AT_DATA && na->name == AT_UNNAMED && - ((!(a->flags & ATTR_IS_SPARSE) != !NAttrSparse(na)) || - (!(a->flags & ATTR_IS_ENCRYPTED) != !NAttrEncrypted(na)))) { - errno = EIO; - ntfs_log_perror("Inode %lld has corrupt attribute flags " - "(0x%x <> 0x%x)",(unsigned long long)ni->mft_no, - a->flags, na->ni->flags); - goto put_err_out; - } - - if (a->non_resident) { - if ((a->flags & ATTR_COMPRESSION_MASK) - && !a->compression_unit) { - errno = EIO; - ntfs_log_perror("Compressed inode %lld attr 0x%x has " - "no compression unit", - (unsigned long long)ni->mft_no, type); - goto put_err_out; - } - ntfs_attr_init(na, TRUE, a->flags, - a->flags & ATTR_IS_ENCRYPTED, - a->flags & ATTR_IS_SPARSE, - sle64_to_cpu(a->allocated_size), - sle64_to_cpu(a->data_size), - sle64_to_cpu(a->initialized_size), - cs ? sle64_to_cpu(a->compressed_size) : 0, - cs ? a->compression_unit : 0); - } else { - s64 l = le32_to_cpu(a->value_length); - ntfs_attr_init(na, FALSE, a->flags, - a->flags & ATTR_IS_ENCRYPTED, - a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l, - cs ? (l + 7) & ~7 : 0, 0); - } - ntfs_attr_put_search_ctx(ctx); + if (a->non_resident) { + if ((a->flags & ATTR_COMPRESSION_MASK) + && !a->compression_unit) { + errno = EIO; + ntfs_log_perror("Compressed inode %lld attr 0x%x has " + "no compression unit", + (unsigned long long)ni->mft_no, type); + goto put_err_out; + } + ntfs_attr_init(na, TRUE, a->flags, + a->flags & ATTR_IS_ENCRYPTED, + a->flags & ATTR_IS_SPARSE, + sle64_to_cpu(a->allocated_size), + sle64_to_cpu(a->data_size), + sle64_to_cpu(a->initialized_size), + cs ? sle64_to_cpu(a->compressed_size) : 0, + cs ? a->compression_unit : 0); + } else { + s64 l = le32_to_cpu(a->value_length); + ntfs_attr_init(na, FALSE, a->flags, + a->flags & ATTR_IS_ENCRYPTED, + a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l, + cs ? (l + 7) & ~7 : 0, 0); + } + ntfs_attr_put_search_ctx(ctx); out: - ntfs_log_leave("\n"); - return na; + ntfs_log_leave("\n"); + return na; put_err_out: - ntfs_attr_put_search_ctx(ctx); + ntfs_attr_put_search_ctx(ctx); err_out: - free(newname); - free(na); - na = NULL; - goto out; + free(newname); + free(na); + na = NULL; + goto out; } /** @@ -520,16 +526,17 @@ err_out: * Release all memory associated with the ntfs attribute @na and then release * @na itself. */ -void ntfs_attr_close(ntfs_attr *na) { - if (!na) - return; - if (NAttrNonResident(na) && na->rl) - free(na->rl); - /* Don't release if using an internal constant. */ - if (na->name != AT_UNNAMED && na->name != NTFS_INDEX_I30 - && na->name != STREAM_SDS) - free(na->name); - free(na); +void ntfs_attr_close(ntfs_attr *na) +{ + if (!na) + return; + if (NAttrNonResident(na) && na->rl) + free(na->rl); + /* Don't release if using an internal constant. */ + if (na->name != AT_UNNAMED && na->name != NTFS_INDEX_I30 + && na->name != STREAM_SDS) + free(na->name); + free(na); } /** @@ -541,38 +548,39 @@ void ntfs_attr_close(ntfs_attr *na) { * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) { - LCN lcn; - ntfs_attr_search_ctx *ctx; +int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) +{ + LCN lcn; + ntfs_attr_search_ctx *ctx; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn 0x%llx.\n", - (unsigned long long)na->ni->mft_no, na->type, (long long)vcn); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn 0x%llx.\n", + (unsigned long long)na->ni->mft_no, na->type, (long long)vcn); - lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); - if (lcn >= 0 || lcn == LCN_HOLE || lcn == LCN_ENOENT) - return 0; + lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); + if (lcn >= 0 || lcn == LCN_HOLE || lcn == LCN_ENOENT) + return 0; - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; - /* Find the attribute in the mft record. */ - if (!ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - vcn, NULL, 0, ctx)) { - runlist_element *rl; + /* Find the attribute in the mft record. */ + if (!ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + vcn, NULL, 0, ctx)) { + runlist_element *rl; - /* Decode the runlist. */ - rl = ntfs_mapping_pairs_decompress(na->ni->vol, ctx->attr, - na->rl); - if (rl) { - na->rl = rl; - ntfs_attr_put_search_ctx(ctx); - return 0; - } - } - - ntfs_attr_put_search_ctx(ctx); - return -1; + /* Decode the runlist. */ + rl = ntfs_mapping_pairs_decompress(na->ni->vol, ctx->attr, + na->rl); + if (rl) { + na->rl = rl; + ntfs_attr_put_search_ctx(ctx); + return 0; + } + } + + ntfs_attr_put_search_ctx(ctx); + return -1; } /** @@ -587,96 +595,97 @@ int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) { * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_whole_runlist(ntfs_attr *na) { - VCN next_vcn, last_vcn, highest_vcn; - ntfs_attr_search_ctx *ctx; - ntfs_volume *vol = na->ni->vol; - ATTR_RECORD *a; - int ret = -1; +int ntfs_attr_map_whole_runlist(ntfs_attr *na) +{ + VCN next_vcn, last_vcn, highest_vcn; + ntfs_attr_search_ctx *ctx; + ntfs_volume *vol = na->ni->vol; + ATTR_RECORD *a; + int ret = -1; - ntfs_log_enter("Entering for inode %llu, attr 0x%x.\n", - (unsigned long long)na->ni->mft_no, na->type); + ntfs_log_enter("Entering for inode %llu, attr 0x%x.\n", + (unsigned long long)na->ni->mft_no, na->type); - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto out; + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + goto out; - /* Map all attribute extents one by one. */ - next_vcn = last_vcn = highest_vcn = 0; - a = NULL; - while (1) { - runlist_element *rl; + /* Map all attribute extents one by one. */ + next_vcn = last_vcn = highest_vcn = 0; + a = NULL; + while (1) { + runlist_element *rl; - int not_mapped = 0; - if (ntfs_rl_vcn_to_lcn(na->rl, next_vcn) == LCN_RL_NOT_MAPPED) - not_mapped = 1; + int not_mapped = 0; + if (ntfs_rl_vcn_to_lcn(na->rl, next_vcn) == LCN_RL_NOT_MAPPED) + not_mapped = 1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, next_vcn, NULL, 0, ctx)) - break; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, next_vcn, NULL, 0, ctx)) + break; - a = ctx->attr; + a = ctx->attr; - if (not_mapped) { - /* Decode the runlist. */ - rl = ntfs_mapping_pairs_decompress(na->ni->vol, - a, na->rl); - if (!rl) - goto err_out; - na->rl = rl; - } + if (not_mapped) { + /* Decode the runlist. */ + rl = ntfs_mapping_pairs_decompress(na->ni->vol, + a, na->rl); + if (!rl) + goto err_out; + na->rl = rl; + } - /* Are we in the first extent? */ - if (!next_vcn) { - if (a->lowest_vcn) { - errno = EIO; - ntfs_log_perror("First extent of inode %llu " - "attribute has non-zero lowest_vcn", - (unsigned long long)na->ni->mft_no); - goto err_out; - } - /* Get the last vcn in the attribute. */ - last_vcn = sle64_to_cpu(a->allocated_size) >> - vol->cluster_size_bits; - } + /* Are we in the first extent? */ + if (!next_vcn) { + if (a->lowest_vcn) { + errno = EIO; + ntfs_log_perror("First extent of inode %llu " + "attribute has non-zero lowest_vcn", + (unsigned long long)na->ni->mft_no); + goto err_out; + } + /* Get the last vcn in the attribute. */ + last_vcn = sle64_to_cpu(a->allocated_size) >> + vol->cluster_size_bits; + } - /* Get the lowest vcn for the next extent. */ - highest_vcn = sle64_to_cpu(a->highest_vcn); - next_vcn = highest_vcn + 1; + /* Get the lowest vcn for the next extent. */ + highest_vcn = sle64_to_cpu(a->highest_vcn); + next_vcn = highest_vcn + 1; - /* Only one extent or error, which we catch below. */ - if (next_vcn <= 0) { - errno = ENOENT; - break; - } + /* Only one extent or error, which we catch below. */ + if (next_vcn <= 0) { + errno = ENOENT; + break; + } - /* Avoid endless loops due to corruption. */ - if (next_vcn < sle64_to_cpu(a->lowest_vcn)) { - errno = EIO; - ntfs_log_perror("Inode %llu has corrupt attribute list", - (unsigned long long)na->ni->mft_no); - goto err_out; - } - } - if (!a) { - ntfs_log_perror("Couldn't find attribute for runlist mapping"); - goto err_out; - } - if (highest_vcn && highest_vcn != last_vcn - 1) { - errno = EIO; - ntfs_log_perror("Failed to load full runlist: inode: %llu " - "highest_vcn: 0x%llx last_vcn: 0x%llx", - (unsigned long long)na->ni->mft_no, - (long long)highest_vcn, (long long)last_vcn); - goto err_out; - } - if (errno == ENOENT) - ret = 0; -err_out: - ntfs_attr_put_search_ctx(ctx); + /* Avoid endless loops due to corruption. */ + if (next_vcn < sle64_to_cpu(a->lowest_vcn)) { + errno = EIO; + ntfs_log_perror("Inode %llu has corrupt attribute list", + (unsigned long long)na->ni->mft_no); + goto err_out; + } + } + if (!a) { + ntfs_log_perror("Couldn't find attribute for runlist mapping"); + goto err_out; + } + if (highest_vcn && highest_vcn != last_vcn - 1) { + errno = EIO; + ntfs_log_perror("Failed to load full runlist: inode: %llu " + "highest_vcn: 0x%llx last_vcn: 0x%llx", + (unsigned long long)na->ni->mft_no, + (long long)highest_vcn, (long long)last_vcn); + goto err_out; + } + if (errno == ENOENT) + ret = 0; +err_out: + ntfs_attr_put_search_ctx(ctx); out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } /** @@ -700,33 +709,34 @@ out: * -4 = LCN_EINVAL Input parameter error. * -5 = LCN_EIO Corrupt fs, disk i/o error, or not enough memory. */ -LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn) { - LCN lcn; - BOOL is_retry = FALSE; +LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn) +{ + LCN lcn; + BOOL is_retry = FALSE; - if (!na || !NAttrNonResident(na) || vcn < 0) - return (LCN)LCN_EINVAL; + if (!na || !NAttrNonResident(na) || vcn < 0) + return (LCN)LCN_EINVAL; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long - long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long + long)na->ni->mft_no, na->type); retry: - /* Convert vcn to lcn. If that fails map the runlist and retry once. */ - lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); - if (lcn >= 0) - return lcn; - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If the attempt to map the runlist failed, or we are getting - * LCN_RL_NOT_MAPPED despite having mapped the attribute extent - * successfully, something is really badly wrong... - */ - if (!is_retry || lcn == (LCN)LCN_RL_NOT_MAPPED) - return (LCN)LCN_EIO; - /* lcn contains the appropriate error code. */ - return lcn; + /* Convert vcn to lcn. If that fails map the runlist and retry once. */ + lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); + if (lcn >= 0) + return lcn; + if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { + is_retry = TRUE; + goto retry; + } + /* + * If the attempt to map the runlist failed, or we are getting + * LCN_RL_NOT_MAPPED despite having mapped the attribute extent + * successfully, something is really badly wrong... + */ + if (!is_retry || lcn == (LCN)LCN_RL_NOT_MAPPED) + return (LCN)LCN_EIO; + /* lcn contains the appropriate error code. */ + return lcn; } /** @@ -749,273 +759,275 @@ retry: * ENOMEM Not enough memory. * EIO I/O error or corrupt metadata. */ -runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn) { - runlist_element *rl; - BOOL is_retry = FALSE; +runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn) +{ + runlist_element *rl; + BOOL is_retry = FALSE; - if (!na || !NAttrNonResident(na) || vcn < 0) { - errno = EINVAL; - return NULL; - } + if (!na || !NAttrNonResident(na) || vcn < 0) { + errno = EINVAL; + return NULL; + } - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn %llx\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)vcn); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn %llx\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)vcn); retry: - rl = na->rl; - if (!rl) - goto map_rl; - if (vcn < rl[0].vcn) - goto map_rl; - while (rl->length) { - if (vcn < rl[1].vcn) { - if (rl->lcn >= (LCN)LCN_HOLE) - return rl; - break; - } - rl++; - } - switch (rl->lcn) { - case (LCN)LCN_RL_NOT_MAPPED: - goto map_rl; - case (LCN)LCN_ENOENT: - errno = ENOENT; - break; - case (LCN)LCN_EINVAL: - errno = EINVAL; - break; - default: - errno = EIO; - break; - } - return NULL; + rl = na->rl; + if (!rl) + goto map_rl; + if (vcn < rl[0].vcn) + goto map_rl; + while (rl->length) { + if (vcn < rl[1].vcn) { + if (rl->lcn >= (LCN)LCN_HOLE) + return rl; + break; + } + rl++; + } + switch (rl->lcn) { + case (LCN)LCN_RL_NOT_MAPPED: + goto map_rl; + case (LCN)LCN_ENOENT: + errno = ENOENT; + break; + case (LCN)LCN_EINVAL: + errno = EINVAL; + break; + default: + errno = EIO; + break; + } + return NULL; map_rl: - /* The @vcn is in an unmapped region, map the runlist and retry. */ - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If we already retried or the mapping attempt failed something has - * gone badly wrong. EINVAL and ENOENT coming from a failed mapping - * attempt are equivalent to errors for us as they should not happen - * in our code paths. - */ - if (is_retry || errno == EINVAL || errno == ENOENT) - errno = EIO; - return NULL; + /* The @vcn is in an unmapped region, map the runlist and retry. */ + if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { + is_retry = TRUE; + goto retry; + } + /* + * If we already retried or the mapping attempt failed something has + * gone badly wrong. EINVAL and ENOENT coming from a failed mapping + * attempt are equivalent to errors for us as they should not happen + * in our code paths. + */ + if (is_retry || errno == EINVAL || errno == ENOENT) + errno = EIO; + return NULL; } /** * ntfs_attr_pread_i - see description at ntfs_attr_pread() - */ -static s64 ntfs_attr_pread_i(ntfs_attr *na, const s64 pos, s64 count, void *b) { - s64 br, to_read, ofs, total, total2, max_read, max_init; - ntfs_volume *vol; - runlist_element *rl; - u16 efs_padding_length; + */ +static s64 ntfs_attr_pread_i(ntfs_attr *na, const s64 pos, s64 count, void *b) +{ + s64 br, to_read, ofs, total, total2, max_read, max_init; + ntfs_volume *vol; + runlist_element *rl; + u16 efs_padding_length; - /* Sanity checking arguments is done in ntfs_attr_pread(). */ + /* Sanity checking arguments is done in ntfs_attr_pread(). */ + + if ((na->data_flags & ATTR_COMPRESSION_MASK) && NAttrNonResident(na)) { + if ((na->data_flags & ATTR_COMPRESSION_MASK) + == ATTR_IS_COMPRESSED) + return ntfs_compressed_attr_pread(na, pos, count, b); + else { + /* compression mode not supported */ + errno = EOPNOTSUPP; + return -1; + } + } + /* + * Encrypted non-resident attributes are not supported. We return + * access denied, which is what Windows NT4 does, too. + * However, allow if mounted with efs_raw option + */ + vol = na->ni->vol; + if (!vol->efs_raw && NAttrEncrypted(na) && NAttrNonResident(na)) { + errno = EACCES; + return -1; + } + + if (!count) + return 0; + /* + * Truncate reads beyond end of attribute, + * but round to next 512 byte boundary for encrypted + * attributes with efs_raw mount option + */ + max_read = na->data_size; + max_init = na->initialized_size; + if (na->ni->vol->efs_raw + && (na->data_flags & ATTR_IS_ENCRYPTED) + && NAttrNonResident(na)) { + if (na->data_size != na->initialized_size) { + ntfs_log_error("uninitialized encrypted file not supported\n"); + errno = EINVAL; + return -1; + } + max_init = max_read = ((na->data_size + 511) & ~511) + 2; + } + if (pos + count > max_read) { + if (pos >= max_read) + return 0; + count = max_read - pos; + } + /* If it is a resident attribute, get the value from the mft record. */ + if (!NAttrNonResident(na)) { + ntfs_attr_search_ctx *ctx; + char *val; - if ((na->data_flags & ATTR_COMPRESSION_MASK) && NAttrNonResident(na)) { - if ((na->data_flags & ATTR_COMPRESSION_MASK) - == ATTR_IS_COMPRESSED) - return ntfs_compressed_attr_pread(na, pos, count, b); - else { - /* compression mode not supported */ - errno = EOPNOTSUPP; - return -1; - } - } - /* - * Encrypted non-resident attributes are not supported. We return - * access denied, which is what Windows NT4 does, too. - * However, allow if mounted with efs_raw option - */ - vol = na->ni->vol; - if (!vol->efs_raw && NAttrEncrypted(na) && NAttrNonResident(na)) { - errno = EACCES; - return -1; - } - - if (!count) - return 0; - /* - * Truncate reads beyond end of attribute, - * but round to next 512 byte boundary for encrypted - * attributes with efs_raw mount option - */ - max_read = na->data_size; - max_init = na->initialized_size; - if (na->ni->vol->efs_raw - && (na->data_flags & ATTR_IS_ENCRYPTED) - && NAttrNonResident(na)) { - if (na->data_size != na->initialized_size) { - ntfs_log_error("uninitialized encrypted file not supported\n"); - errno = EINVAL; - return -1; - } - max_init = max_read = ((na->data_size + 511) & ~511) + 2; - } - if (pos + count > max_read) { - if (pos >= max_read) - return 0; - count = max_read - pos; - } - /* If it is a resident attribute, get the value from the mft record. */ - if (!NAttrNonResident(na)) { - ntfs_attr_search_ctx *ctx; - char *val; - - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx)) { + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx)) { res_err_out: - ntfs_attr_put_search_ctx(ctx); - return -1; - } - val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); - if (val < (char*)ctx->attr || val + - le32_to_cpu(ctx->attr->value_length) > - (char*)ctx->mrec + vol->mft_record_size) { - errno = EIO; - ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); - goto res_err_out; - } - memcpy(b, val + pos, count); - ntfs_attr_put_search_ctx(ctx); - return count; - } - total = total2 = 0; - /* Zero out reads beyond initialized size. */ - if (pos + count > max_init) { - if (pos >= max_init) { - memset(b, 0, count); - return count; - } - total2 = pos + count - max_init; - count -= total2; - memset((u8*)b + count, 0, total2); - } - /* - * for encrypted non-resident attributes with efs_raw set - * the last two bytes aren't read from disk but contain - * the number of padding bytes so original size can be - * restored - */ - if (na->ni->vol->efs_raw && - (na->data_flags & ATTR_IS_ENCRYPTED) && - ((pos + count) > max_init-2)) { - efs_padding_length = 511 - ((na->data_size - 1) & 511); - if (pos+count == max_init) { - if (count == 1) { - *((u8*)b+count-1) = (u8)(efs_padding_length >> 8); - count--; - total2++; - } else { - *(u16*)((u8*)b+count-2) = cpu_to_le16(efs_padding_length); - count -= 2; - total2 +=2; - } - } else { - *((u8*)b+count-1) = (u8)(efs_padding_length & 0xff); - count--; - total2++; - } - } - - /* Find the runlist element containing the vcn. */ - rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds read. - * However, we already truncated the read to the data_size, - * so getting this here is an error. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #1", __FUNCTION__); - } - return -1; - } - /* - * Gather the requested data into the linear destination buffer. Note, - * a partial final vcn is taken care of by the @count capping of read - * length. - */ - ofs = pos - (rl->vcn << vol->cluster_size_bits); - for (; count; rl++, ofs = 0) { - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #2", - __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = pos + total - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - if (rl->lcn != (LCN)LCN_HOLE) { - ntfs_log_perror("%s: Bad run (%lld)", - __FUNCTION__, - (long long)rl->lcn); - goto rl_err_out; - } - /* It is a hole, just zero the matching @b range. */ - to_read = min(count, (rl->length << - vol->cluster_size_bits) - ofs); - memset(b, 0, to_read); - /* Update progress counters. */ - total += to_read; - count -= to_read; - b = (u8*)b + to_read; - continue; - } - /* It is a real lcn, read it into @dst. */ - to_read = min(count, (rl->length << vol->cluster_size_bits) - - ofs); + ntfs_attr_put_search_ctx(ctx); + return -1; + } + val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); + if (val < (char*)ctx->attr || val + + le32_to_cpu(ctx->attr->value_length) > + (char*)ctx->mrec + vol->mft_record_size) { + errno = EIO; + ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); + goto res_err_out; + } + memcpy(b, val + pos, count); + ntfs_attr_put_search_ctx(ctx); + return count; + } + total = total2 = 0; + /* Zero out reads beyond initialized size. */ + if (pos + count > max_init) { + if (pos >= max_init) { + memset(b, 0, count); + return count; + } + total2 = pos + count - max_init; + count -= total2; + memset((u8*)b + count, 0, total2); + } + /* + * for encrypted non-resident attributes with efs_raw set + * the last two bytes aren't read from disk but contain + * the number of padding bytes so original size can be + * restored + */ + if (na->ni->vol->efs_raw && + (na->data_flags & ATTR_IS_ENCRYPTED) && + ((pos + count) > max_init-2)) { + efs_padding_length = 511 - ((na->data_size - 1) & 511); + if (pos+count == max_init) { + if (count == 1) { + *((u8*)b+count-1) = (u8)(efs_padding_length >> 8); + count--; + total2++; + } else { + *(u16*)((u8*)b+count-2) = cpu_to_le16(efs_padding_length); + count -= 2; + total2 +=2; + } + } else { + *((u8*)b+count-1) = (u8)(efs_padding_length & 0xff); + count--; + total2++; + } + } + + /* Find the runlist element containing the vcn. */ + rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); + if (!rl) { + /* + * If the vcn is not present it is an out of bounds read. + * However, we already truncated the read to the data_size, + * so getting this here is an error. + */ + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #1", __FUNCTION__); + } + return -1; + } + /* + * Gather the requested data into the linear destination buffer. Note, + * a partial final vcn is taken care of by the @count capping of read + * length. + */ + ofs = pos - (rl->vcn << vol->cluster_size_bits); + for (; count; rl++, ofs = 0) { + if (rl->lcn == LCN_RL_NOT_MAPPED) { + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl) { + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #2", + __FUNCTION__); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = pos + total - (rl->vcn << vol->cluster_size_bits); + } + if (!rl->length) { + errno = EIO; + ntfs_log_perror("%s: Zero run length", __FUNCTION__); + goto rl_err_out; + } + if (rl->lcn < (LCN)0) { + if (rl->lcn != (LCN)LCN_HOLE) { + ntfs_log_perror("%s: Bad run (%lld)", + __FUNCTION__, + (long long)rl->lcn); + goto rl_err_out; + } + /* It is a hole, just zero the matching @b range. */ + to_read = min(count, (rl->length << + vol->cluster_size_bits) - ofs); + memset(b, 0, to_read); + /* Update progress counters. */ + total += to_read; + count -= to_read; + b = (u8*)b + to_read; + continue; + } + /* It is a real lcn, read it into @dst. */ + to_read = min(count, (rl->length << vol->cluster_size_bits) - + ofs); retry: - ntfs_log_trace("Reading %lld bytes from vcn %lld, lcn %lld, ofs" - " %lld.\n", (long long)to_read, (long long)rl->vcn, - (long long )rl->lcn, (long long)ofs); - br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) + - ofs, to_read, b); - /* If everything ok, update progress counters and continue. */ - if (br > 0) { - total += br; - count -= br; - b = (u8*)b + br; - } - if (br == to_read) - continue; - /* If the syscall was interrupted, try again. */ - if (br == (s64)-1 && errno == EINTR) - goto retry; - if (total) - return total; - if (!br) - errno = EIO; - ntfs_log_perror("%s: ntfs_pread failed", __FUNCTION__); - return -1; - } - /* Finally, return the number of bytes read. */ - return total + total2; + ntfs_log_trace("Reading %lld bytes from vcn %lld, lcn %lld, ofs" + " %lld.\n", (long long)to_read, (long long)rl->vcn, + (long long )rl->lcn, (long long)ofs); + br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) + + ofs, to_read, b); + /* If everything ok, update progress counters and continue. */ + if (br > 0) { + total += br; + count -= br; + b = (u8*)b + br; + } + if (br == to_read) + continue; + /* If the syscall was interrupted, try again. */ + if (br == (s64)-1 && errno == EINTR) + goto retry; + if (total) + return total; + if (!br) + errno = EIO; + ntfs_log_perror("%s: ntfs_pread failed", __FUNCTION__); + return -1; + } + /* Finally, return the number of bytes read. */ + return total + total2; rl_err_out: - if (total) - return total; - errno = EIO; - return -1; + if (total) + return total; + errno = EIO; + return -1; } /** @@ -1037,216 +1049,219 @@ rl_err_out: * to the return code of ntfs_pread(), or to EINVAL in case of invalid * arguments. */ -s64 ntfs_attr_pread(ntfs_attr *na, const s64 pos, s64 count, void *b) { - s64 ret; +s64 ntfs_attr_pread(ntfs_attr *na, const s64 pos, s64 count, void *b) +{ + s64 ret; + + if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) { + errno = EINVAL; + ntfs_log_perror("%s: na=%p b=%p pos=%lld count=%lld", + __FUNCTION__, na, b, (long long)pos, + (long long)count); + return -1; + } + + ntfs_log_enter("Entering for inode %lld attr 0x%x pos %lld count " + "%lld\n", (unsigned long long)na->ni->mft_no, + na->type, (long long)pos, (long long)count); - if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s: na=%p b=%p pos=%lld count=%lld", - __FUNCTION__, na, b, (long long)pos, - (long long)count); - return -1; - } - - ntfs_log_enter("Entering for inode %lld attr 0x%x pos %lld count " - "%lld\n", (unsigned long long)na->ni->mft_no, - na->type, (long long)pos, (long long)count); - - ret = ntfs_attr_pread_i(na, pos, count, b); - - ntfs_log_leave("\n"); - return ret; + ret = ntfs_attr_pread_i(na, pos, count, b); + + ntfs_log_leave("\n"); + return ret; } -static int ntfs_attr_fill_zero(ntfs_attr *na, s64 pos, s64 count) { - char *buf; - s64 written, size, end = pos + count; - s64 ofsi; - const runlist_element *rli; - ntfs_volume *vol; - int ret = -1; +static int ntfs_attr_fill_zero(ntfs_attr *na, s64 pos, s64 count) +{ + char *buf; + s64 written, size, end = pos + count; + s64 ofsi; + const runlist_element *rli; + ntfs_volume *vol; + int ret = -1; - ntfs_log_trace("pos %lld, count %lld\n", (long long)pos, - (long long)count); - - if (!na || pos < 0 || count < 0) { - errno = EINVAL; - goto err_out; - } - - buf = ntfs_calloc(NTFS_BUF_SIZE); - if (!buf) - goto err_out; - - rli = na->rl; - ofsi = 0; - vol = na->ni->vol; - while (pos < end) { - while (rli->length && (ofsi + (rli->length << - vol->cluster_size_bits) <= pos)) { - ofsi += (rli->length << vol->cluster_size_bits); - rli++; - } - size = min(end - pos, NTFS_BUF_SIZE); - written = ntfs_rl_pwrite(vol, rli, ofsi, pos, size, buf); - if (written <= 0) { - ntfs_log_perror("Failed to zero space"); - goto err_free; - } - pos += written; - } - - ret = 0; -err_free: - free(buf); + ntfs_log_trace("pos %lld, count %lld\n", (long long)pos, + (long long)count); + + if (!na || pos < 0 || count < 0) { + errno = EINVAL; + goto err_out; + } + + buf = ntfs_calloc(NTFS_BUF_SIZE); + if (!buf) + goto err_out; + + rli = na->rl; + ofsi = 0; + vol = na->ni->vol; + while (pos < end) { + while (rli->length && (ofsi + (rli->length << + vol->cluster_size_bits) <= pos)) { + ofsi += (rli->length << vol->cluster_size_bits); + rli++; + } + size = min(end - pos, NTFS_BUF_SIZE); + written = ntfs_rl_pwrite(vol, rli, ofsi, pos, size, buf); + if (written <= 0) { + ntfs_log_perror("Failed to zero space"); + goto err_free; + } + pos += written; + } + + ret = 0; +err_free: + free(buf); err_out: - return ret; + return ret; } -static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs, - runlist_element **rl, VCN *update_from) { - s64 to_write; - s64 need; - ntfs_volume *vol = na->ni->vol; - int eo, ret = -1; - runlist *rlc; - LCN lcn_seek_from = -1; - VCN cur_vcn, from_vcn; +static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs, + runlist_element **rl, VCN *update_from) +{ + s64 to_write; + s64 need; + ntfs_volume *vol = na->ni->vol; + int eo, ret = -1; + runlist *rlc; + LCN lcn_seek_from = -1; + VCN cur_vcn, from_vcn; - to_write = min(count, ((*rl)->length << vol->cluster_size_bits) - *ofs); - - cur_vcn = (*rl)->vcn; - from_vcn = (*rl)->vcn + (*ofs >> vol->cluster_size_bits); - - ntfs_log_trace("count: %lld, cur_vcn: %lld, from: %lld, to: %lld, ofs: " - "%lld\n", (long long)count, (long long)cur_vcn, - (long long)from_vcn, (long long)to_write, (long long)*ofs); - - /* Map whole runlist to be able update mapping pairs later. */ - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - - /* Restore @*rl, it probably get lost during runlist mapping. */ - *rl = ntfs_attr_find_vcn(na, cur_vcn); - if (!*rl) { - ntfs_log_error("Failed to find run after mapping runlist. " - "Please report to %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - - /* Search backwards to find the best lcn to start seek from. */ - rlc = *rl; - while (rlc->vcn) { - rlc--; - if (rlc->lcn >= 0) { - /* - * avoid fragmenting a compressed file - * Windows does not do that, and that may - * not be desirable for files which can - * be updated - */ - if (na->data_flags & ATTR_COMPRESSION_MASK) - lcn_seek_from = rlc->lcn + rlc->length; - else - lcn_seek_from = rlc->lcn + (from_vcn - rlc->vcn); - break; - } - } - if (lcn_seek_from == -1) { - /* Backwards search failed, search forwards. */ - rlc = *rl; - while (rlc->length) { - rlc++; - if (rlc->lcn >= 0) { - lcn_seek_from = rlc->lcn - (rlc->vcn - from_vcn); - if (lcn_seek_from < -1) - lcn_seek_from = -1; - break; - } - } - } - - need = ((*ofs + to_write - 1) >> vol->cluster_size_bits) - + 1 + (*rl)->vcn - from_vcn; - if ((na->data_flags & ATTR_COMPRESSION_MASK) - && (need < na->compression_block_clusters)) { - /* - * for a compressed file, be sure to allocate the full hole. - * We may need space to decompress existing compressed data. - */ - rlc = ntfs_cluster_alloc(vol, (*rl)->vcn, (*rl)->length, - lcn_seek_from, DATA_ZONE); - } else - rlc = ntfs_cluster_alloc(vol, from_vcn, need, - lcn_seek_from, DATA_ZONE); - if (!rlc) - goto err_out; - - *rl = ntfs_runlists_merge(na->rl, rlc); - /* - * For a compressed attribute, we must be sure there is an - * available entry, so reserve it before it gets too late. - */ - if (*rl && (na->data_flags & ATTR_COMPRESSION_MASK)) - *rl = ntfs_rl_extend(*rl,1); - if (!*rl) { - eo = errno; - ntfs_log_perror("Failed to merge runlists"); - if (ntfs_cluster_free_from_rl(vol, rlc)) { - ntfs_log_perror("Failed to free hot clusters. " - "Please run chkdsk /f"); - } - errno = eo; - goto err_out; - } - na->rl = *rl; - if (*update_from == -1) - *update_from = from_vcn; - *rl = ntfs_attr_find_vcn(na, cur_vcn); - if (!*rl) { - /* - * It's definitely a BUG, if we failed to find @cur_vcn, because - * we missed it during instantiating of the hole. - */ - ntfs_log_error("Failed to find run after hole instantiation. " - "Please report to %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - /* If leaved part of the hole go to the next run. */ - if ((*rl)->lcn < 0) - (*rl)++; - /* Now LCN shoudn't be less than 0. */ - if ((*rl)->lcn < 0) { - ntfs_log_error("BUG! LCN is lesser than 0. " - "Please report to the %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - if (*ofs) { - /* Clear non-sparse region from @cur_vcn to @*ofs. */ - if (ntfs_attr_fill_zero(na, cur_vcn << vol->cluster_size_bits, - *ofs)) - goto err_out; - } - if ((*rl)->vcn < cur_vcn) { - /* - * Clusters that replaced hole are merged with - * previous run, so we need to update offset. - */ - *ofs += (cur_vcn - (*rl)->vcn) << vol->cluster_size_bits; - } - if ((*rl)->vcn > cur_vcn) { - /* - * We left part of the hole, so we need to update offset - */ - *ofs -= ((*rl)->vcn - cur_vcn) << vol->cluster_size_bits; - } - - ret = 0; + to_write = min(count, ((*rl)->length << vol->cluster_size_bits) - *ofs); + + cur_vcn = (*rl)->vcn; + from_vcn = (*rl)->vcn + (*ofs >> vol->cluster_size_bits); + + ntfs_log_trace("count: %lld, cur_vcn: %lld, from: %lld, to: %lld, ofs: " + "%lld\n", (long long)count, (long long)cur_vcn, + (long long)from_vcn, (long long)to_write, (long long)*ofs); + + /* Map whole runlist to be able update mapping pairs later. */ + if (ntfs_attr_map_whole_runlist(na)) + goto err_out; + + /* Restore @*rl, it probably get lost during runlist mapping. */ + *rl = ntfs_attr_find_vcn(na, cur_vcn); + if (!*rl) { + ntfs_log_error("Failed to find run after mapping runlist. " + "Please report to %s.\n", NTFS_DEV_LIST); + errno = EIO; + goto err_out; + } + + /* Search backwards to find the best lcn to start seek from. */ + rlc = *rl; + while (rlc->vcn) { + rlc--; + if (rlc->lcn >= 0) { + /* + * avoid fragmenting a compressed file + * Windows does not do that, and that may + * not be desirable for files which can + * be updated + */ + if (na->data_flags & ATTR_COMPRESSION_MASK) + lcn_seek_from = rlc->lcn + rlc->length; + else + lcn_seek_from = rlc->lcn + (from_vcn - rlc->vcn); + break; + } + } + if (lcn_seek_from == -1) { + /* Backwards search failed, search forwards. */ + rlc = *rl; + while (rlc->length) { + rlc++; + if (rlc->lcn >= 0) { + lcn_seek_from = rlc->lcn - (rlc->vcn - from_vcn); + if (lcn_seek_from < -1) + lcn_seek_from = -1; + break; + } + } + } + + need = ((*ofs + to_write - 1) >> vol->cluster_size_bits) + + 1 + (*rl)->vcn - from_vcn; + if ((na->data_flags & ATTR_COMPRESSION_MASK) + && (need < na->compression_block_clusters)) { + /* + * for a compressed file, be sure to allocate the full hole. + * We may need space to decompress existing compressed data. + */ + rlc = ntfs_cluster_alloc(vol, (*rl)->vcn, (*rl)->length, + lcn_seek_from, DATA_ZONE); + } else + rlc = ntfs_cluster_alloc(vol, from_vcn, need, + lcn_seek_from, DATA_ZONE); + if (!rlc) + goto err_out; + + *rl = ntfs_runlists_merge(na->rl, rlc); + /* + * For a compressed attribute, we must be sure there is an + * available entry, so reserve it before it gets too late. + */ + if (*rl && (na->data_flags & ATTR_COMPRESSION_MASK)) + *rl = ntfs_rl_extend(*rl,1); + if (!*rl) { + eo = errno; + ntfs_log_perror("Failed to merge runlists"); + if (ntfs_cluster_free_from_rl(vol, rlc)) { + ntfs_log_perror("Failed to free hot clusters. " + "Please run chkdsk /f"); + } + errno = eo; + goto err_out; + } + na->rl = *rl; + if (*update_from == -1) + *update_from = from_vcn; + *rl = ntfs_attr_find_vcn(na, cur_vcn); + if (!*rl) { + /* + * It's definitely a BUG, if we failed to find @cur_vcn, because + * we missed it during instantiating of the hole. + */ + ntfs_log_error("Failed to find run after hole instantiation. " + "Please report to %s.\n", NTFS_DEV_LIST); + errno = EIO; + goto err_out; + } + /* If leaved part of the hole go to the next run. */ + if ((*rl)->lcn < 0) + (*rl)++; + /* Now LCN shoudn't be less than 0. */ + if ((*rl)->lcn < 0) { + ntfs_log_error("BUG! LCN is lesser than 0. " + "Please report to the %s.\n", NTFS_DEV_LIST); + errno = EIO; + goto err_out; + } + if (*ofs) { + /* Clear non-sparse region from @cur_vcn to @*ofs. */ + if (ntfs_attr_fill_zero(na, cur_vcn << vol->cluster_size_bits, + *ofs)) + goto err_out; + } + if ((*rl)->vcn < cur_vcn) { + /* + * Clusters that replaced hole are merged with + * previous run, so we need to update offset. + */ + *ofs += (cur_vcn - (*rl)->vcn) << vol->cluster_size_bits; + } + if ((*rl)->vcn > cur_vcn) { + /* + * We left part of the hole, so we need to update offset + */ + *ofs -= ((*rl)->vcn - cur_vcn) << vol->cluster_size_bits; + } + + ret = 0; err_out: - return ret; + return ret; } static int stuff_hole(ntfs_attr *na, const s64 pos); @@ -1270,651 +1285,651 @@ static int stuff_hole(ntfs_attr *na, const s64 pos); * appropriately to the return code of ntfs_pwrite(), or to EINVAL in case of * invalid arguments. */ -s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, const void *b) { - s64 written, to_write, ofs, old_initialized_size, old_data_size; - s64 total = 0; - VCN update_from = -1; - ntfs_volume *vol; - s64 fullcount; - ntfs_attr_search_ctx *ctx = NULL; - runlist_element *rl; - s64 hole_end; - int eo; - int compressed_part; - struct { -unsigned int undo_initialized_size : - 1; -unsigned int undo_data_size : - 1; - } need_to = { 0, 0 }; - BOOL makingnonresident = FALSE; - BOOL wasnonresident = FALSE; - BOOL compressed; +s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, const void *b) +{ + s64 written, to_write, ofs, old_initialized_size, old_data_size; + s64 total = 0; + VCN update_from = -1; + ntfs_volume *vol; + s64 fullcount; + ntfs_attr_search_ctx *ctx = NULL; + runlist_element *rl; + s64 hole_end; + int eo; + int compressed_part; + struct { + unsigned int undo_initialized_size : 1; + unsigned int undo_data_size : 1; + } need_to = { 0, 0 }; + BOOL makingnonresident = FALSE; + BOOL wasnonresident = FALSE; + BOOL compressed; - ntfs_log_enter("Entering for inode %lld, attr 0x%x, pos 0x%llx, count " - "0x%llx.\n", (long long)na->ni->mft_no, na->type, - (long long)pos, (long long)count); + ntfs_log_enter("Entering for inode %lld, attr 0x%x, pos 0x%llx, count " + "0x%llx.\n", (long long)na->ni->mft_no, na->type, + (long long)pos, (long long)count); + + if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + goto errno_set; + } + vol = na->ni->vol; + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + /* + * Encrypted attributes are only supported in raw mode. We return + * access denied, which is what Windows NT4 does, too. + * Moreover a file cannot be both encrypted and compressed. + */ + if ((na->data_flags & ATTR_IS_ENCRYPTED) + && (compressed || !vol->efs_raw)) { + errno = EACCES; + goto errno_set; + } + /* + * Fill the gap, when writing beyond the end of a compressed + * file. This will make recursive calls + */ + if (compressed + && (na->type == AT_DATA) + && (pos > na->initialized_size) + && stuff_hole(na,pos)) + goto errno_set; + /* If this is a compressed attribute it needs special treatment. */ + wasnonresident = NAttrNonResident(na) != 0; + makingnonresident = wasnonresident /* yes : already changed */ + && !pos && (count == na->initialized_size); + /* + * Writing to compressed files is currently restricted + * to appending data. However we have to accept + * recursive write calls to make the attribute non resident. + * These are writing at position 0 up to initialized_size. + * Compression is also restricted to data streams. + * Only ATTR_IS_COMPRESSED compression mode is supported. + */ + if (compressed + && ((na->type != AT_DATA) + || ((na->data_flags & ATTR_COMPRESSION_MASK) + != ATTR_IS_COMPRESSED) + || ((pos != na->initialized_size) + && (pos || (count != na->initialized_size))))) { + // TODO: Implement writing compressed attributes! (AIA) + errno = EOPNOTSUPP; + goto errno_set; + } + + if (!count) + goto out; + /* for a compressed file, get prepared to reserve a full block */ + fullcount = count; + /* If the write reaches beyond the end, extend the attribute. */ + old_data_size = na->data_size; + if (pos + count > na->data_size) { + if (ntfs_attr_truncate(na, pos + count)) { + ntfs_log_perror("Failed to enlarge attribute"); + goto errno_set; + } + /* resizing may change the compression mode */ + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + need_to.undo_data_size = 1; + } + /* + * For compressed data, a single full block was allocated + * to deal with compression, possibly in a previous call. + * We are not able to process several blocks because + * some clusters are freed after compression and + * new allocations have to be done before proceeding, + * so truncate the requested count if needed (big buffers). + */ + if (compressed) { + fullcount = na->data_size - pos; + if (count > fullcount) + count = fullcount; + } + old_initialized_size = na->initialized_size; + /* If it is a resident attribute, write the data to the mft record. */ + if (!NAttrNonResident(na)) { + char *val; - if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto errno_set; - } - vol = na->ni->vol; - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - /* - * Encrypted attributes are only supported in raw mode. We return - * access denied, which is what Windows NT4 does, too. - * Moreover a file cannot be both encrypted and compressed. - */ - if ((na->data_flags & ATTR_IS_ENCRYPTED) - && (compressed || !vol->efs_raw)) { - errno = EACCES; - goto errno_set; - } - /* - * Fill the gap, when writing beyond the end of a compressed - * file. This will make recursive calls - */ - if (compressed - && (na->type == AT_DATA) - && (pos > na->initialized_size) - && stuff_hole(na,pos)) - goto errno_set; - /* If this is a compressed attribute it needs special treatment. */ - wasnonresident = NAttrNonResident(na) != 0; - makingnonresident = wasnonresident /* yes : already changed */ - && !pos && (count == na->initialized_size); - /* - * Writing to compressed files is currently restricted - * to appending data. However we have to accept - * recursive write calls to make the attribute non resident. - * These are writing at position 0 up to initialized_size. - * Compression is also restricted to data streams. - * Only ATTR_IS_COMPRESSED compression mode is supported. - */ - if (compressed - && ((na->type != AT_DATA) - || ((na->data_flags & ATTR_COMPRESSION_MASK) - != ATTR_IS_COMPRESSED) - || ((pos != na->initialized_size) - && (pos || (count != na->initialized_size))))) { - // TODO: Implement writing compressed attributes! (AIA) - errno = EOPNOTSUPP; - goto errno_set; - } + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + goto err_out; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx)) { + ntfs_log_perror("%s: lookup failed", __FUNCTION__); + goto err_out; + } + val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); + if (val < (char*)ctx->attr || val + + le32_to_cpu(ctx->attr->value_length) > + (char*)ctx->mrec + vol->mft_record_size) { + errno = EIO; + ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); + goto err_out; + } + memcpy(val + pos, b, count); + if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, + ctx->mrec)) { + /* + * NOTE: We are in a bad state at this moment. We have + * dirtied the mft record but we failed to commit it to + * disk. Since we have read the mft record ok before, + * it is unlikely to fail writing it, so is ok to just + * return error here... (AIA) + */ + ntfs_log_perror("%s: failed to write mft record", __FUNCTION__); + goto err_out; + } + ntfs_attr_put_search_ctx(ctx); + total = count; + goto out; + } + + /* Handle writes beyond initialized_size. */ + if (pos + count > na->initialized_size) { + if (ntfs_attr_map_whole_runlist(na)) + goto err_out; + /* + * For a compressed attribute, we must be sure there is an + * available entry, and, when reopening a compressed file, + * we may need to split a hole. So reserve the entries + * before it gets too late. + */ + if (compressed) { + na->rl = ntfs_rl_extend(na->rl,2); + if (!na->rl) + goto err_out; + } + /* Set initialized_size to @pos + @count. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + goto err_out; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx)) + goto err_out; + + /* If write starts beyond initialized_size, zero the gap. */ + if (pos > na->initialized_size) + if (ntfs_attr_fill_zero(na, na->initialized_size, + pos - na->initialized_size)) + goto err_out; + + ctx->attr->initialized_size = cpu_to_sle64(pos + count); + /* fix data_size for compressed files */ + if (compressed) + ctx->attr->data_size = ctx->attr->initialized_size; + if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, + ctx->mrec)) { + /* + * Undo the change in the in-memory copy and send it + * back for writing. + */ + ctx->attr->initialized_size = + cpu_to_sle64(old_initialized_size); + ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, + ctx->mrec); + goto err_out; + } + na->initialized_size = pos + count; + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; + /* + * NOTE: At this point the initialized_size in the mft record + * has been updated BUT there is random data on disk thus if + * we decide to abort, we MUST change the initialized_size + * again. + */ + need_to.undo_initialized_size = 1; + } + /* Find the runlist element containing the vcn. */ + rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); + if (!rl) { + /* + * If the vcn is not present it is an out of bounds write. + * However, we already extended the size of the attribute, + * so getting this here must be an error of some kind. + */ + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #3", __FUNCTION__); + } + goto err_out; + } + ofs = pos - (rl->vcn << vol->cluster_size_bits); + /* + * Determine if there is compressed data in the current + * compression block (when appending to an existing file). + * If so, decompression will be needed, and the full block + * must be allocated to be identified as uncompressed. + * This comes in two variants, depending on whether + * compression has saved at least one cluster. + * The compressed size can never be over full size by + * more than 485 (maximum for 15 compression blocks + * compressed to 4098 and the last 3640 bytes compressed + * to 3640 + 3640/8 = 4095, with 15*2 + 4095 - 3640 = 485) + * This is less than the smallest cluster, so the hole is + * is never beyond the cluster next to the position of + * the first uncompressed byte to write. + */ + compressed_part = 0; + if (compressed) { + if ((rl->lcn == (LCN)LCN_HOLE) + && wasnonresident) { + if (rl->length < na->compression_block_clusters) + compressed_part + = na->compression_block_clusters + - rl->length; + else { + compressed_part + = na->compression_block_clusters; + if (rl->length > na->compression_block_clusters) { + rl[2].lcn = rl[1].lcn; + rl[2].vcn = rl[1].vcn; + rl[2].length = rl[1].length; + rl[1].vcn -= compressed_part; + rl[1].lcn = LCN_HOLE; + rl[1].length = compressed_part; + rl[0].length -= compressed_part; + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } + } + /* normal hole filling will do later */ + } else + if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) { + s64 xofs; - if (!count) - goto out; - /* for a compressed file, get prepared to reserve a full block */ - fullcount = count; - /* If the write reaches beyond the end, extend the attribute. */ - old_data_size = na->data_size; - if (pos + count > na->data_size) { - if (ntfs_attr_truncate(na, pos + count)) { - ntfs_log_perror("Failed to enlarge attribute"); - goto errno_set; - } - /* resizing may change the compression mode */ - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - need_to.undo_data_size = 1; - } - /* - * For compressed data, a single full block was allocated - * to deal with compression, possibly in a previous call. - * We are not able to process several blocks because - * some clusters are freed after compression and - * new allocations have to be done before proceeding, - * so truncate the requested count if needed (big buffers). - */ - if (compressed) { - fullcount = na->data_size - pos; - if (count > fullcount) - count = fullcount; - } - old_initialized_size = na->initialized_size; - /* If it is a resident attribute, write the data to the mft record. */ - if (!NAttrNonResident(na)) { - char *val; + if (wasnonresident) + compressed_part = na->compression_block_clusters + - rl[1].length; + rl++; + xofs = 0; + if (ntfs_attr_fill_hole(na, + rl->length << vol->cluster_size_bits, + &xofs, &rl, &update_from)) + goto err_out; + /* the fist allocated cluster was not merged */ + if (!xofs) + rl--; + } + } + /* + * Scatter the data from the linear data buffer to the volume. Note, a + * partial final vcn is taken care of by the @count capping of write + * length. + */ + for (hole_end = 0; count; rl++, ofs = 0, hole_end = 0) { + if (rl->lcn == LCN_RL_NOT_MAPPED) { + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl) { + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN" + " #4", __FUNCTION__); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = pos + total - (rl->vcn << vol->cluster_size_bits); + } + if (!rl->length) { + errno = EIO; + ntfs_log_perror("%s: Zero run length", __FUNCTION__); + goto rl_err_out; + } + if (rl->lcn < (LCN)0) { + hole_end = rl->vcn + rl->length; - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto err_out; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx)) { - ntfs_log_perror("%s: lookup failed", __FUNCTION__); - goto err_out; - } - val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); - if (val < (char*)ctx->attr || val + - le32_to_cpu(ctx->attr->value_length) > - (char*)ctx->mrec + vol->mft_record_size) { - errno = EIO; - ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); - goto err_out; - } - memcpy(val + pos, b, count); - if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec)) { - /* - * NOTE: We are in a bad state at this moment. We have - * dirtied the mft record but we failed to commit it to - * disk. Since we have read the mft record ok before, - * it is unlikely to fail writing it, so is ok to just - * return error here... (AIA) - */ - ntfs_log_perror("%s: failed to write mft record", __FUNCTION__); - goto err_out; - } - ntfs_attr_put_search_ctx(ctx); - total = count; - goto out; - } + if (rl->lcn != (LCN)LCN_HOLE) { + errno = EIO; + ntfs_log_perror("%s: Unexpected LCN (%lld)", + __FUNCTION__, + (long long)rl->lcn); + goto rl_err_out; + } + if (ntfs_attr_fill_hole(na, fullcount, &ofs, &rl, + &update_from)) + goto err_out; + } + if (compressed) { + while (rl->length + && (ofs >= (rl->length << vol->cluster_size_bits))) { + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } + } - /* Handle writes beyond initialized_size. */ - if (pos + count > na->initialized_size) { - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - /* - * For a compressed attribute, we must be sure there is an - * available entry, and, when reopening a compressed file, - * we may need to split a hole. So reserve the entries - * before it gets too late. - */ - if (compressed) { - na->rl = ntfs_rl_extend(na->rl,2); - if (!na->rl) - goto err_out; - } - /* Set initialized_size to @pos + @count. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto err_out; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx)) - goto err_out; - - /* If write starts beyond initialized_size, zero the gap. */ - if (pos > na->initialized_size) - if (ntfs_attr_fill_zero(na, na->initialized_size, - pos - na->initialized_size)) - goto err_out; - - ctx->attr->initialized_size = cpu_to_sle64(pos + count); - /* fix data_size for compressed files */ - if (compressed) - ctx->attr->data_size = ctx->attr->initialized_size; - if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec)) { - /* - * Undo the change in the in-memory copy and send it - * back for writing. - */ - ctx->attr->initialized_size = - cpu_to_sle64(old_initialized_size); - ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec); - goto err_out; - } - na->initialized_size = pos + count; - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - /* - * NOTE: At this point the initialized_size in the mft record - * has been updated BUT there is random data on disk thus if - * we decide to abort, we MUST change the initialized_size - * again. - */ - need_to.undo_initialized_size = 1; - } - /* Find the runlist element containing the vcn. */ - rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds write. - * However, we already extended the size of the attribute, - * so getting this here must be an error of some kind. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #3", __FUNCTION__); - } - goto err_out; - } - ofs = pos - (rl->vcn << vol->cluster_size_bits); - /* - * Determine if there is compressed data in the current - * compression block (when appending to an existing file). - * If so, decompression will be needed, and the full block - * must be allocated to be identified as uncompressed. - * This comes in two variants, depending on whether - * compression has saved at least one cluster. - * The compressed size can never be over full size by - * more than 485 (maximum for 15 compression blocks - * compressed to 4098 and the last 3640 bytes compressed - * to 3640 + 3640/8 = 4095, with 15*2 + 4095 - 3640 = 485) - * This is less than the smallest cluster, so the hole is - * is never beyond the cluster next to the position of - * the first uncompressed byte to write. - */ - compressed_part = 0; - if (compressed) { - if ((rl->lcn == (LCN)LCN_HOLE) - && wasnonresident) { - if (rl->length < na->compression_block_clusters) - compressed_part - = na->compression_block_clusters - - rl->length; - else { - compressed_part - = na->compression_block_clusters; - if (rl->length > na->compression_block_clusters) { - rl[2].lcn = rl[1].lcn; - rl[2].vcn = rl[1].vcn; - rl[2].length = rl[1].length; - rl[1].vcn -= compressed_part; - rl[1].lcn = LCN_HOLE; - rl[1].length = compressed_part; - rl[0].length -= compressed_part; - ofs -= rl->length << vol->cluster_size_bits; - rl++; - } - } - /* normal hole filling will do later */ - } else - if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) { - s64 xofs; - - if (wasnonresident) - compressed_part = na->compression_block_clusters - - rl[1].length; - rl++; - xofs = 0; - if (ntfs_attr_fill_hole(na, - rl->length << vol->cluster_size_bits, - &xofs, &rl, &update_from)) - goto err_out; - /* the fist allocated cluster was not merged */ - if (!xofs) - rl--; - } - } - /* - * Scatter the data from the linear data buffer to the volume. Note, a - * partial final vcn is taken care of by the @count capping of write - * length. - */ - for (hole_end = 0; count; rl++, ofs = 0, hole_end = 0) { - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN" - " #4", __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = pos + total - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - hole_end = rl->vcn + rl->length; - - if (rl->lcn != (LCN)LCN_HOLE) { - errno = EIO; - ntfs_log_perror("%s: Unexpected LCN (%lld)", - __FUNCTION__, - (long long)rl->lcn); - goto rl_err_out; - } - if (ntfs_attr_fill_hole(na, fullcount, &ofs, &rl, - &update_from)) - goto err_out; - } - if (compressed) { - while (rl->length - && (ofs >= (rl->length << vol->cluster_size_bits))) { - ofs -= rl->length << vol->cluster_size_bits; - rl++; - } - } - - /* It is a real lcn, write it to the volume. */ - to_write = min(count, (rl->length << vol->cluster_size_bits) - ofs); + /* It is a real lcn, write it to the volume. */ + to_write = min(count, (rl->length << vol->cluster_size_bits) - ofs); retry: - ntfs_log_trace("Writing %lld bytes to vcn %lld, lcn %lld, ofs " - "%lld.\n", (long long)to_write, (long long)rl->vcn, - (long long)rl->lcn, (long long)ofs); - if (!NVolReadOnly(vol)) { - - s64 wpos = (rl->lcn << vol->cluster_size_bits) + ofs; - s64 wend = (rl->vcn << vol->cluster_size_bits) + ofs + to_write; - u32 bsize = vol->cluster_size; - /* Byte size needed to zero fill a cluster */ - s64 rounding = ((wend + bsize - 1) & ~(s64)(bsize - 1)) - wend; - /** - * Zero fill to cluster boundary if we're writing at the - * end of the attribute or into an ex-sparse cluster. - * This will cause the kernel not to seek and read disk - * blocks during write(2) to fill the end of the buffer - * which increases write speed by 2-10 fold typically. - * - * This is done even for compressed files, because - * data is generally first written uncompressed. - */ - if (rounding && ((wend == na->initialized_size) || - (wend < (hole_end << vol->cluster_size_bits)))) { - - char *cb; - - rounding += to_write; - - cb = ntfs_malloc(rounding); - if (!cb) - goto err_out; - - memcpy(cb, b, to_write); - memset(cb + to_write, 0, rounding - to_write); - - if (compressed) { - written = ntfs_compressed_pwrite(na, - rl, wpos, ofs, to_write, - rounding, b, compressed_part); - } else { - written = ntfs_pwrite(vol->dev, wpos, - rounding, cb); - if (written == rounding) - written = to_write; - } - - free(cb); - } else { - if (compressed) { - written = ntfs_compressed_pwrite(na, - rl, wpos, ofs, to_write, - to_write, b, compressed_part); - } else - written = ntfs_pwrite(vol->dev, wpos, - to_write, b); - } - } else - written = to_write; - /* If everything ok, update progress counters and continue. */ - if (written > 0) { - total += written; - count -= written; - fullcount -= written; - b = (const u8*)b + written; - } - if (written != to_write) { - /* Partial write cannot be dealt with, stop there */ - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (!written) - errno = EIO; - goto rl_err_out; - } - compressed_part = 0; - } + ntfs_log_trace("Writing %lld bytes to vcn %lld, lcn %lld, ofs " + "%lld.\n", (long long)to_write, (long long)rl->vcn, + (long long)rl->lcn, (long long)ofs); + if (!NVolReadOnly(vol)) { + + s64 wpos = (rl->lcn << vol->cluster_size_bits) + ofs; + s64 wend = (rl->vcn << vol->cluster_size_bits) + ofs + to_write; + u32 bsize = vol->cluster_size; + /* Byte size needed to zero fill a cluster */ + s64 rounding = ((wend + bsize - 1) & ~(s64)(bsize - 1)) - wend; + /** + * Zero fill to cluster boundary if we're writing at the + * end of the attribute or into an ex-sparse cluster. + * This will cause the kernel not to seek and read disk + * blocks during write(2) to fill the end of the buffer + * which increases write speed by 2-10 fold typically. + * + * This is done even for compressed files, because + * data is generally first written uncompressed. + */ + if (rounding && ((wend == na->initialized_size) || + (wend < (hole_end << vol->cluster_size_bits)))){ + + char *cb; + + rounding += to_write; + + cb = ntfs_malloc(rounding); + if (!cb) + goto err_out; + + memcpy(cb, b, to_write); + memset(cb + to_write, 0, rounding - to_write); + + if (compressed) { + written = ntfs_compressed_pwrite(na, + rl, wpos, ofs, to_write, + rounding, b, compressed_part); + } else { + written = ntfs_pwrite(vol->dev, wpos, + rounding, cb); + if (written == rounding) + written = to_write; + } + + free(cb); + } else { + if (compressed) { + written = ntfs_compressed_pwrite(na, + rl, wpos, ofs, to_write, + to_write, b, compressed_part); + } else + written = ntfs_pwrite(vol->dev, wpos, + to_write, b); + } + } else + written = to_write; + /* If everything ok, update progress counters and continue. */ + if (written > 0) { + total += written; + count -= written; + fullcount -= written; + b = (const u8*)b + written; + } + if (written != to_write) { + /* Partial write cannot be dealt with, stop there */ + /* If the syscall was interrupted, try again. */ + if (written == (s64)-1 && errno == EINTR) + goto retry; + if (!written) + errno = EIO; + goto rl_err_out; + } + compressed_part = 0; + } done: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if ((update_from != -1) - || (compressed && !makingnonresident)) - if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { - /* - * FIXME: trying to recover by goto rl_err_out; - * could cause driver hang by infinite looping. - */ - total = -1; - goto out; - } -out: - ntfs_log_leave("\n"); - return total; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if ((update_from != -1) + || (compressed && !makingnonresident)) + if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { + /* + * FIXME: trying to recover by goto rl_err_out; + * could cause driver hang by infinite looping. + */ + total = -1; + goto out; + } +out: + ntfs_log_leave("\n"); + return total; rl_err_out: - eo = errno; - if (total) { - if (need_to.undo_initialized_size) { - if (pos + total > na->initialized_size) - goto done; - /* - * TODO: Need to try to change initialized_size. If it - * succeeds goto done, otherwise goto err_out. (AIA) - */ - goto err_out; - } - goto done; - } - errno = eo; + eo = errno; + if (total) { + if (need_to.undo_initialized_size) { + if (pos + total > na->initialized_size) + goto done; + /* + * TODO: Need to try to change initialized_size. If it + * succeeds goto done, otherwise goto err_out. (AIA) + */ + goto err_out; + } + goto done; + } + errno = eo; err_out: - eo = errno; - if (need_to.undo_initialized_size) { - int err; + eo = errno; + if (need_to.undo_initialized_size) { + int err; - err = 0; - if (!ctx) { - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - err = 1; - } else - ntfs_attr_reinit_search_ctx(ctx); - if (!err) { - err = ntfs_attr_lookup(na->type, na->name, - na->name_len, 0, 0, NULL, 0, ctx); - if (!err) { - na->initialized_size = old_initialized_size; - ctx->attr->initialized_size = cpu_to_sle64( - old_initialized_size); - err = ntfs_mft_record_write(vol, - ctx->ntfs_ino->mft_no, - ctx->mrec); - } - } - if (err) { - /* - * FIXME: At this stage could try to recover by filling - * old_initialized_size -> new_initialized_size with - * data or at least zeroes. (AIA) - */ - ntfs_log_error("Eeek! Failed to recover from error. " - "Leaving metadata in inconsistent " - "state! Run chkdsk!\n"); - } - } - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if (update_from != -1) - ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); - /* Restore original data_size if needed. */ - if (need_to.undo_data_size && ntfs_attr_truncate(na, old_data_size)) - ntfs_log_perror("Failed to restore data_size"); - errno = eo; + err = 0; + if (!ctx) { + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + err = 1; + } else + ntfs_attr_reinit_search_ctx(ctx); + if (!err) { + err = ntfs_attr_lookup(na->type, na->name, + na->name_len, 0, 0, NULL, 0, ctx); + if (!err) { + na->initialized_size = old_initialized_size; + ctx->attr->initialized_size = cpu_to_sle64( + old_initialized_size); + err = ntfs_mft_record_write(vol, + ctx->ntfs_ino->mft_no, + ctx->mrec); + } + } + if (err) { + /* + * FIXME: At this stage could try to recover by filling + * old_initialized_size -> new_initialized_size with + * data or at least zeroes. (AIA) + */ + ntfs_log_error("Eeek! Failed to recover from error. " + "Leaving metadata in inconsistent " + "state! Run chkdsk!\n"); + } + } + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if (update_from != -1) + ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); + /* Restore original data_size if needed. */ + if (need_to.undo_data_size && ntfs_attr_truncate(na, old_data_size)) + ntfs_log_perror("Failed to restore data_size"); + errno = eo; errno_set: - total = -1; - goto out; + total = -1; + goto out; } -int ntfs_attr_pclose(ntfs_attr *na) { - s64 written, ofs; - BOOL ok = TRUE; - VCN update_from = -1; - ntfs_volume *vol; - ntfs_attr_search_ctx *ctx = NULL; - runlist_element *rl; - int eo; - s64 hole; - int compressed_part; - BOOL compressed; +int ntfs_attr_pclose(ntfs_attr *na) +{ + s64 written, ofs; + BOOL ok = TRUE; + VCN update_from = -1; + ntfs_volume *vol; + ntfs_attr_search_ctx *ctx = NULL; + runlist_element *rl; + int eo; + s64 hole; + int compressed_part; + BOOL compressed; - ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x.\n", - na->ni->mft_no, na->type); + ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x.\n", + na->ni->mft_no, na->type); + + if (!na || !na->ni || !na->ni->vol) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + goto errno_set; + } + vol = na->ni->vol; + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + /* + * Encrypted non-resident attributes are not supported. We return + * access denied, which is what Windows NT4 does, too. + */ + if (NAttrEncrypted(na) && NAttrNonResident(na)) { + errno = EACCES; + goto errno_set; + } + /* If this is not a compressed attribute get out */ + /* same if it is resident */ + if (!compressed || !NAttrNonResident(na)) + goto out; - if (!na || !na->ni || !na->ni->vol) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto errno_set; - } - vol = na->ni->vol; - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - /* - * Encrypted non-resident attributes are not supported. We return - * access denied, which is what Windows NT4 does, too. - */ - if (NAttrEncrypted(na) && NAttrNonResident(na)) { - errno = EACCES; - goto errno_set; - } - /* If this is not a compressed attribute get out */ - /* same if it is resident */ - if (!compressed || !NAttrNonResident(na)) - goto out; + /* + * For a compressed attribute, we must be sure there is an + * available entry, so reserve it before it gets too late. + */ + if (ntfs_attr_map_whole_runlist(na)) + goto err_out; + na->rl = ntfs_rl_extend(na->rl,1); + if (!na->rl) + goto err_out; + /* Find the runlist element containing the terminal vcn. */ + rl = ntfs_attr_find_vcn(na, (na->initialized_size - 1) >> vol->cluster_size_bits); + if (!rl) { + /* + * If the vcn is not present it is an out of bounds write. + * However, we have already written the last byte uncompressed, + * so getting this here must be an error of some kind. + */ + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #5", __FUNCTION__); + } + goto err_out; + } + /* + * Scatter the data from the linear data buffer to the volume. Note, a + * partial final vcn is taken care of by the @count capping of write + * length. + */ + compressed_part = 0; + if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) + compressed_part + = na->compression_block_clusters - rl[1].length; + else + if (rl->lcn == (LCN)LCN_HOLE) { + if (rl->length < na->compression_block_clusters) + compressed_part + = na->compression_block_clusters + - rl->length; + else + compressed_part + = na->compression_block_clusters; + } + /* done, if the last block set was compressed */ + if (compressed_part) + goto out; - /* - * For a compressed attribute, we must be sure there is an - * available entry, so reserve it before it gets too late. - */ - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - na->rl = ntfs_rl_extend(na->rl,1); - if (!na->rl) - goto err_out; - /* Find the runlist element containing the terminal vcn. */ - rl = ntfs_attr_find_vcn(na, (na->initialized_size - 1) >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds write. - * However, we have already written the last byte uncompressed, - * so getting this here must be an error of some kind. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #5", __FUNCTION__); - } - goto err_out; - } - /* - * Scatter the data from the linear data buffer to the volume. Note, a - * partial final vcn is taken care of by the @count capping of write - * length. - */ - compressed_part = 0; - if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) - compressed_part - = na->compression_block_clusters - rl[1].length; - else - if (rl->lcn == (LCN)LCN_HOLE) { - if (rl->length < na->compression_block_clusters) - compressed_part - = na->compression_block_clusters - - rl->length; - else - compressed_part - = na->compression_block_clusters; - } - /* done, if the last block set was compressed */ - if (compressed_part) - goto out; + ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); - ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); - - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN" - " #6", __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - hole = rl->vcn + rl->length; - if (rl->lcn != (LCN)LCN_HOLE) { - errno = EIO; - ntfs_log_perror("%s: Unexpected LCN (%lld)", - __FUNCTION__, - (long long)rl->lcn); - goto rl_err_out; - } - - if (ntfs_attr_fill_hole(na, (s64)0, &ofs, &rl, &update_from)) - goto err_out; - } - while (rl->length - && (ofs >= (rl->length << vol->cluster_size_bits))) { - ofs -= rl->length << vol->cluster_size_bits; - rl++; - } + if (rl->lcn == LCN_RL_NOT_MAPPED) { + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl) { + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN" + " #6", __FUNCTION__); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); + } + if (!rl->length) { + errno = EIO; + ntfs_log_perror("%s: Zero run length", __FUNCTION__); + goto rl_err_out; + } + if (rl->lcn < (LCN)0) { + hole = rl->vcn + rl->length; + if (rl->lcn != (LCN)LCN_HOLE) { + errno = EIO; + ntfs_log_perror("%s: Unexpected LCN (%lld)", + __FUNCTION__, + (long long)rl->lcn); + goto rl_err_out; + } + + if (ntfs_attr_fill_hole(na, (s64)0, &ofs, &rl, &update_from)) + goto err_out; + } + while (rl->length + && (ofs >= (rl->length << vol->cluster_size_bits))) { + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } retry: - written = 0; - if (!NVolReadOnly(vol)) { - - written = ntfs_compressed_close(na, rl, ofs); - /* If everything ok, update progress counters and continue. */ - if (!written) - goto done; - } - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (!written) - errno = EIO; - goto rl_err_out; + written = 0; + if (!NVolReadOnly(vol)) { + + written = ntfs_compressed_close(na, rl, ofs); + /* If everything ok, update progress counters and continue. */ + if (!written) + goto done; + } + /* If the syscall was interrupted, try again. */ + if (written == (s64)-1 && errno == EINTR) + goto retry; + if (!written) + errno = EIO; + goto rl_err_out; done: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { - /* - * FIXME: trying to recover by goto rl_err_out; - * could cause driver hang by infinite looping. - */ - ok = FALSE; - goto out; - } -out: - ntfs_log_leave("\n"); - return (!ok); + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { + /* + * FIXME: trying to recover by goto rl_err_out; + * could cause driver hang by infinite looping. + */ + ok = FALSE; + goto out; + } +out: + ntfs_log_leave("\n"); + return (!ok); rl_err_out: - /* - * need not restore old sizes, only compressed_size - * can have changed. It has been set according to - * the current runlist while updating the mapping pairs, - * and must be kept consistent with the runlists. - */ + /* + * need not restore old sizes, only compressed_size + * can have changed. It has been set according to + * the current runlist while updating the mapping pairs, + * and must be kept consistent with the runlists. + */ err_out: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); - errno = eo; + eo = errno; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); + errno = eo; errno_set: - ok = FALSE; - goto out; + ok = FALSE; + goto out; } /** @@ -1947,27 +1962,28 @@ errno_set: * errors can be repaired. */ s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, const s64 bk_cnt, - const u32 bk_size, void *dst) { - s64 br; - u8 *end; + const u32 bk_size, void *dst) +{ + s64 br; + u8 *end; - ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)pos); - if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } - br = ntfs_attr_pread(na, pos, bk_cnt * bk_size, dst); - if (br <= 0) - return br; - br /= bk_size; - for (end = (u8*)dst + br * bk_size; (u8*)dst < end; dst = (u8*)dst + - bk_size) - ntfs_mst_post_read_fixup((NTFS_RECORD*)dst, bk_size); - /* Finally, return the number of blocks read. */ - return br; + ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)pos); + if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } + br = ntfs_attr_pread(na, pos, bk_cnt * bk_size, dst); + if (br <= 0) + return br; + br /= bk_size; + for (end = (u8*)dst + br * bk_size; (u8*)dst < end; dst = (u8*)dst + + bk_size) + ntfs_mst_post_read_fixup((NTFS_RECORD*)dst, bk_size); + /* Finally, return the number of blocks read. */ + return br; } /** @@ -2001,47 +2017,48 @@ s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, const s64 bk_cnt, * achieved. */ s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, - const u32 bk_size, void *src) { - s64 written, i; + const u32 bk_size, void *src) +{ + s64 written, i; - ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)pos); - if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { - errno = EINVAL; - return -1; - } - if (!bk_cnt) - return 0; - /* Prepare data for writing. */ - for (i = 0; i < bk_cnt; ++i) { - int err; + ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)pos); + if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { + errno = EINVAL; + return -1; + } + if (!bk_cnt) + return 0; + /* Prepare data for writing. */ + for (i = 0; i < bk_cnt; ++i) { + int err; - err = ntfs_mst_pre_write_fixup((NTFS_RECORD*) - ((u8*)src + i * bk_size), bk_size); - if (err < 0) { - /* Abort write at this position. */ - ntfs_log_perror("%s #1", __FUNCTION__); - if (!i) - return err; - bk_cnt = i; - break; - } - } - /* Write the prepared data. */ - written = ntfs_attr_pwrite(na, pos, bk_cnt * bk_size, src); - if (written <= 0) { - ntfs_log_perror("%s: written=%lld", __FUNCTION__, - (long long)written); - } - /* Quickly deprotect the data again. */ - for (i = 0; i < bk_cnt; ++i) - ntfs_mst_post_write_fixup((NTFS_RECORD*)((u8*)src + i * - bk_size)); - if (written <= 0) - return written; - /* Finally, return the number of complete blocks written. */ - return written / bk_size; + err = ntfs_mst_pre_write_fixup((NTFS_RECORD*) + ((u8*)src + i * bk_size), bk_size); + if (err < 0) { + /* Abort write at this position. */ + ntfs_log_perror("%s #1", __FUNCTION__); + if (!i) + return err; + bk_cnt = i; + break; + } + } + /* Write the prepared data. */ + written = ntfs_attr_pwrite(na, pos, bk_cnt * bk_size, src); + if (written <= 0) { + ntfs_log_perror("%s: written=%lld", __FUNCTION__, + (long long)written); + } + /* Quickly deprotect the data again. */ + for (i = 0; i < bk_cnt; ++i) + ntfs_mst_post_write_fixup((NTFS_RECORD*)((u8*)src + i * + bk_size)); + if (written <= 0) + return written; + /* Finally, return the number of complete blocks written. */ + return written / bk_size; } /** @@ -2115,161 +2132,164 @@ s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, * non-resident as this most likely will result in a crash! */ static int ntfs_attr_find(const ATTR_TYPES type, const ntfschar *name, - const u32 name_len, const IGNORE_CASE_BOOL ic, - const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx) { - ATTR_RECORD *a; - ntfs_volume *vol; - ntfschar *upcase; - u32 upcase_len; + const u32 name_len, const IGNORE_CASE_BOOL ic, + const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx) +{ + ATTR_RECORD *a; + ntfs_volume *vol; + ntfschar *upcase; + u32 upcase_len; - ntfs_log_trace("attribute type 0x%x.\n", type); + ntfs_log_trace("attribute type 0x%x.\n", type); - if (ctx->ntfs_ino) { - vol = ctx->ntfs_ino->vol; - upcase = vol->upcase; - upcase_len = vol->upcase_len; - } else { - if (name && name != AT_UNNAMED) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } - vol = NULL; - upcase = NULL; - upcase_len = 0; - } - /* - * Iterate over attributes in mft record starting at @ctx->attr, or the - * attribute following that, if @ctx->is_first is TRUE. - */ - if (ctx->is_first) { - a = ctx->attr; - ctx->is_first = FALSE; - } else - a = (ATTR_RECORD*)((char*)ctx->attr + - le32_to_cpu(ctx->attr->length)); - for (;; a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length))) { - if (p2n(a) < p2n(ctx->mrec) || (char*)a > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_allocated)) - break; - ctx->attr = a; - if (((type != AT_UNUSED) && (le32_to_cpu(a->type) > - le32_to_cpu(type))) || - (a->type == AT_END)) { - errno = ENOENT; - return -1; - } - if (!a->length) - break; - /* If this is an enumeration return this attribute. */ - if (type == AT_UNUSED) - return 0; - if (a->type != type) - continue; - /* - * If @name is AT_UNNAMED we want an unnamed attribute. - * If @name is present, compare the two names. - * Otherwise, match any attribute. - */ - if (name == AT_UNNAMED) { - /* The search failed if the found attribute is named. */ - if (a->name_length) { - errno = ENOENT; - return -1; - } - } else if (name && !ntfs_names_are_equal(name, name_len, - (ntfschar*)((char*)a + le16_to_cpu(a->name_offset)), - a->name_length, ic, upcase, upcase_len)) { - register int rc; + if (ctx->ntfs_ino) { + vol = ctx->ntfs_ino->vol; + upcase = vol->upcase; + upcase_len = vol->upcase_len; + } else { + if (name && name != AT_UNNAMED) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } + vol = NULL; + upcase = NULL; + upcase_len = 0; + } + /* + * Iterate over attributes in mft record starting at @ctx->attr, or the + * attribute following that, if @ctx->is_first is TRUE. + */ + if (ctx->is_first) { + a = ctx->attr; + ctx->is_first = FALSE; + } else + a = (ATTR_RECORD*)((char*)ctx->attr + + le32_to_cpu(ctx->attr->length)); + for (;; a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length))) { + if (p2n(a) < p2n(ctx->mrec) || (char*)a > (char*)ctx->mrec + + le32_to_cpu(ctx->mrec->bytes_allocated)) + break; + ctx->attr = a; + if (((type != AT_UNUSED) && (le32_to_cpu(a->type) > + le32_to_cpu(type))) || + (a->type == AT_END)) { + errno = ENOENT; + return -1; + } + if (!a->length) + break; + /* If this is an enumeration return this attribute. */ + if (type == AT_UNUSED) + return 0; + if (a->type != type) + continue; + /* + * If @name is AT_UNNAMED we want an unnamed attribute. + * If @name is present, compare the two names. + * Otherwise, match any attribute. + */ + if (name == AT_UNNAMED) { + /* The search failed if the found attribute is named. */ + if (a->name_length) { + errno = ENOENT; + return -1; + } + } else if (name && !ntfs_names_are_equal(name, name_len, + (ntfschar*)((char*)a + le16_to_cpu(a->name_offset)), + a->name_length, ic, upcase, upcase_len)) { + register int rc; - rc = ntfs_names_collate(name, name_len, - (ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, 1, IGNORE_CASE, - upcase, upcase_len); - /* - * If @name collates before a->name, there is no - * matching attribute. - */ - if (rc == -1) { - errno = ENOENT; - return -1; - } - /* If the strings are not equal, continue search. */ - if (rc) - continue; - rc = ntfs_names_collate(name, name_len, - (ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, 1, CASE_SENSITIVE, - upcase, upcase_len); - if (rc == -1) { - errno = ENOENT; - return -1; - } - if (rc) - continue; - } - /* - * The names match or @name not present and attribute is - * unnamed. If no @val specified, we have found the attribute - * and are done. - */ - if (!val) - return 0; - /* @val is present; compare values. */ - else { - register int rc; + rc = ntfs_names_collate(name, name_len, + (ntfschar*)((char*)a + + le16_to_cpu(a->name_offset)), + a->name_length, 1, IGNORE_CASE, + upcase, upcase_len); + /* + * If @name collates before a->name, there is no + * matching attribute. + */ + if (rc == -1) { + errno = ENOENT; + return -1; + } + /* If the strings are not equal, continue search. */ + if (rc) + continue; + rc = ntfs_names_collate(name, name_len, + (ntfschar*)((char*)a + + le16_to_cpu(a->name_offset)), + a->name_length, 1, CASE_SENSITIVE, + upcase, upcase_len); + if (rc == -1) { + errno = ENOENT; + return -1; + } + if (rc) + continue; + } + /* + * The names match or @name not present and attribute is + * unnamed. If no @val specified, we have found the attribute + * and are done. + */ + if (!val) + return 0; + /* @val is present; compare values. */ + else { + register int rc; - rc = memcmp(val, (char*)a +le16_to_cpu(a->value_offset), - min(val_len, - le32_to_cpu(a->value_length))); - /* - * If @val collates before the current attribute's - * value, there is no matching attribute. - */ - if (!rc) { - register u32 avl; - avl = le32_to_cpu(a->value_length); - if (val_len == avl) - return 0; - if (val_len < avl) { - errno = ENOENT; - return -1; - } - } else if (rc < 0) { - errno = ENOENT; - return -1; - } - } - } - errno = EIO; - ntfs_log_perror("%s: Corrupt inode (%lld)", __FUNCTION__, - ctx->ntfs_ino ? (long long)ctx->ntfs_ino->mft_no : -1); - return -1; + rc = memcmp(val, (char*)a +le16_to_cpu(a->value_offset), + min(val_len, + le32_to_cpu(a->value_length))); + /* + * If @val collates before the current attribute's + * value, there is no matching attribute. + */ + if (!rc) { + register u32 avl; + avl = le32_to_cpu(a->value_length); + if (val_len == avl) + return 0; + if (val_len < avl) { + errno = ENOENT; + return -1; + } + } else if (rc < 0) { + errno = ENOENT; + return -1; + } + } + } + errno = EIO; + ntfs_log_perror("%s: Corrupt inode (%lld)", __FUNCTION__, + ctx->ntfs_ino ? (long long)ctx->ntfs_ino->mft_no : -1); + return -1; } -void ntfs_attr_name_free(char **name) { - if (*name) { - free(*name); - *name = NULL; - } +void ntfs_attr_name_free(char **name) +{ + if (*name) { + free(*name); + *name = NULL; + } } -char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) { - char *name = NULL; - int name_len; +char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) +{ + char *name = NULL; + int name_len; - name_len = ntfs_ucstombs(uname, uname_len, &name, 0); - if (name_len < 0) { - ntfs_log_perror("ntfs_ucstombs"); - return NULL; + name_len = ntfs_ucstombs(uname, uname_len, &name, 0); + if (name_len < 0) { + ntfs_log_perror("ntfs_ucstombs"); + return NULL; - } else if (name_len > 0) - return name; + } else if (name_len > 0) + return name; - ntfs_attr_name_free(&name); - return NULL; + ntfs_attr_name_free(&name); + return NULL; } /** @@ -2343,342 +2363,343 @@ char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) { * ENOMEM Not enough memory to allocate necessary buffers. */ static int ntfs_external_attr_find(ATTR_TYPES type, const ntfschar *name, - const u32 name_len, const IGNORE_CASE_BOOL ic, - const VCN lowest_vcn, const u8 *val, const u32 val_len, - ntfs_attr_search_ctx *ctx) { - ntfs_inode *base_ni, *ni; - ntfs_volume *vol; - ATTR_LIST_ENTRY *al_entry, *next_al_entry; - u8 *al_start, *al_end; - ATTR_RECORD *a; - ntfschar *al_name; - u32 al_name_len; - BOOL is_first_search = FALSE; + const u32 name_len, const IGNORE_CASE_BOOL ic, + const VCN lowest_vcn, const u8 *val, const u32 val_len, + ntfs_attr_search_ctx *ctx) +{ + ntfs_inode *base_ni, *ni; + ntfs_volume *vol; + ATTR_LIST_ENTRY *al_entry, *next_al_entry; + u8 *al_start, *al_end; + ATTR_RECORD *a; + ntfschar *al_name; + u32 al_name_len; + BOOL is_first_search = FALSE; - ni = ctx->ntfs_ino; - base_ni = ctx->base_ntfs_ino; - ntfs_log_trace("Entering for inode %lld, attribute type 0x%x.\n", - (unsigned long long)ni->mft_no, type); - if (!base_ni) { - /* First call happens with the base mft record. */ - base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino; - ctx->base_mrec = ctx->mrec; - } - if (ni == base_ni) - ctx->base_attr = ctx->attr; - if (type == AT_END) - goto not_found; - vol = base_ni->vol; - al_start = base_ni->attr_list; - al_end = al_start + base_ni->attr_list_size; - if (!ctx->al_entry) { - ctx->al_entry = (ATTR_LIST_ENTRY*)al_start; - is_first_search = TRUE; - } - /* - * Iterate over entries in attribute list starting at @ctx->al_entry, - * or the entry following that, if @ctx->is_first is TRUE. - */ - if (ctx->is_first) { - al_entry = ctx->al_entry; - ctx->is_first = FALSE; - /* - * If an enumeration and the first attribute is higher than - * the attribute list itself, need to return the attribute list - * attribute. - */ - if ((type == AT_UNUSED) && is_first_search && - le32_to_cpu(al_entry->type) > - le32_to_cpu(AT_ATTRIBUTE_LIST)) - goto find_attr_list_attr; - } else { - al_entry = (ATTR_LIST_ENTRY*)((char*)ctx->al_entry + - le16_to_cpu(ctx->al_entry->length)); - /* - * If this is an enumeration and the attribute list attribute - * is the next one in the enumeration sequence, just return the - * attribute list attribute from the base mft record as it is - * not listed in the attribute list itself. - */ - if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) < - le32_to_cpu(AT_ATTRIBUTE_LIST) && - le32_to_cpu(al_entry->type) > - le32_to_cpu(AT_ATTRIBUTE_LIST)) { - int rc; + ni = ctx->ntfs_ino; + base_ni = ctx->base_ntfs_ino; + ntfs_log_trace("Entering for inode %lld, attribute type 0x%x.\n", + (unsigned long long)ni->mft_no, type); + if (!base_ni) { + /* First call happens with the base mft record. */ + base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino; + ctx->base_mrec = ctx->mrec; + } + if (ni == base_ni) + ctx->base_attr = ctx->attr; + if (type == AT_END) + goto not_found; + vol = base_ni->vol; + al_start = base_ni->attr_list; + al_end = al_start + base_ni->attr_list_size; + if (!ctx->al_entry) { + ctx->al_entry = (ATTR_LIST_ENTRY*)al_start; + is_first_search = TRUE; + } + /* + * Iterate over entries in attribute list starting at @ctx->al_entry, + * or the entry following that, if @ctx->is_first is TRUE. + */ + if (ctx->is_first) { + al_entry = ctx->al_entry; + ctx->is_first = FALSE; + /* + * If an enumeration and the first attribute is higher than + * the attribute list itself, need to return the attribute list + * attribute. + */ + if ((type == AT_UNUSED) && is_first_search && + le32_to_cpu(al_entry->type) > + le32_to_cpu(AT_ATTRIBUTE_LIST)) + goto find_attr_list_attr; + } else { + al_entry = (ATTR_LIST_ENTRY*)((char*)ctx->al_entry + + le16_to_cpu(ctx->al_entry->length)); + /* + * If this is an enumeration and the attribute list attribute + * is the next one in the enumeration sequence, just return the + * attribute list attribute from the base mft record as it is + * not listed in the attribute list itself. + */ + if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) < + le32_to_cpu(AT_ATTRIBUTE_LIST) && + le32_to_cpu(al_entry->type) > + le32_to_cpu(AT_ATTRIBUTE_LIST)) { + int rc; find_attr_list_attr: - /* Check for bogus calls. */ - if (name || name_len || val || val_len || lowest_vcn) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } + /* Check for bogus calls. */ + if (name || name_len || val || val_len || lowest_vcn) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } - /* We want the base record. */ - ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - ctx->is_first = TRUE; - /* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); + /* We want the base record. */ + ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + ctx->is_first = TRUE; + /* Sanity checks are performed elsewhere. */ + ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); - /* Find the attribute list attribute. */ - rc = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0, - IGNORE_CASE, NULL, 0, ctx); + /* Find the attribute list attribute. */ + rc = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0, + IGNORE_CASE, NULL, 0, ctx); - /* - * Setup the search context so the correct - * attribute is returned next time round. - */ - ctx->al_entry = al_entry; - ctx->is_first = TRUE; + /* + * Setup the search context so the correct + * attribute is returned next time round. + */ + ctx->al_entry = al_entry; + ctx->is_first = TRUE; - /* Got it. Done. */ - if (!rc) - return 0; + /* Got it. Done. */ + if (!rc) + return 0; - /* Error! If other than not found return it. */ - if (errno != ENOENT) - return rc; + /* Error! If other than not found return it. */ + if (errno != ENOENT) + return rc; - /* Not found?!? Absurd! */ - errno = EIO; - ntfs_log_error("Attribute list wasn't found"); - return -1; - } - } - for (;; al_entry = next_al_entry) { - /* Out of bounds check. */ - if ((u8*)al_entry < base_ni->attr_list || - (u8*)al_entry > al_end) - break; /* Inode is corrupt. */ - ctx->al_entry = al_entry; - /* Catch the end of the attribute list. */ - if ((u8*)al_entry == al_end) - goto not_found; - if (!al_entry->length) - break; - if ((u8*)al_entry + 6 > al_end || (u8*)al_entry + - le16_to_cpu(al_entry->length) > al_end) - break; - next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry + - le16_to_cpu(al_entry->length)); - if (type != AT_UNUSED) { - if (le32_to_cpu(al_entry->type) > le32_to_cpu(type)) - goto not_found; - if (type != al_entry->type) - continue; - } - al_name_len = al_entry->name_length; - al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset); - /* - * If !@type we want the attribute represented by this - * attribute list entry. - */ - if (type == AT_UNUSED) - goto is_enumeration; - /* - * If @name is AT_UNNAMED we want an unnamed attribute. - * If @name is present, compare the two names. - * Otherwise, match any attribute. - */ - if (name == AT_UNNAMED) { - if (al_name_len) - goto not_found; - } else if (name && !ntfs_names_are_equal(al_name, al_name_len, - name, name_len, ic, vol->upcase, - vol->upcase_len)) { - register int rc; + /* Not found?!? Absurd! */ + errno = EIO; + ntfs_log_error("Attribute list wasn't found"); + return -1; + } + } + for (;; al_entry = next_al_entry) { + /* Out of bounds check. */ + if ((u8*)al_entry < base_ni->attr_list || + (u8*)al_entry > al_end) + break; /* Inode is corrupt. */ + ctx->al_entry = al_entry; + /* Catch the end of the attribute list. */ + if ((u8*)al_entry == al_end) + goto not_found; + if (!al_entry->length) + break; + if ((u8*)al_entry + 6 > al_end || (u8*)al_entry + + le16_to_cpu(al_entry->length) > al_end) + break; + next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry + + le16_to_cpu(al_entry->length)); + if (type != AT_UNUSED) { + if (le32_to_cpu(al_entry->type) > le32_to_cpu(type)) + goto not_found; + if (type != al_entry->type) + continue; + } + al_name_len = al_entry->name_length; + al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset); + /* + * If !@type we want the attribute represented by this + * attribute list entry. + */ + if (type == AT_UNUSED) + goto is_enumeration; + /* + * If @name is AT_UNNAMED we want an unnamed attribute. + * If @name is present, compare the two names. + * Otherwise, match any attribute. + */ + if (name == AT_UNNAMED) { + if (al_name_len) + goto not_found; + } else if (name && !ntfs_names_are_equal(al_name, al_name_len, + name, name_len, ic, vol->upcase, + vol->upcase_len)) { + register int rc; - rc = ntfs_names_collate(name, name_len, al_name, - al_name_len, 1, IGNORE_CASE, - vol->upcase, vol->upcase_len); - /* - * If @name collates before al_name, there is no - * matching attribute. - */ - if (rc == -1) - goto not_found; - /* If the strings are not equal, continue search. */ - if (rc) - continue; - /* - * FIXME: Reverse engineering showed 0, IGNORE_CASE but - * that is inconsistent with ntfs_attr_find(). The - * subsequent rc checks were also different. Perhaps I - * made a mistake in one of the two. Need to recheck - * which is correct or at least see what is going - * on... (AIA) - */ - rc = ntfs_names_collate(name, name_len, al_name, - al_name_len, 1, CASE_SENSITIVE, - vol->upcase, vol->upcase_len); - if (rc == -1) - goto not_found; - if (rc) - continue; - } - /* - * The names match or @name not present and attribute is - * unnamed. Now check @lowest_vcn. Continue search if the - * next attribute list entry still fits @lowest_vcn. Otherwise - * we have reached the right one or the search has failed. - */ - if (lowest_vcn && (u8*)next_al_entry >= al_start && - (u8*)next_al_entry + 6 < al_end && - (u8*)next_al_entry + le16_to_cpu( - next_al_entry->length) <= al_end && - sle64_to_cpu(next_al_entry->lowest_vcn) <= - lowest_vcn && - next_al_entry->type == al_entry->type && - next_al_entry->name_length == al_name_len && - ntfs_names_are_equal((ntfschar*)((char*) - next_al_entry + - next_al_entry->name_offset), - next_al_entry->name_length, - al_name, al_name_len, CASE_SENSITIVE, - vol->upcase, vol->upcase_len)) - continue; + rc = ntfs_names_collate(name, name_len, al_name, + al_name_len, 1, IGNORE_CASE, + vol->upcase, vol->upcase_len); + /* + * If @name collates before al_name, there is no + * matching attribute. + */ + if (rc == -1) + goto not_found; + /* If the strings are not equal, continue search. */ + if (rc) + continue; + /* + * FIXME: Reverse engineering showed 0, IGNORE_CASE but + * that is inconsistent with ntfs_attr_find(). The + * subsequent rc checks were also different. Perhaps I + * made a mistake in one of the two. Need to recheck + * which is correct or at least see what is going + * on... (AIA) + */ + rc = ntfs_names_collate(name, name_len, al_name, + al_name_len, 1, CASE_SENSITIVE, + vol->upcase, vol->upcase_len); + if (rc == -1) + goto not_found; + if (rc) + continue; + } + /* + * The names match or @name not present and attribute is + * unnamed. Now check @lowest_vcn. Continue search if the + * next attribute list entry still fits @lowest_vcn. Otherwise + * we have reached the right one or the search has failed. + */ + if (lowest_vcn && (u8*)next_al_entry >= al_start && + (u8*)next_al_entry + 6 < al_end && + (u8*)next_al_entry + le16_to_cpu( + next_al_entry->length) <= al_end && + sle64_to_cpu(next_al_entry->lowest_vcn) <= + lowest_vcn && + next_al_entry->type == al_entry->type && + next_al_entry->name_length == al_name_len && + ntfs_names_are_equal((ntfschar*)((char*) + next_al_entry + + next_al_entry->name_offset), + next_al_entry->name_length, + al_name, al_name_len, CASE_SENSITIVE, + vol->upcase, vol->upcase_len)) + continue; is_enumeration: - if (MREF_LE(al_entry->mft_reference) == ni->mft_no) { - if (MSEQNO_LE(al_entry->mft_reference) != - le16_to_cpu( - ni->mrec->sequence_number)) { - ntfs_log_error("Found stale mft reference in " - "attribute list!\n"); - break; - } - } else { /* Mft references do not match. */ - /* Do we want the base record back? */ - if (MREF_LE(al_entry->mft_reference) == - base_ni->mft_no) { - ni = ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - } else { - /* We want an extent record. */ - ni = ntfs_extent_inode_open(base_ni, - al_entry->mft_reference); - if (!ni) - break; - ctx->ntfs_ino = ni; - ctx->mrec = ni->mrec; - } - } - a = ctx->attr = (ATTR_RECORD*)((char*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - /* - * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the - * mft record containing the attribute represented by the - * current al_entry. - * - * We could call into ntfs_attr_find() to find the right - * attribute in this mft record but this would be less - * efficient and not quite accurate as ntfs_attr_find() ignores - * the attribute instance numbers for example which become - * important when one plays with attribute lists. Also, because - * a proper match has been found in the attribute list entry - * above, the comparison can now be optimized. So it is worth - * re-implementing a simplified ntfs_attr_find() here. - * - * Use a manual loop so we can still use break and continue - * with the same meanings as above. - */ + if (MREF_LE(al_entry->mft_reference) == ni->mft_no) { + if (MSEQNO_LE(al_entry->mft_reference) != + le16_to_cpu( + ni->mrec->sequence_number)) { + ntfs_log_error("Found stale mft reference in " + "attribute list!\n"); + break; + } + } else { /* Mft references do not match. */ + /* Do we want the base record back? */ + if (MREF_LE(al_entry->mft_reference) == + base_ni->mft_no) { + ni = ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + } else { + /* We want an extent record. */ + ni = ntfs_extent_inode_open(base_ni, + al_entry->mft_reference); + if (!ni) + break; + ctx->ntfs_ino = ni; + ctx->mrec = ni->mrec; + } + } + a = ctx->attr = (ATTR_RECORD*)((char*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); + /* + * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the + * mft record containing the attribute represented by the + * current al_entry. + * + * We could call into ntfs_attr_find() to find the right + * attribute in this mft record but this would be less + * efficient and not quite accurate as ntfs_attr_find() ignores + * the attribute instance numbers for example which become + * important when one plays with attribute lists. Also, because + * a proper match has been found in the attribute list entry + * above, the comparison can now be optimized. So it is worth + * re-implementing a simplified ntfs_attr_find() here. + * + * Use a manual loop so we can still use break and continue + * with the same meanings as above. + */ do_next_attr_loop: - if ((char*)a < (char*)ctx->mrec || (char*)a > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_allocated)) - break; - if (a->type == AT_END) - continue; - if (!a->length) - break; - if (al_entry->instance != a->instance) - goto do_next_attr; - /* - * If the type and/or the name are/is mismatched between the - * attribute list entry and the attribute record, there is - * corruption so we break and return error EIO. - */ - if (al_entry->type != a->type) - break; - if (!ntfs_names_are_equal((ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, al_name, - al_name_len, CASE_SENSITIVE, - vol->upcase, vol->upcase_len)) - break; - ctx->attr = a; - /* - * If no @val specified or @val specified and it matches, we - * have found it! Also, if !@type, it is an enumeration, so we - * want the current attribute. - */ - if ((type == AT_UNUSED) || !val || (!a->non_resident && - le32_to_cpu(a->value_length) == val_len && - !memcmp((char*)a + le16_to_cpu(a->value_offset), - val, val_len))) { - return 0; - } + if ((char*)a < (char*)ctx->mrec || (char*)a > (char*)ctx->mrec + + le32_to_cpu(ctx->mrec->bytes_allocated)) + break; + if (a->type == AT_END) + continue; + if (!a->length) + break; + if (al_entry->instance != a->instance) + goto do_next_attr; + /* + * If the type and/or the name are/is mismatched between the + * attribute list entry and the attribute record, there is + * corruption so we break and return error EIO. + */ + if (al_entry->type != a->type) + break; + if (!ntfs_names_are_equal((ntfschar*)((char*)a + + le16_to_cpu(a->name_offset)), + a->name_length, al_name, + al_name_len, CASE_SENSITIVE, + vol->upcase, vol->upcase_len)) + break; + ctx->attr = a; + /* + * If no @val specified or @val specified and it matches, we + * have found it! Also, if !@type, it is an enumeration, so we + * want the current attribute. + */ + if ((type == AT_UNUSED) || !val || (!a->non_resident && + le32_to_cpu(a->value_length) == val_len && + !memcmp((char*)a + le16_to_cpu(a->value_offset), + val, val_len))) { + return 0; + } do_next_attr: - /* Proceed to the next attribute in the current mft record. */ - a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length)); - goto do_next_attr_loop; - } - if (ni != base_ni) { - ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - ctx->attr = ctx->base_attr; - } - errno = EIO; - ntfs_log_perror("Inode is corrupt (%lld)", (long long)base_ni->mft_no); - return -1; + /* Proceed to the next attribute in the current mft record. */ + a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length)); + goto do_next_attr_loop; + } + if (ni != base_ni) { + ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + ctx->attr = ctx->base_attr; + } + errno = EIO; + ntfs_log_perror("Inode is corrupt (%lld)", (long long)base_ni->mft_no); + return -1; not_found: - /* - * If we were looking for AT_END or we were enumerating and reached the - * end, we reset the search context @ctx and use ntfs_attr_find() to - * seek to the end of the base mft record. - */ - if (type == AT_UNUSED || type == AT_END) { - ntfs_attr_reinit_search_ctx(ctx); - return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len, - ctx); - } - /* - * The attribute wasn't found. Before we return, we want to ensure - * @ctx->mrec and @ctx->attr indicate the position at which the - * attribute should be inserted in the base mft record. Since we also - * want to preserve @ctx->al_entry we cannot reinitialize the search - * context using ntfs_attr_reinit_search_ctx() as this would set - * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see - * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve - * @ctx->al_entry as the remaining fields (base_*) are identical to - * their non base_ counterparts and we cannot set @ctx->base_attr - * correctly yet as we do not know what @ctx->attr will be set to by - * the call to ntfs_attr_find() below. - */ - ctx->mrec = ctx->base_mrec; - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - ctx->is_first = TRUE; - ctx->ntfs_ino = ctx->base_ntfs_ino; - ctx->base_ntfs_ino = NULL; - ctx->base_mrec = NULL; - ctx->base_attr = NULL; - /* - * In case there are multiple matches in the base mft record, need to - * keep enumerating until we get an attribute not found response (or - * another error), otherwise we would keep returning the same attribute - * over and over again and all programs using us for enumeration would - * lock up in a tight loop. - */ - { - int ret; + /* + * If we were looking for AT_END or we were enumerating and reached the + * end, we reset the search context @ctx and use ntfs_attr_find() to + * seek to the end of the base mft record. + */ + if (type == AT_UNUSED || type == AT_END) { + ntfs_attr_reinit_search_ctx(ctx); + return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len, + ctx); + } + /* + * The attribute wasn't found. Before we return, we want to ensure + * @ctx->mrec and @ctx->attr indicate the position at which the + * attribute should be inserted in the base mft record. Since we also + * want to preserve @ctx->al_entry we cannot reinitialize the search + * context using ntfs_attr_reinit_search_ctx() as this would set + * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see + * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve + * @ctx->al_entry as the remaining fields (base_*) are identical to + * their non base_ counterparts and we cannot set @ctx->base_attr + * correctly yet as we do not know what @ctx->attr will be set to by + * the call to ntfs_attr_find() below. + */ + ctx->mrec = ctx->base_mrec; + ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); + ctx->is_first = TRUE; + ctx->ntfs_ino = ctx->base_ntfs_ino; + ctx->base_ntfs_ino = NULL; + ctx->base_mrec = NULL; + ctx->base_attr = NULL; + /* + * In case there are multiple matches in the base mft record, need to + * keep enumerating until we get an attribute not found response (or + * another error), otherwise we would keep returning the same attribute + * over and over again and all programs using us for enumeration would + * lock up in a tight loop. + */ + { + int ret; - do { - ret = ntfs_attr_find(type, name, name_len, ic, val, - val_len, ctx); - } while (!ret); - return ret; - } + do { + ret = ntfs_attr_find(type, name, name_len, ic, val, + val_len, ctx); + } while (!ret); + return ret; + } } /** @@ -2749,35 +2770,36 @@ not_found: * ENOMEM Not enough memory to allocate necessary buffers. */ int ntfs_attr_lookup(const ATTR_TYPES type, const ntfschar *name, - const u32 name_len, const IGNORE_CASE_BOOL ic, - const VCN lowest_vcn, const u8 *val, const u32 val_len, - ntfs_attr_search_ctx *ctx) { - ntfs_volume *vol; - ntfs_inode *base_ni; - int ret = -1; + const u32 name_len, const IGNORE_CASE_BOOL ic, + const VCN lowest_vcn, const u8 *val, const u32 val_len, + ntfs_attr_search_ctx *ctx) +{ + ntfs_volume *vol; + ntfs_inode *base_ni; + int ret = -1; - ntfs_log_enter("Entering for attribute type 0x%x\n", type); - - if (!ctx || !ctx->mrec || !ctx->attr || (name && name != AT_UNNAMED && - (!ctx->ntfs_ino || !(vol = ctx->ntfs_ino->vol) || - !vol->upcase || !vol->upcase_len))) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto out; - } - - if (ctx->base_ntfs_ino) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; - if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST) - ret = ntfs_attr_find(type, name, name_len, ic, val, val_len, ctx); - else - ret = ntfs_external_attr_find(type, name, name_len, ic, - lowest_vcn, val, val_len, ctx); + ntfs_log_enter("Entering for attribute type 0x%x\n", type); + + if (!ctx || !ctx->mrec || !ctx->attr || (name && name != AT_UNNAMED && + (!ctx->ntfs_ino || !(vol = ctx->ntfs_ino->vol) || + !vol->upcase || !vol->upcase_len))) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + goto out; + } + + if (ctx->base_ntfs_ino) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; + if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST) + ret = ntfs_attr_find(type, name, name_len, ic, val, val_len, ctx); + else + ret = ntfs_external_attr_find(type, name, name_len, ic, + lowest_vcn, val, val_len, ctx); out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } /** @@ -2797,16 +2819,17 @@ out: * ENOMEM Not enough memory to allocate necessary buffers. * ENOSPC No attribute was found after 'type', only AT_END. */ -int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) { - if (ntfs_attr_lookup(type, NULL, 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (errno != ENOENT) - return -1; - if (ctx->attr->type == AT_END) { - errno = ENOSPC; - return -1; - } - } - return 0; +int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) +{ + if (ntfs_attr_lookup(type, NULL, 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (errno != ENOENT) + return -1; + if (ctx->attr->type == AT_END) { + errno = ENOSPC; + return -1; + } + } + return 0; } /** @@ -2818,18 +2841,19 @@ int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) { * Initialize the attribute search context @ctx with @ni and @mrec. */ static void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx, - ntfs_inode *ni, MFT_RECORD *mrec) { - if (!mrec) - mrec = ni->mrec; - ctx->mrec = mrec; - /* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset)); - ctx->is_first = TRUE; - ctx->ntfs_ino = ni; - ctx->al_entry = NULL; - ctx->base_ntfs_ino = NULL; - ctx->base_mrec = NULL; - ctx->base_attr = NULL; + ntfs_inode *ni, MFT_RECORD *mrec) +{ + if (!mrec) + mrec = ni->mrec; + ctx->mrec = mrec; + /* Sanity checks are performed elsewhere. */ + ctx->attr = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset)); + ctx->is_first = TRUE; + ctx->ntfs_ino = ni; + ctx->al_entry = NULL; + ctx->base_ntfs_ino = NULL; + ctx->base_mrec = NULL; + ctx->base_attr = NULL; } /** @@ -2841,22 +2865,23 @@ static void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx, * This is used when a search for a new attribute is being started to reset * the search context to the beginning. */ -void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) { - if (!ctx->base_ntfs_ino) { - /* No attribute list. */ - ctx->is_first = TRUE; - /* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - /* - * This needs resetting due to ntfs_external_attr_find() which - * can leave it set despite having zeroed ctx->base_ntfs_ino. - */ - ctx->al_entry = NULL; - return; - } /* Attribute list. */ - ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec); - return; +void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) +{ + if (!ctx->base_ntfs_ino) { + /* No attribute list. */ + ctx->is_first = TRUE; + /* Sanity checks are performed elsewhere. */ + ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); + /* + * This needs resetting due to ntfs_external_attr_find() which + * can leave it set despite having zeroed ctx->base_ntfs_ino. + */ + ctx->al_entry = NULL; + return; + } /* Attribute list. */ + ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec); + return; } /** @@ -2873,18 +2898,19 @@ void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) { * be NULL and @mrec to be set. Do NOT do this unless you understand the * implications!!! For example it is no longer safe to call ntfs_attr_lookup(). */ -ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) { - ntfs_attr_search_ctx *ctx; +ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) +{ + ntfs_attr_search_ctx *ctx; - if (!ni && !mrec) { - errno = EINVAL; - ntfs_log_perror("NULL arguments"); - return NULL; - } - ctx = ntfs_malloc(sizeof(ntfs_attr_search_ctx)); - if (ctx) - ntfs_attr_init_search_ctx(ctx, ni, mrec); - return ctx; + if (!ni && !mrec) { + errno = EINVAL; + ntfs_log_perror("NULL arguments"); + return NULL; + } + ctx = ntfs_malloc(sizeof(ntfs_attr_search_ctx)); + if (ctx) + ntfs_attr_init_search_ctx(ctx, ni, mrec); + return ctx; } /** @@ -2893,9 +2919,10 @@ ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) * * Release the attribute search context @ctx. */ -void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) { - // NOTE: save errno if it could change and function stays void! - free(ctx); +void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) +{ + // NOTE: save errno if it could change and function stays void! + free(ctx); } /** @@ -2913,28 +2940,29 @@ void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) { * EINVAL - Invalid parameters (e.g. @vol is not valid). */ ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, - const ATTR_TYPES type) { - ATTR_DEF *ad; + const ATTR_TYPES type) +{ + ATTR_DEF *ad; - if (!vol || !vol->attrdef || !type) { - errno = EINVAL; - ntfs_log_perror("%s: type=%d", __FUNCTION__, type); - return NULL; - } - for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef < - vol->attrdef_len && ad->type; ++ad) { - /* We haven't found it yet, carry on searching. */ - if (le32_to_cpu(ad->type) < le32_to_cpu(type)) - continue; - /* We found the attribute; return it. */ - if (ad->type == type) - return ad; - /* We have gone too far already. No point in continuing. */ - break; - } - errno = ENOENT; - ntfs_log_perror("%s: type=%d", __FUNCTION__, type); - return NULL; + if (!vol || !vol->attrdef || !type) { + errno = EINVAL; + ntfs_log_perror("%s: type=%d", __FUNCTION__, type); + return NULL; + } + for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef < + vol->attrdef_len && ad->type; ++ad) { + /* We haven't found it yet, carry on searching. */ + if (le32_to_cpu(ad->type) < le32_to_cpu(type)) + continue; + /* We found the attribute; return it. */ + if (ad->type == type) + return ad; + /* We have gone too far already. No point in continuing. */ + break; + } + errno = ENOENT; + ntfs_log_perror("%s: type=%d", __FUNCTION__, type); + return NULL; } /** @@ -2953,43 +2981,44 @@ ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, * EINVAL - Invalid parameters (e.g. @size is < 0 or @vol is not valid). */ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type, - const s64 size) { - ATTR_DEF *ad; - s64 min_size, max_size; + const s64 size) +{ + ATTR_DEF *ad; + s64 min_size, max_size; - if (size < 0) { - errno = EINVAL; - ntfs_log_perror("%s: size=%lld", __FUNCTION__, - (long long)size); - return -1; - } + if (size < 0) { + errno = EINVAL; + ntfs_log_perror("%s: size=%lld", __FUNCTION__, + (long long)size); + return -1; + } - /* - * $ATTRIBUTE_LIST shouldn't be greater than 0x40000, otherwise - * Windows would crash. This is not listed in the AttrDef. - */ - if (type == AT_ATTRIBUTE_LIST && size > 0x40000) { - errno = ERANGE; - ntfs_log_perror("Too large attrlist (%lld)", (long long)size); - return -1; - } + /* + * $ATTRIBUTE_LIST shouldn't be greater than 0x40000, otherwise + * Windows would crash. This is not listed in the AttrDef. + */ + if (type == AT_ATTRIBUTE_LIST && size > 0x40000) { + errno = ERANGE; + ntfs_log_perror("Too large attrlist (%lld)", (long long)size); + return -1; + } - ad = ntfs_attr_find_in_attrdef(vol, type); - if (!ad) - return -1; - - min_size = sle64_to_cpu(ad->min_size); - max_size = sle64_to_cpu(ad->max_size); - - if ((min_size && (size < min_size)) || - ((max_size > 0) && (size > max_size))) { - errno = ERANGE; - ntfs_log_perror("Attr type %d size check failed (min,size,max=" - "%lld,%lld,%lld)", type, (long long)min_size, - (long long)size, (long long)max_size); - return -1; - } - return 0; + ad = ntfs_attr_find_in_attrdef(vol, type); + if (!ad) + return -1; + + min_size = sle64_to_cpu(ad->min_size); + max_size = sle64_to_cpu(ad->max_size); + + if ((min_size && (size < min_size)) || + ((max_size > 0) && (size > max_size))) { + errno = ERANGE; + ntfs_log_perror("Attr type %d size check failed (min,size,max=" + "%lld,%lld,%lld)", type, (long long)min_size, + (long long)size, (long long)max_size); + return -1; + } + return 0; } /** @@ -3012,37 +3041,38 @@ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type, * EINVAL - Invalid parameters (e.g. @vol is not valid). */ static int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type, - const ntfschar *name, int name_len) { - ATTR_DEF *ad; - BOOL allowed; + const ntfschar *name, int name_len) +{ + ATTR_DEF *ad; + BOOL allowed; - /* - * Microsoft has decreed that $LOGGED_UTILITY_STREAM attributes with a - * name of $TXF_DATA must be resident despite the entry for - * $LOGGED_UTILITY_STREAM in $AttrDef allowing them to be non-resident. - * Failure to obey this on the root directory mft record of a volume - * causes Windows Vista and later to see the volume as a RAW volume and - * thus cannot mount it at all. - */ - if ((type == AT_LOGGED_UTILITY_STREAM) - && name - && ntfs_names_are_equal(TXF_DATA, 9, name, name_len, - CASE_SENSITIVE, vol->upcase, vol->upcase_len)) - allowed = FALSE; - else { - /* Find the attribute definition record in $AttrDef. */ - ad = ntfs_attr_find_in_attrdef(vol, type); - if (!ad) - return -1; - /* Check the flags and return the result. */ - allowed = !(ad->flags & ATTR_DEF_RESIDENT); - } - if (!allowed) { - errno = EPERM; - ntfs_log_trace("Attribute can't be non-resident\n"); - return -1; - } - return 0; + /* + * Microsoft has decreed that $LOGGED_UTILITY_STREAM attributes with a + * name of $TXF_DATA must be resident despite the entry for + * $LOGGED_UTILITY_STREAM in $AttrDef allowing them to be non-resident. + * Failure to obey this on the root directory mft record of a volume + * causes Windows Vista and later to see the volume as a RAW volume and + * thus cannot mount it at all. + */ + if ((type == AT_LOGGED_UTILITY_STREAM) + && name + && ntfs_names_are_equal(TXF_DATA, 9, name, name_len, + CASE_SENSITIVE, vol->upcase, vol->upcase_len)) + allowed = FALSE; + else { + /* Find the attribute definition record in $AttrDef. */ + ad = ntfs_attr_find_in_attrdef(vol, type); + if (!ad) + return -1; + /* Check the flags and return the result. */ + allowed = !(ad->flags & ATTR_DEF_RESIDENT); + } + if (!allowed) { + errno = EPERM; + ntfs_log_trace("Attribute can't be non-resident\n"); + return -1; + } + return 0; } /** @@ -3067,17 +3097,18 @@ static int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPE * check for this here as we don't know which inode's $Bitmap is being * asked about so the caller needs to special case this. */ -int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) { - if (!vol || !vol->attrdef || !type) { - errno = EINVAL; - return -1; - } - if (type != AT_INDEX_ALLOCATION) - return 0; - - ntfs_log_trace("Attribute can't be resident\n"); - errno = EPERM; - return -1; +int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) +{ + if (!vol || !vol->attrdef || !type) { + errno = EINVAL; + return -1; + } + if (type != AT_INDEX_ALLOCATION) + return 0; + + ntfs_log_trace("Attribute can't be resident\n"); + errno = EPERM; + return -1; } /** @@ -3094,43 +3125,44 @@ int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) { * caller has to make space before calling this. * EINVAL - Input parameters were faulty. */ -int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) { - u32 biu; +int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) +{ + u32 biu; - ntfs_log_trace("Entering for pos 0x%d, size %u.\n", - (int)(pos - (u8*)m), (unsigned) size); + ntfs_log_trace("Entering for pos 0x%d, size %u.\n", + (int)(pos - (u8*)m), (unsigned) size); - /* Make size 8-byte alignment. */ - size = (size + 7) & ~7; + /* Make size 8-byte alignment. */ + size = (size + 7) & ~7; - /* Rigorous consistency checks. */ - if (!m || !pos || pos < (u8*)m) { - errno = EINVAL; - ntfs_log_perror("%s: pos=%p m=%p", __FUNCTION__, pos, m); - return -1; - } - /* The -8 is for the attribute terminator. */ - if (pos - (u8*)m > (int)le32_to_cpu(m->bytes_in_use) - 8) { - errno = EINVAL; - return -1; - } - /* Nothing to do. */ - if (!size) - return 0; + /* Rigorous consistency checks. */ + if (!m || !pos || pos < (u8*)m) { + errno = EINVAL; + ntfs_log_perror("%s: pos=%p m=%p", __FUNCTION__, pos, m); + return -1; + } + /* The -8 is for the attribute terminator. */ + if (pos - (u8*)m > (int)le32_to_cpu(m->bytes_in_use) - 8) { + errno = EINVAL; + return -1; + } + /* Nothing to do. */ + if (!size) + return 0; - biu = le32_to_cpu(m->bytes_in_use); - /* Do we have enough space? */ - if (biu + size > le32_to_cpu(m->bytes_allocated) || - pos + size > (u8*)m + le32_to_cpu(m->bytes_allocated)) { - errno = ENOSPC; - ntfs_log_trace("No enough space in the MFT record\n"); - return -1; - } - /* Move everything after pos to pos + size. */ - memmove(pos + size, pos, biu - (pos - (u8*)m)); - /* Update mft record. */ - m->bytes_in_use = cpu_to_le32(biu + size); - return 0; + biu = le32_to_cpu(m->bytes_in_use); + /* Do we have enough space? */ + if (biu + size > le32_to_cpu(m->bytes_allocated) || + pos + size > (u8*)m + le32_to_cpu(m->bytes_allocated)) { + errno = ENOSPC; + ntfs_log_trace("No enough space in the MFT record\n"); + return -1; + } + /* Move everything after pos to pos + size. */ + memmove(pos + size, pos, biu - (pos - (u8*)m)); + /* Update mft record. */ + m->bytes_in_use = cpu_to_le32(biu + size); + return 0; } /** @@ -3151,113 +3183,114 @@ int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) { * EIO - I/O error occurred or damaged filesystem. */ int ntfs_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, u8 *val, u32 size, - ATTR_FLAGS data_flags) { - ntfs_attr_search_ctx *ctx; - u32 length; - ATTR_RECORD *a; - MFT_RECORD *m; - int err, offset; - ntfs_inode *base_ni; + ntfschar *name, u8 name_len, u8 *val, u32 size, + ATTR_FLAGS data_flags) +{ + ntfs_attr_search_ctx *ctx; + u32 length; + ATTR_RECORD *a; + MFT_RECORD *m; + int err, offset; + ntfs_inode *base_ni; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n", - (long long) ni->mft_no, (unsigned) type, (unsigned) data_flags); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n", + (long long) ni->mft_no, (unsigned) type, (unsigned) data_flags); - if (!ni || (!name && name_len)) { - errno = EINVAL; - return -1; - } + if (!ni || (!name && name_len)) { + errno = EINVAL; + return -1; + } - if (ntfs_attr_can_be_resident(ni->vol, type)) { - if (errno == EPERM) - ntfs_log_trace("Attribute can't be resident.\n"); - else - ntfs_log_trace("ntfs_attr_can_be_resident failed.\n"); - return -1; - } + if (ntfs_attr_can_be_resident(ni->vol, type)) { + if (errno == EPERM) + ntfs_log_trace("Attribute can't be resident.\n"); + else + ntfs_log_trace("ntfs_attr_can_be_resident failed.\n"); + return -1; + } - /* Locate place where record should be. */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; - /* - * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for - * attribute in @ni->mrec, not any extent inode in case if @ni is base - * file record. - */ - if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size, - ctx)) { - err = EEXIST; - ntfs_log_trace("Attribute already present.\n"); - goto put_err_out; - } - if (errno != ENOENT) { - err = EIO; - goto put_err_out; - } - a = ctx->attr; - m = ctx->mrec; + /* Locate place where record should be. */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return -1; + /* + * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for + * attribute in @ni->mrec, not any extent inode in case if @ni is base + * file record. + */ + if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size, + ctx)) { + err = EEXIST; + ntfs_log_trace("Attribute already present.\n"); + goto put_err_out; + } + if (errno != ENOENT) { + err = EIO; + goto put_err_out; + } + a = ctx->attr; + m = ctx->mrec; - /* Make room for attribute. */ - length = offsetof(ATTR_RECORD, resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + - ((size + 7) & ~7); - if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { - err = errno; - ntfs_log_trace("Failed to make room for attribute.\n"); - goto put_err_out; - } + /* Make room for attribute. */ + length = offsetof(ATTR_RECORD, resident_end) + + ((name_len * sizeof(ntfschar) + 7) & ~7) + + ((size + 7) & ~7); + if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { + err = errno; + ntfs_log_trace("Failed to make room for attribute.\n"); + goto put_err_out; + } - /* Setup record fields. */ - offset = ((u8*)a - (u8*)m); - a->type = type; - a->length = cpu_to_le32(length); - a->non_resident = 0; - a->name_length = name_len; - a->name_offset = (name_len - ? cpu_to_le16(offsetof(ATTR_RECORD, resident_end)) - : const_cpu_to_le16(0)); - a->flags = data_flags; - a->instance = m->next_attr_instance; - a->value_length = cpu_to_le32(size); - a->value_offset = cpu_to_le16(length - ((size + 7) & ~7)); - if (val) - memcpy((u8*)a + le16_to_cpu(a->value_offset), val, size); - else - memset((u8*)a + le16_to_cpu(a->value_offset), 0, size); - if (type == AT_FILE_NAME) - a->resident_flags = RESIDENT_ATTR_IS_INDEXED; - else - a->resident_flags = 0; - if (name_len) - memcpy((u8*)a + le16_to_cpu(a->name_offset), - name, sizeof(ntfschar) * name_len); - m->next_attr_instance = - cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); - if (ni->nr_extents == -1) - base_ni = ni->base_ni; - else - base_ni = ni; - if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { - if (ntfs_attrlist_entry_add(ni, a)) { - err = errno; - ntfs_attr_record_resize(m, a, 0); - ntfs_log_trace("Failed add attribute entry to " - "ATTRIBUTE_LIST.\n"); - goto put_err_out; - } - } - if (type == AT_DATA && name == AT_UNNAMED) { - ni->data_size = size; - ni->allocated_size = (size + 7) & ~7; - } - ntfs_inode_mark_dirty(ni); - ntfs_attr_put_search_ctx(ctx); - return offset; + /* Setup record fields. */ + offset = ((u8*)a - (u8*)m); + a->type = type; + a->length = cpu_to_le32(length); + a->non_resident = 0; + a->name_length = name_len; + a->name_offset = (name_len + ? cpu_to_le16(offsetof(ATTR_RECORD, resident_end)) + : const_cpu_to_le16(0)); + a->flags = data_flags; + a->instance = m->next_attr_instance; + a->value_length = cpu_to_le32(size); + a->value_offset = cpu_to_le16(length - ((size + 7) & ~7)); + if (val) + memcpy((u8*)a + le16_to_cpu(a->value_offset), val, size); + else + memset((u8*)a + le16_to_cpu(a->value_offset), 0, size); + if (type == AT_FILE_NAME) + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + else + a->resident_flags = 0; + if (name_len) + memcpy((u8*)a + le16_to_cpu(a->name_offset), + name, sizeof(ntfschar) * name_len); + m->next_attr_instance = + cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); + if (ni->nr_extents == -1) + base_ni = ni->base_ni; + else + base_ni = ni; + if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { + if (ntfs_attrlist_entry_add(ni, a)) { + err = errno; + ntfs_attr_record_resize(m, a, 0); + ntfs_log_trace("Failed add attribute entry to " + "ATTRIBUTE_LIST.\n"); + goto put_err_out; + } + } + if (type == AT_DATA && name == AT_UNNAMED) { + ni->data_size = size; + ni->allocated_size = (size + 7) & ~7; + } + ntfs_inode_mark_dirty(ni); + ntfs_attr_put_search_ctx(ctx); + return offset; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } /** @@ -3279,129 +3312,130 @@ put_err_out: * EIO - I/O error occurred or damaged filesystem. */ int ntfs_non_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size, - ATTR_FLAGS flags) { - ntfs_attr_search_ctx *ctx; - u32 length; - ATTR_RECORD *a; - MFT_RECORD *m; - ntfs_inode *base_ni; - int err, offset; + ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size, + ATTR_FLAGS flags) +{ + ntfs_attr_search_ctx *ctx; + u32 length; + ATTR_RECORD *a; + MFT_RECORD *m; + ntfs_inode *base_ni; + int err, offset; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, " - "dataruns_size %d, flags 0x%x.\n", - (long long) ni->mft_no, (unsigned) type, - (long long) lowest_vcn, dataruns_size, (unsigned) flags); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, " + "dataruns_size %d, flags 0x%x.\n", + (long long) ni->mft_no, (unsigned) type, + (long long) lowest_vcn, dataruns_size, (unsigned) flags); - if (!ni || dataruns_size <= 0 || (!name && name_len)) { - errno = EINVAL; - return -1; - } + if (!ni || dataruns_size <= 0 || (!name && name_len)) { + errno = EINVAL; + return -1; + } - if (ntfs_attr_can_be_non_resident(ni->vol, type, name, name_len)) { - if (errno == EPERM) - ntfs_log_perror("Attribute can't be non resident"); - else - ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); - return -1; - } + if (ntfs_attr_can_be_non_resident(ni->vol, type, name, name_len)) { + if (errno == EPERM) + ntfs_log_perror("Attribute can't be non resident"); + else + ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); + return -1; + } - /* Locate place where record should be. */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; - /* - * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for - * attribute in @ni->mrec, not any extent inode in case if @ni is base - * file record. - */ - if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, - ctx)) { - err = EEXIST; - ntfs_log_perror("Attribute 0x%x already present", type); - goto put_err_out; - } - if (errno != ENOENT) { - ntfs_log_perror("ntfs_attr_find failed"); - err = EIO; - goto put_err_out; - } - a = ctx->attr; - m = ctx->mrec; + /* Locate place where record should be. */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return -1; + /* + * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for + * attribute in @ni->mrec, not any extent inode in case if @ni is base + * file record. + */ + if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, + ctx)) { + err = EEXIST; + ntfs_log_perror("Attribute 0x%x already present", type); + goto put_err_out; + } + if (errno != ENOENT) { + ntfs_log_perror("ntfs_attr_find failed"); + err = EIO; + goto put_err_out; + } + a = ctx->attr; + m = ctx->mrec; - /* Make room for attribute. */ - dataruns_size = (dataruns_size + 7) & ~7; - length = offsetof(ATTR_RECORD, compressed_size) + ((sizeof(ntfschar) * - name_len + 7) & ~7) + dataruns_size + - ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? - sizeof(a->compressed_size) : 0); - if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { - err = errno; - ntfs_log_perror("Failed to make room for attribute"); - goto put_err_out; - } + /* Make room for attribute. */ + dataruns_size = (dataruns_size + 7) & ~7; + length = offsetof(ATTR_RECORD, compressed_size) + ((sizeof(ntfschar) * + name_len + 7) & ~7) + dataruns_size + + ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? + sizeof(a->compressed_size) : 0); + if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { + err = errno; + ntfs_log_perror("Failed to make room for attribute"); + goto put_err_out; + } - /* Setup record fields. */ - a->type = type; - a->length = cpu_to_le32(length); - a->non_resident = 1; - a->name_length = name_len; - a->name_offset = cpu_to_le16(offsetof(ATTR_RECORD, compressed_size) + - ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? - sizeof(a->compressed_size) : 0)); - a->flags = flags; - a->instance = m->next_attr_instance; - a->lowest_vcn = cpu_to_sle64(lowest_vcn); - a->mapping_pairs_offset = cpu_to_le16(length - dataruns_size); - a->compression_unit = (flags & ATTR_IS_COMPRESSED) - ? STANDARD_COMPRESSION_UNIT : 0; - /* If @lowest_vcn == 0, than setup empty attribute. */ - if (!lowest_vcn) { - a->highest_vcn = cpu_to_sle64(-1); - a->allocated_size = 0; - a->data_size = 0; - a->initialized_size = 0; - /* Set empty mapping pairs. */ - *((u8*)a + le16_to_cpu(a->mapping_pairs_offset)) = 0; - } - if (name_len) - memcpy((u8*)a + le16_to_cpu(a->name_offset), - name, sizeof(ntfschar) * name_len); - m->next_attr_instance = - cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); - if (ni->nr_extents == -1) - base_ni = ni->base_ni; - else - base_ni = ni; - if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { - if (ntfs_attrlist_entry_add(ni, a)) { - err = errno; - ntfs_log_perror("Failed add attr entry to attrlist"); - ntfs_attr_record_resize(m, a, 0); - goto put_err_out; - } - } - ntfs_inode_mark_dirty(ni); - /* - * Locate offset from start of the MFT record where new attribute is - * placed. We need relookup it, because record maybe moved during - * update of attribute list. - */ - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, - lowest_vcn, NULL, 0, ctx)) { - ntfs_log_perror("%s: attribute lookup failed", __FUNCTION__); - ntfs_attr_put_search_ctx(ctx); - return -1; + /* Setup record fields. */ + a->type = type; + a->length = cpu_to_le32(length); + a->non_resident = 1; + a->name_length = name_len; + a->name_offset = cpu_to_le16(offsetof(ATTR_RECORD, compressed_size) + + ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? + sizeof(a->compressed_size) : 0)); + a->flags = flags; + a->instance = m->next_attr_instance; + a->lowest_vcn = cpu_to_sle64(lowest_vcn); + a->mapping_pairs_offset = cpu_to_le16(length - dataruns_size); + a->compression_unit = (flags & ATTR_IS_COMPRESSED) + ? STANDARD_COMPRESSION_UNIT : 0; + /* If @lowest_vcn == 0, than setup empty attribute. */ + if (!lowest_vcn) { + a->highest_vcn = cpu_to_sle64(-1); + a->allocated_size = 0; + a->data_size = 0; + a->initialized_size = 0; + /* Set empty mapping pairs. */ + *((u8*)a + le16_to_cpu(a->mapping_pairs_offset)) = 0; + } + if (name_len) + memcpy((u8*)a + le16_to_cpu(a->name_offset), + name, sizeof(ntfschar) * name_len); + m->next_attr_instance = + cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); + if (ni->nr_extents == -1) + base_ni = ni->base_ni; + else + base_ni = ni; + if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { + if (ntfs_attrlist_entry_add(ni, a)) { + err = errno; + ntfs_log_perror("Failed add attr entry to attrlist"); + ntfs_attr_record_resize(m, a, 0); + goto put_err_out; + } + } + ntfs_inode_mark_dirty(ni); + /* + * Locate offset from start of the MFT record where new attribute is + * placed. We need relookup it, because record maybe moved during + * update of attribute list. + */ + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, + lowest_vcn, NULL, 0, ctx)) { + ntfs_log_perror("%s: attribute lookup failed", __FUNCTION__); + ntfs_attr_put_search_ctx(ctx); + return -1; - } - offset = (u8*)ctx->attr - (u8*)ctx->mrec; - ntfs_attr_put_search_ctx(ctx); - return offset; + } + offset = (u8*)ctx->attr - (u8*)ctx->mrec; + ntfs_attr_put_search_ctx(ctx); + return offset; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } /** @@ -3416,122 +3450,123 @@ put_err_out: * EINVAL - Invalid arguments passed to function. * EIO - I/O error occurred or damaged filesystem. */ -int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) { - ntfs_inode *base_ni, *ni; - ATTR_TYPES type; - int err; +int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) +{ + ntfs_inode *base_ni, *ni; + ATTR_TYPES type; + int err; - if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr) { - errno = EINVAL; - return -1; - } + if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr) { + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", - (long long) ctx->ntfs_ino->mft_no, - (unsigned) le32_to_cpu(ctx->attr->type)); - type = ctx->attr->type; - ni = ctx->ntfs_ino; - if (ctx->base_ntfs_ino) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", + (long long) ctx->ntfs_ino->mft_no, + (unsigned) le32_to_cpu(ctx->attr->type)); + type = ctx->attr->type; + ni = ctx->ntfs_ino; + if (ctx->base_ntfs_ino) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; - /* Remove attribute itself. */ - if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) { - ntfs_log_trace("Couldn't remove attribute record. Bug or damaged MFT " - "record.\n"); - if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) - if (ntfs_attrlist_entry_add(ni, ctx->attr)) - ntfs_log_trace("Rollback failed. Leaving inconstant " - "metadata.\n"); - err = EIO; - return -1; - } - ntfs_inode_mark_dirty(ni); + /* Remove attribute itself. */ + if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) { + ntfs_log_trace("Couldn't remove attribute record. Bug or damaged MFT " + "record.\n"); + if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) + if (ntfs_attrlist_entry_add(ni, ctx->attr)) + ntfs_log_trace("Rollback failed. Leaving inconstant " + "metadata.\n"); + err = EIO; + return -1; + } + ntfs_inode_mark_dirty(ni); - /* - * Remove record from $ATTRIBUTE_LIST if present and we don't want - * delete $ATTRIBUTE_LIST itself. - */ - if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) { - if (ntfs_attrlist_entry_rm(ctx)) { - ntfs_log_trace("Couldn't delete record from " - "$ATTRIBUTE_LIST.\n"); - return -1; - } - } + /* + * Remove record from $ATTRIBUTE_LIST if present and we don't want + * delete $ATTRIBUTE_LIST itself. + */ + if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) { + if (ntfs_attrlist_entry_rm(ctx)) { + ntfs_log_trace("Couldn't delete record from " + "$ATTRIBUTE_LIST.\n"); + return -1; + } + } - /* Post $ATTRIBUTE_LIST delete setup. */ - if (type == AT_ATTRIBUTE_LIST) { - if (NInoAttrList(base_ni) && base_ni->attr_list) - free(base_ni->attr_list); - base_ni->attr_list = NULL; - NInoClearAttrList(base_ni); - NInoAttrListClearDirty(base_ni); - } + /* Post $ATTRIBUTE_LIST delete setup. */ + if (type == AT_ATTRIBUTE_LIST) { + if (NInoAttrList(base_ni) && base_ni->attr_list) + free(base_ni->attr_list); + base_ni->attr_list = NULL; + NInoClearAttrList(base_ni); + NInoAttrListClearDirty(base_ni); + } - /* Free MFT record, if it doesn't contain attributes. */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) - - le16_to_cpu(ctx->mrec->attrs_offset) == 8) { - if (ntfs_mft_record_free(ni->vol, ni)) { - // FIXME: We need rollback here. - ntfs_log_trace("Couldn't free MFT record.\n"); - errno = EIO; - return -1; - } - /* Remove done if we freed base inode. */ - if (ni == base_ni) - return 0; - } + /* Free MFT record, if it doesn't contain attributes. */ + if (le32_to_cpu(ctx->mrec->bytes_in_use) - + le16_to_cpu(ctx->mrec->attrs_offset) == 8) { + if (ntfs_mft_record_free(ni->vol, ni)) { + // FIXME: We need rollback here. + ntfs_log_trace("Couldn't free MFT record.\n"); + errno = EIO; + return -1; + } + /* Remove done if we freed base inode. */ + if (ni == base_ni) + return 0; + } - if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni)) - return 0; + if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni)) + return 0; - /* Remove attribute list if we don't need it any more. */ - if (!ntfs_attrlist_need(base_ni)) { - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - /* - * FIXME: Should we succeed here? Definitely something - * goes wrong because NInoAttrList(base_ni) returned - * that we have got attribute list. - */ - ntfs_log_trace("Couldn't find attribute list. Succeed " - "anyway.\n"); - return 0; - } - /* Deallocate clusters. */ - if (ctx->attr->non_resident) { - runlist *al_rl; + /* Remove attribute list if we don't need it any more. */ + if (!ntfs_attrlist_need(base_ni)) { + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + /* + * FIXME: Should we succeed here? Definitely something + * goes wrong because NInoAttrList(base_ni) returned + * that we have got attribute list. + */ + ntfs_log_trace("Couldn't find attribute list. Succeed " + "anyway.\n"); + return 0; + } + /* Deallocate clusters. */ + if (ctx->attr->non_resident) { + runlist *al_rl; - al_rl = ntfs_mapping_pairs_decompress(base_ni->vol, - ctx->attr, NULL); - if (!al_rl) { - ntfs_log_trace("Couldn't decompress attribute list " - "runlist. Succeed anyway.\n"); - return 0; - } - if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl)) { - ntfs_log_trace("Leaking clusters! Run chkdsk. " - "Couldn't free clusters from " - "attribute list runlist.\n"); - } - free(al_rl); - } - /* Remove attribute record itself. */ - if (ntfs_attr_record_rm(ctx)) { - /* - * FIXME: Should we succeed here? BTW, chkdsk doesn't - * complain if it find MFT record with attribute list, - * but without extents. - */ - ntfs_log_trace("Couldn't remove attribute list. Succeed " - "anyway.\n"); - return 0; - } - } - return 0; + al_rl = ntfs_mapping_pairs_decompress(base_ni->vol, + ctx->attr, NULL); + if (!al_rl) { + ntfs_log_trace("Couldn't decompress attribute list " + "runlist. Succeed anyway.\n"); + return 0; + } + if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl)) { + ntfs_log_trace("Leaking clusters! Run chkdsk. " + "Couldn't free clusters from " + "attribute list runlist.\n"); + } + free(al_rl); + } + /* Remove attribute record itself. */ + if (ntfs_attr_record_rm(ctx)) { + /* + * FIXME: Should we succeed here? BTW, chkdsk doesn't + * complain if it find MFT record with attribute list, + * but without extents. + */ + ntfs_log_trace("Couldn't remove attribute list. Succeed " + "anyway.\n"); + return 0; + } + } + return 0; } /** @@ -3561,191 +3596,192 @@ int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) { * On success return 0. On error return -1 with errno set to the error code. */ int ntfs_attr_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, u8 *val, s64 size) { - u32 attr_rec_size; - int err, i, offset; - BOOL is_resident; - BOOL can_be_non_resident = FALSE; - ntfs_inode *attr_ni; - ntfs_attr *na; - ATTR_FLAGS data_flags; + ntfschar *name, u8 name_len, u8 *val, s64 size) +{ + u32 attr_rec_size; + int err, i, offset; + BOOL is_resident; + BOOL can_be_non_resident = FALSE; + ntfs_inode *attr_ni; + ntfs_attr *na; + ATTR_FLAGS data_flags; - if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST) { - errno = EINVAL; - ntfs_log_perror("%s: ni=%p size=%lld", __FUNCTION__, ni, - (long long)size); - return -1; - } + if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST) { + errno = EINVAL; + ntfs_log_perror("%s: ni=%p size=%lld", __FUNCTION__, ni, + (long long)size); + return -1; + } - ntfs_log_trace("Entering for inode %lld, attr %x, size %lld.\n", - (long long)ni->mft_no, type, (long long)size); + ntfs_log_trace("Entering for inode %lld, attr %x, size %lld.\n", + (long long)ni->mft_no, type, (long long)size); - if (ni->nr_extents == -1) - ni = ni->base_ni; + if (ni->nr_extents == -1) + ni = ni->base_ni; - /* Check the attribute type and the size. */ - if (ntfs_attr_size_bounds_check(ni->vol, type, size)) { - if (errno == ENOENT) - errno = EIO; - return -1; - } + /* Check the attribute type and the size. */ + if (ntfs_attr_size_bounds_check(ni->vol, type, size)) { + if (errno == ENOENT) + errno = EIO; + return -1; + } - /* Sanity checks for always resident attributes. */ - if (ntfs_attr_can_be_non_resident(ni->vol, type, name, name_len)) { - if (errno != EPERM) { - err = errno; - ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); - goto err_out; - } - /* @val is mandatory. */ - if (!val) { - errno = EINVAL; - ntfs_log_perror("val is mandatory for always resident " - "attributes"); - return -1; - } - if (size > ni->vol->mft_record_size) { - errno = ERANGE; - ntfs_log_perror("Attribute is too big"); - return -1; - } - } else - can_be_non_resident = TRUE; + /* Sanity checks for always resident attributes. */ + if (ntfs_attr_can_be_non_resident(ni->vol, type, name, name_len)) { + if (errno != EPERM) { + err = errno; + ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); + goto err_out; + } + /* @val is mandatory. */ + if (!val) { + errno = EINVAL; + ntfs_log_perror("val is mandatory for always resident " + "attributes"); + return -1; + } + if (size > ni->vol->mft_record_size) { + errno = ERANGE; + ntfs_log_perror("Attribute is too big"); + return -1; + } + } else + can_be_non_resident = TRUE; - /* - * Determine resident or not will be new attribute. We add 8 to size in - * non resident case for mapping pairs. - */ - if (!ntfs_attr_can_be_resident(ni->vol, type)) { - is_resident = TRUE; - } else { - if (errno != EPERM) { - err = errno; - ntfs_log_perror("ntfs_attr_can_be_resident failed"); - goto err_out; - } - is_resident = FALSE; - } - /* Calculate attribute record size. */ - if (is_resident) - attr_rec_size = offsetof(ATTR_RECORD, resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + - ((size + 7) & ~7); - else - attr_rec_size = offsetof(ATTR_RECORD, non_resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + 8; + /* + * Determine resident or not will be new attribute. We add 8 to size in + * non resident case for mapping pairs. + */ + if (!ntfs_attr_can_be_resident(ni->vol, type)) { + is_resident = TRUE; + } else { + if (errno != EPERM) { + err = errno; + ntfs_log_perror("ntfs_attr_can_be_resident failed"); + goto err_out; + } + is_resident = FALSE; + } + /* Calculate attribute record size. */ + if (is_resident) + attr_rec_size = offsetof(ATTR_RECORD, resident_end) + + ((name_len * sizeof(ntfschar) + 7) & ~7) + + ((size + 7) & ~7); + else + attr_rec_size = offsetof(ATTR_RECORD, non_resident_end) + + ((name_len * sizeof(ntfschar) + 7) & ~7) + 8; - /* - * If we have enough free space for the new attribute in the base MFT - * record, then add attribute to it. - */ - if (le32_to_cpu(ni->mrec->bytes_allocated) - - le32_to_cpu(ni->mrec->bytes_in_use) >= attr_rec_size) { - attr_ni = ni; - goto add_attr_record; - } + /* + * If we have enough free space for the new attribute in the base MFT + * record, then add attribute to it. + */ + if (le32_to_cpu(ni->mrec->bytes_allocated) - + le32_to_cpu(ni->mrec->bytes_in_use) >= attr_rec_size) { + attr_ni = ni; + goto add_attr_record; + } - /* Try to add to extent inodes. */ - if (ntfs_inode_attach_all_extents(ni)) { - err = errno; - ntfs_log_perror("Failed to attach all extents to inode"); - goto err_out; - } - for (i = 0; i < ni->nr_extents; i++) { - attr_ni = ni->extent_nis[i]; - if (le32_to_cpu(attr_ni->mrec->bytes_allocated) - - le32_to_cpu(attr_ni->mrec->bytes_in_use) >= - attr_rec_size) - goto add_attr_record; - } + /* Try to add to extent inodes. */ + if (ntfs_inode_attach_all_extents(ni)) { + err = errno; + ntfs_log_perror("Failed to attach all extents to inode"); + goto err_out; + } + for (i = 0; i < ni->nr_extents; i++) { + attr_ni = ni->extent_nis[i]; + if (le32_to_cpu(attr_ni->mrec->bytes_allocated) - + le32_to_cpu(attr_ni->mrec->bytes_in_use) >= + attr_rec_size) + goto add_attr_record; + } - /* There is no extent that contain enough space for new attribute. */ - if (!NInoAttrList(ni)) { - /* Add attribute list not present, add it and retry. */ - if (ntfs_inode_add_attrlist(ni)) { - err = errno; - ntfs_log_perror("Failed to add attribute list"); - goto err_out; - } - return ntfs_attr_add(ni, type, name, name_len, val, size); - } - /* Allocate new extent. */ - attr_ni = ntfs_mft_record_alloc(ni->vol, ni); - if (!attr_ni) { - err = errno; - ntfs_log_perror("Failed to allocate extent record"); - goto err_out; - } + /* There is no extent that contain enough space for new attribute. */ + if (!NInoAttrList(ni)) { + /* Add attribute list not present, add it and retry. */ + if (ntfs_inode_add_attrlist(ni)) { + err = errno; + ntfs_log_perror("Failed to add attribute list"); + goto err_out; + } + return ntfs_attr_add(ni, type, name, name_len, val, size); + } + /* Allocate new extent. */ + attr_ni = ntfs_mft_record_alloc(ni->vol, ni); + if (!attr_ni) { + err = errno; + ntfs_log_perror("Failed to allocate extent record"); + goto err_out; + } add_attr_record: - if ((ni->flags & FILE_ATTR_COMPRESSED) - && ((type == AT_DATA) - || ((type == AT_INDEX_ROOT) && (name == NTFS_INDEX_I30)))) - data_flags = ATTR_IS_COMPRESSED; - else - data_flags = const_cpu_to_le16(0); - if (is_resident) { - /* Add resident attribute. */ - offset = ntfs_resident_attr_record_add(attr_ni, type, name, - name_len, val, size, data_flags); - if (offset < 0) { - if (errno == ENOSPC && can_be_non_resident) - goto add_non_resident; - err = errno; - ntfs_log_perror("Failed to add resident attribute"); - goto free_err_out; - } - return 0; - } + if ((ni->flags & FILE_ATTR_COMPRESSED) + && ((type == AT_DATA) + || ((type == AT_INDEX_ROOT) && (name == NTFS_INDEX_I30)))) + data_flags = ATTR_IS_COMPRESSED; + else + data_flags = const_cpu_to_le16(0); + if (is_resident) { + /* Add resident attribute. */ + offset = ntfs_resident_attr_record_add(attr_ni, type, name, + name_len, val, size, data_flags); + if (offset < 0) { + if (errno == ENOSPC && can_be_non_resident) + goto add_non_resident; + err = errno; + ntfs_log_perror("Failed to add resident attribute"); + goto free_err_out; + } + return 0; + } add_non_resident: - /* Add non resident attribute. */ - offset = ntfs_non_resident_attr_record_add(attr_ni, type, name, - name_len, 0, 8, data_flags); - if (offset < 0) { - err = errno; - ntfs_log_perror("Failed to add non resident attribute"); - goto free_err_out; - } + /* Add non resident attribute. */ + offset = ntfs_non_resident_attr_record_add(attr_ni, type, name, + name_len, 0, 8, data_flags); + if (offset < 0) { + err = errno; + ntfs_log_perror("Failed to add non resident attribute"); + goto free_err_out; + } - /* If @size == 0, we are done. */ - if (!size) - return 0; + /* If @size == 0, we are done. */ + if (!size) + return 0; - /* Open new attribute and resize it. */ - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - err = errno; - ntfs_log_perror("Failed to open just added attribute"); - goto rm_attr_err_out; - } - /* Resize and set attribute value. */ - if (ntfs_attr_truncate(na, size) || - (val && (ntfs_attr_pwrite(na, 0, size, val) != size))) { - err = errno; - ntfs_log_perror("Failed to initialize just added attribute"); - if (ntfs_attr_rm(na)) - ntfs_log_perror("Failed to remove just added attribute"); - ntfs_attr_close(na); - goto err_out; - } - ntfs_attr_close(na); - return 0; + /* Open new attribute and resize it. */ + na = ntfs_attr_open(ni, type, name, name_len); + if (!na) { + err = errno; + ntfs_log_perror("Failed to open just added attribute"); + goto rm_attr_err_out; + } + /* Resize and set attribute value. */ + if (ntfs_attr_truncate(na, size) || + (val && (ntfs_attr_pwrite(na, 0, size, val) != size))) { + err = errno; + ntfs_log_perror("Failed to initialize just added attribute"); + if (ntfs_attr_rm(na)) + ntfs_log_perror("Failed to remove just added attribute"); + ntfs_attr_close(na); + goto err_out; + } + ntfs_attr_close(na); + return 0; rm_attr_err_out: - /* Remove just added attribute. */ - if (ntfs_attr_record_resize(attr_ni->mrec, - (ATTR_RECORD*)((u8*)attr_ni->mrec + offset), 0)) - ntfs_log_perror("Failed to remove just added attribute #2"); + /* Remove just added attribute. */ + if (ntfs_attr_record_resize(attr_ni->mrec, + (ATTR_RECORD*)((u8*)attr_ni->mrec + offset), 0)) + ntfs_log_perror("Failed to remove just added attribute #2"); free_err_out: - /* Free MFT record, if it doesn't contain attributes. */ - if (le32_to_cpu(attr_ni->mrec->bytes_in_use) - - le16_to_cpu(attr_ni->mrec->attrs_offset) == 8) - if (ntfs_mft_record_free(attr_ni->vol, attr_ni)) - ntfs_log_perror("Failed to free MFT record"); + /* Free MFT record, if it doesn't contain attributes. */ + if (le32_to_cpu(attr_ni->mrec->bytes_in_use) - + le16_to_cpu(attr_ni->mrec->attrs_offset) == 8) + if (ntfs_mft_record_free(attr_ni->vol, attr_ni)) + ntfs_log_perror("Failed to free MFT record"); err_out: - errno = err; - return -1; + errno = err; + return -1; } /* @@ -3753,25 +3789,26 @@ err_out: */ int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask) { - ntfs_attr_search_ctx *ctx; - int res; + ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask) +{ + ntfs_attr_search_ctx *ctx; + int res; - res = -1; - /* Search for designated attribute */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (ctx) { - if (!ntfs_attr_lookup(type, name, name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - /* do the requested change (all small endian le16) */ - ctx->attr->flags = (ctx->attr->flags & ~mask) - | (flags & mask); - NInoSetDirty(ni); - res = 0; - } - ntfs_attr_put_search_ctx(ctx); - } - return (res); + res = -1; + /* Search for designated attribute */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (ctx) { + if (!ntfs_attr_lookup(type, name, name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + /* do the requested change (all small endian le16) */ + ctx->attr->flags = (ctx->attr->flags & ~mask) + | (flags & mask); + NInoSetDirty(ni); + res = 0; + } + ntfs_attr_put_search_ctx(ctx); + } + return (res); } @@ -3784,51 +3821,52 @@ int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_attr_rm(ntfs_attr *na) { - ntfs_attr_search_ctx *ctx; - int ret = 0; +int ntfs_attr_rm(ntfs_attr *na) +{ + ntfs_attr_search_ctx *ctx; + int ret = 0; - if (!na) { - ntfs_log_trace("Invalid arguments passed.\n"); - errno = EINVAL; - return -1; - } + if (!na) { + ntfs_log_trace("Invalid arguments passed.\n"); + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", - (long long) na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", + (long long) na->ni->mft_no, na->type); - /* Free cluster allocation. */ - if (NAttrNonResident(na)) { - if (ntfs_attr_map_whole_runlist(na)) - return -1; - if (ntfs_cluster_free(na->ni->vol, na, 0, -1) < 0) { - ntfs_log_trace("Failed to free cluster allocation. Leaving " - "inconstant metadata.\n"); - ret = -1; - } - } + /* Free cluster allocation. */ + if (NAttrNonResident(na)) { + if (ntfs_attr_map_whole_runlist(na)) + return -1; + if (ntfs_cluster_free(na->ni->vol, na, 0, -1) < 0) { + ntfs_log_trace("Failed to free cluster allocation. Leaving " + "inconstant metadata.\n"); + ret = -1; + } + } - /* Search for attribute extents and remove them all. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (ntfs_attr_record_rm(ctx)) { - ntfs_log_trace("Failed to remove attribute extent. Leaving " - "inconstant metadata.\n"); - ret = -1; - } - ntfs_attr_reinit_search_ctx(ctx); - } - ntfs_attr_put_search_ctx(ctx); - if (errno != ENOENT) { - ntfs_log_trace("Attribute lookup failed. Probably leaving inconstant " - "metadata.\n"); - ret = -1; - } + /* Search for attribute extents and remove them all. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; + while (!ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (ntfs_attr_record_rm(ctx)) { + ntfs_log_trace("Failed to remove attribute extent. Leaving " + "inconstant metadata.\n"); + ret = -1; + } + ntfs_attr_reinit_search_ctx(ctx); + } + ntfs_attr_put_search_ctx(ctx); + if (errno != ENOENT) { + ntfs_log_trace("Attribute lookup failed. Probably leaving inconstant " + "metadata.\n"); + ret = -1; + } - return ret; + return ret; } /** @@ -3848,53 +3886,54 @@ int ntfs_attr_rm(ntfs_attr *na) { * Warning: If you make a record smaller without having copied all the data you * are interested in the data may be overwritten! */ -int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) { - u32 old_size, alloc_size, attr_size; +int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) +{ + u32 old_size, alloc_size, attr_size; + + old_size = le32_to_cpu(m->bytes_in_use); + alloc_size = le32_to_cpu(m->bytes_allocated); + attr_size = le32_to_cpu(a->length); + + ntfs_log_trace("Sizes: old=%u alloc=%u attr=%u new=%u\n", + (unsigned)old_size, (unsigned)alloc_size, + (unsigned)attr_size, (unsigned)new_size); - old_size = le32_to_cpu(m->bytes_in_use); - alloc_size = le32_to_cpu(m->bytes_allocated); - attr_size = le32_to_cpu(a->length); + /* Align to 8 bytes, just in case the caller hasn't. */ + new_size = (new_size + 7) & ~7; + + /* If the actual attribute length has changed, move things around. */ + if (new_size != attr_size) { + + u32 new_muse = old_size - attr_size + new_size; + + /* Not enough space in this mft record. */ + if (new_muse > alloc_size) { + errno = ENOSPC; + ntfs_log_trace("Not enough space in the MFT record " + "(%u > %u)\n", new_muse, alloc_size); + return -1; + } - ntfs_log_trace("Sizes: old=%u alloc=%u attr=%u new=%u\n", - (unsigned)old_size, (unsigned)alloc_size, - (unsigned)attr_size, (unsigned)new_size); - - /* Align to 8 bytes, just in case the caller hasn't. */ - new_size = (new_size + 7) & ~7; - - /* If the actual attribute length has changed, move things around. */ - if (new_size != attr_size) { - - u32 new_muse = old_size - attr_size + new_size; - - /* Not enough space in this mft record. */ - if (new_muse > alloc_size) { - errno = ENOSPC; - ntfs_log_trace("Not enough space in the MFT record " - "(%u > %u)\n", new_muse, alloc_size); - return -1; - } - - if (a->type == AT_INDEX_ROOT && new_size > attr_size && - new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) { - errno = ENOSPC; - ntfs_log_trace("Too big INDEX_ROOT (%u > %u)\n", - new_muse, alloc_size); - return STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; - } - - /* Move attributes following @a to their new location. */ - memmove((u8 *)a + new_size, (u8 *)a + attr_size, - old_size - ((u8 *)a - (u8 *)m) - attr_size); - - /* Adjust @m to reflect the change in used space. */ - m->bytes_in_use = cpu_to_le32(new_muse); - - /* Adjust @a to reflect the new size. */ - if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length)) - a->length = cpu_to_le32(new_size); - } - return 0; + if (a->type == AT_INDEX_ROOT && new_size > attr_size && + new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) { + errno = ENOSPC; + ntfs_log_trace("Too big INDEX_ROOT (%u > %u)\n", + new_muse, alloc_size); + return STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; + } + + /* Move attributes following @a to their new location. */ + memmove((u8 *)a + new_size, (u8 *)a + attr_size, + old_size - ((u8 *)a - (u8 *)m) - attr_size); + + /* Adjust @m to reflect the change in used space. */ + m->bytes_in_use = cpu_to_le32(new_muse); + + /* Adjust @a to reflect the new size. */ + if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length)) + a->length = cpu_to_le32(new_size); + } + return 0; } /** @@ -3912,26 +3951,27 @@ int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) { * Note that on error no modifications have been performed whatsoever. */ int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, - const u32 new_size) { - int ret; + const u32 new_size) +{ + int ret; + + ntfs_log_trace("Entering for new size %u.\n", (unsigned)new_size); - ntfs_log_trace("Entering for new size %u.\n", (unsigned)new_size); - - /* Resize the resident part of the attribute record. */ - if ((ret = ntfs_attr_record_resize(m, a, (le16_to_cpu(a->value_offset) + - new_size + 7) & ~7)) < 0) - return ret; - /* - * If we made the attribute value bigger, clear the area between the - * old size and @new_size. - */ - if (new_size > le32_to_cpu(a->value_length)) - memset((u8*)a + le16_to_cpu(a->value_offset) + - le32_to_cpu(a->value_length), 0, new_size - - le32_to_cpu(a->value_length)); - /* Finally update the length of the attribute value. */ - a->value_length = cpu_to_le32(new_size); - return 0; + /* Resize the resident part of the attribute record. */ + if ((ret = ntfs_attr_record_resize(m, a, (le16_to_cpu(a->value_offset) + + new_size + 7) & ~7)) < 0) + return ret; + /* + * If we made the attribute value bigger, clear the area between the + * old size and @new_size. + */ + if (new_size > le32_to_cpu(a->value_length)) + memset((u8*)a + le16_to_cpu(a->value_offset) + + le32_to_cpu(a->value_length), 0, new_size - + le32_to_cpu(a->value_length)); + /* Finally update the length of the attribute value. */ + a->value_length = cpu_to_le32(new_size); + return 0; } /** @@ -3944,85 +3984,86 @@ int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni) { - ntfs_attr_search_ctx *nctx; - ATTR_RECORD *a; - int err; +int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni) +{ + ntfs_attr_search_ctx *nctx; + ATTR_RECORD *a; + int err; - if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) { - ntfs_log_trace("Invalid arguments passed.\n"); - errno = EINVAL; - return -1; - } + if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) { + ntfs_log_trace("Invalid arguments passed.\n"); + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no " - "0x%llx, ni->mft_no 0x%llx.\n", - (unsigned) le32_to_cpu(ctx->attr->type), - (long long) ctx->ntfs_ino->mft_no, - (long long) ni->mft_no); + ntfs_log_trace("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no " + "0x%llx, ni->mft_no 0x%llx.\n", + (unsigned) le32_to_cpu(ctx->attr->type), + (long long) ctx->ntfs_ino->mft_no, + (long long) ni->mft_no); - if (ctx->ntfs_ino == ni) - return 0; + if (ctx->ntfs_ino == ni) + return 0; - if (!ctx->al_entry) { - ntfs_log_trace("Inode should contain attribute list to use this " - "function.\n"); - errno = EINVAL; - return -1; - } + if (!ctx->al_entry) { + ntfs_log_trace("Inode should contain attribute list to use this " + "function.\n"); + errno = EINVAL; + return -1; + } - /* Find place in MFT record where attribute will be moved. */ - a = ctx->attr; - nctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!nctx) - return -1; + /* Find place in MFT record where attribute will be moved. */ + a = ctx->attr; + nctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!nctx) + return -1; - /* - * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for - * attribute in @ni->mrec, not any extent inode in case if @ni is base - * file record. - */ - if (!ntfs_attr_find(a->type, (ntfschar*)((u8*)a + le16_to_cpu( - a->name_offset)), a->name_length, CASE_SENSITIVE, NULL, - 0, nctx)) { - ntfs_log_trace("Attribute of such type, with same name already " - "present in this MFT record.\n"); - err = EEXIST; - goto put_err_out; - } - if (errno != ENOENT) { - err = errno; - ntfs_log_debug("Attribute lookup failed.\n"); - goto put_err_out; - } + /* + * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for + * attribute in @ni->mrec, not any extent inode in case if @ni is base + * file record. + */ + if (!ntfs_attr_find(a->type, (ntfschar*)((u8*)a + le16_to_cpu( + a->name_offset)), a->name_length, CASE_SENSITIVE, NULL, + 0, nctx)) { + ntfs_log_trace("Attribute of such type, with same name already " + "present in this MFT record.\n"); + err = EEXIST; + goto put_err_out; + } + if (errno != ENOENT) { + err = errno; + ntfs_log_debug("Attribute lookup failed.\n"); + goto put_err_out; + } - /* Make space and move attribute. */ - if (ntfs_make_room_for_attr(ni->mrec, (u8*) nctx->attr, - le32_to_cpu(a->length))) { - err = errno; - ntfs_log_trace("Couldn't make space for attribute.\n"); - goto put_err_out; - } - memcpy(nctx->attr, a, le32_to_cpu(a->length)); - nctx->attr->instance = nctx->mrec->next_attr_instance; - nctx->mrec->next_attr_instance = cpu_to_le16( - (le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff); - ntfs_attr_record_resize(ctx->mrec, a, 0); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_inode_mark_dirty(ni); + /* Make space and move attribute. */ + if (ntfs_make_room_for_attr(ni->mrec, (u8*) nctx->attr, + le32_to_cpu(a->length))) { + err = errno; + ntfs_log_trace("Couldn't make space for attribute.\n"); + goto put_err_out; + } + memcpy(nctx->attr, a, le32_to_cpu(a->length)); + nctx->attr->instance = nctx->mrec->next_attr_instance; + nctx->mrec->next_attr_instance = cpu_to_le16( + (le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff); + ntfs_attr_record_resize(ctx->mrec, a, 0); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_inode_mark_dirty(ni); - /* Update attribute list. */ - ctx->al_entry->mft_reference = - MK_LE_MREF(ni->mft_no, le16_to_cpu(ni->mrec->sequence_number)); - ctx->al_entry->instance = nctx->attr->instance; - ntfs_attrlist_mark_dirty(ni); + /* Update attribute list. */ + ctx->al_entry->mft_reference = + MK_LE_MREF(ni->mft_no, le16_to_cpu(ni->mrec->sequence_number)); + ctx->al_entry->instance = nctx->attr->instance; + ntfs_attrlist_mark_dirty(ni); - ntfs_attr_put_search_ctx(nctx); - return 0; + ntfs_attr_put_search_ctx(nctx); + return 0; put_err_out: - ntfs_attr_put_search_ctx(nctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(nctx); + errno = err; + return -1; } /** @@ -4038,76 +4079,77 @@ put_err_out: * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) { - ntfs_inode *base_ni, *ni; - MFT_RECORD *m; - int i; +int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) +{ + ntfs_inode *base_ni, *ni; + MFT_RECORD *m; + int i; - if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0) { - errno = EINVAL; - ntfs_log_perror("%s: ctx=%p ctx->attr=%p extra=%d", __FUNCTION__, - ctx, ctx ? ctx->attr : NULL, extra); - return -1; - } + if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0) { + errno = EINVAL; + ntfs_log_perror("%s: ctx=%p ctx->attr=%p extra=%d", __FUNCTION__, + ctx, ctx ? ctx->attr : NULL, extra); + return -1; + } - ntfs_log_trace("Entering for attr 0x%x, inode %llu\n", - (unsigned) le32_to_cpu(ctx->attr->type), - (unsigned long long)ctx->ntfs_ino->mft_no); + ntfs_log_trace("Entering for attr 0x%x, inode %llu\n", + (unsigned) le32_to_cpu(ctx->attr->type), + (unsigned long long)ctx->ntfs_ino->mft_no); - if (ctx->ntfs_ino->nr_extents == -1) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; + if (ctx->ntfs_ino->nr_extents == -1) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; - if (!NInoAttrList(base_ni)) { - errno = EINVAL; - ntfs_log_perror("Inode %llu has no attrlist", - (unsigned long long)base_ni->mft_no); - return -1; - } + if (!NInoAttrList(base_ni)) { + errno = EINVAL; + ntfs_log_perror("Inode %llu has no attrlist", + (unsigned long long)base_ni->mft_no); + return -1; + } - if (ntfs_inode_attach_all_extents(ctx->ntfs_ino)) { - ntfs_log_perror("Couldn't attach extents, inode=%llu", - (unsigned long long)base_ni->mft_no); - return -1; - } + if (ntfs_inode_attach_all_extents(ctx->ntfs_ino)) { + ntfs_log_perror("Couldn't attach extents, inode=%llu", + (unsigned long long)base_ni->mft_no); + return -1; + } - /* Walk through all extents and try to move attribute to them. */ - for (i = 0; i < base_ni->nr_extents; i++) { - ni = base_ni->extent_nis[i]; - m = ni->mrec; + /* Walk through all extents and try to move attribute to them. */ + for (i = 0; i < base_ni->nr_extents; i++) { + ni = base_ni->extent_nis[i]; + m = ni->mrec; - if (ctx->ntfs_ino->mft_no == ni->mft_no) - continue; + if (ctx->ntfs_ino->mft_no == ni->mft_no) + continue; - if (le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) < - le32_to_cpu(ctx->attr->length) + extra) - continue; + if (le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use) < + le32_to_cpu(ctx->attr->length) + extra) + continue; - /* - * ntfs_attr_record_move_to can fail if extent with other lowest - * VCN already present in inode we trying move record to. So, - * do not return error. - */ - if (!ntfs_attr_record_move_to(ctx, ni)) - return 0; - } + /* + * ntfs_attr_record_move_to can fail if extent with other lowest + * VCN already present in inode we trying move record to. So, + * do not return error. + */ + if (!ntfs_attr_record_move_to(ctx, ni)) + return 0; + } - /* - * Failed to move attribute to one of the current extents, so allocate - * new extent and move attribute to it. - */ - ni = ntfs_mft_record_alloc(base_ni->vol, base_ni); - if (!ni) { - ntfs_log_perror("Couldn't allocate MFT record"); - return -1; - } - if (ntfs_attr_record_move_to(ctx, ni)) { - ntfs_log_perror("Couldn't move attribute to MFT record"); - return -1; - } - return 0; + /* + * Failed to move attribute to one of the current extents, so allocate + * new extent and move attribute to it. + */ + ni = ntfs_mft_record_alloc(base_ni->vol, base_ni); + if (!ni) { + ntfs_log_perror("Couldn't allocate MFT record"); + return -1; + } + if (ntfs_attr_record_move_to(ctx, ni)) { + ntfs_log_perror("Couldn't move attribute to MFT record"); + return -1; + } + return 0; } /** @@ -4130,167 +4172,168 @@ int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) { * function and it is likely there will be further changes made. */ int ntfs_attr_make_non_resident(ntfs_attr *na, - ntfs_attr_search_ctx *ctx) { - s64 new_allocated_size, bw; - ntfs_volume *vol = na->ni->vol; - ATTR_REC *a = ctx->attr; - runlist *rl; - int mp_size, mp_ofs, name_ofs, arec_size, err; + ntfs_attr_search_ctx *ctx) +{ + s64 new_allocated_size, bw; + ntfs_volume *vol = na->ni->vol; + ATTR_REC *a = ctx->attr; + runlist *rl; + int mp_size, mp_ofs, name_ofs, arec_size, err; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long - long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long + long)na->ni->mft_no, na->type); - /* Some preliminary sanity checking. */ - if (NAttrNonResident(na)) { - ntfs_log_trace("Eeek! Trying to make non-resident attribute " - "non-resident. Aborting...\n"); - errno = EINVAL; - return -1; - } + /* Some preliminary sanity checking. */ + if (NAttrNonResident(na)) { + ntfs_log_trace("Eeek! Trying to make non-resident attribute " + "non-resident. Aborting...\n"); + errno = EINVAL; + return -1; + } - /* Check that the attribute is allowed to be non-resident. */ - if (ntfs_attr_can_be_non_resident(vol, na->type, na->name, na->name_len)) - return -1; + /* Check that the attribute is allowed to be non-resident. */ + if (ntfs_attr_can_be_non_resident(vol, na->type, na->name, na->name_len)) + return -1; - new_allocated_size = (le32_to_cpu(a->value_length) + vol->cluster_size - - 1) & ~(vol->cluster_size - 1); + new_allocated_size = (le32_to_cpu(a->value_length) + vol->cluster_size + - 1) & ~(vol->cluster_size - 1); - if (new_allocated_size > 0) { - /* Start by allocating clusters to hold the attribute value. */ - rl = ntfs_cluster_alloc(vol, 0, new_allocated_size >> - vol->cluster_size_bits, -1, DATA_ZONE); - if (!rl) - return -1; - } else - rl = NULL; - /* - * Setup the in-memory attribute structure to be non-resident so that - * we can use ntfs_attr_pwrite(). - */ - NAttrSetNonResident(na); - na->rl = rl; - na->allocated_size = new_allocated_size; - na->data_size = na->initialized_size = le32_to_cpu(a->value_length); - /* - * FIXME: For now just clear all of these as we don't support them when - * writing. - */ - NAttrClearSparse(na); - NAttrClearEncrypted(na); - if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { - /* set compression writing parameters */ - na->compression_block_size - = 1 << (STANDARD_COMPRESSION_UNIT + vol->cluster_size_bits); - na->compression_block_clusters = 1 << STANDARD_COMPRESSION_UNIT; - } + if (new_allocated_size > 0) { + /* Start by allocating clusters to hold the attribute value. */ + rl = ntfs_cluster_alloc(vol, 0, new_allocated_size >> + vol->cluster_size_bits, -1, DATA_ZONE); + if (!rl) + return -1; + } else + rl = NULL; + /* + * Setup the in-memory attribute structure to be non-resident so that + * we can use ntfs_attr_pwrite(). + */ + NAttrSetNonResident(na); + na->rl = rl; + na->allocated_size = new_allocated_size; + na->data_size = na->initialized_size = le32_to_cpu(a->value_length); + /* + * FIXME: For now just clear all of these as we don't support them when + * writing. + */ + NAttrClearSparse(na); + NAttrClearEncrypted(na); + if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { + /* set compression writing parameters */ + na->compression_block_size + = 1 << (STANDARD_COMPRESSION_UNIT + vol->cluster_size_bits); + na->compression_block_clusters = 1 << STANDARD_COMPRESSION_UNIT; + } - if (rl) { - /* Now copy the attribute value to the allocated cluster(s). */ - bw = ntfs_attr_pwrite(na, 0, le32_to_cpu(a->value_length), - (u8*)a + le16_to_cpu(a->value_offset)); - if (bw != le32_to_cpu(a->value_length)) { - err = errno; - ntfs_log_debug("Eeek! Failed to write out attribute value " - "(bw = %lli, errno = %i). " - "Aborting...\n", (long long)bw, err); - if (bw >= 0) - err = EIO; - goto cluster_free_err_out; - } - } - /* Determine the size of the mapping pairs array. */ - mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, INT_MAX); - if (mp_size < 0) { - err = errno; - ntfs_log_debug("Eeek! Failed to get size for mapping pairs array. " - "Aborting...\n"); - goto cluster_free_err_out; - } - /* Calculate new offsets for the name and the mapping pairs array. */ - if (na->ni->flags & FILE_ATTR_COMPRESSED) - name_ofs = (sizeof(ATTR_REC) + 7) & ~7; - else - name_ofs = (sizeof(ATTR_REC) - sizeof(a->compressed_size) + 7) & ~7; - mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; - /* - * Determine the size of the resident part of the non-resident - * attribute record. (Not compressed thus no compressed_size element - * present.) - */ - arec_size = (mp_ofs + mp_size + 7) & ~7; + if (rl) { + /* Now copy the attribute value to the allocated cluster(s). */ + bw = ntfs_attr_pwrite(na, 0, le32_to_cpu(a->value_length), + (u8*)a + le16_to_cpu(a->value_offset)); + if (bw != le32_to_cpu(a->value_length)) { + err = errno; + ntfs_log_debug("Eeek! Failed to write out attribute value " + "(bw = %lli, errno = %i). " + "Aborting...\n", (long long)bw, err); + if (bw >= 0) + err = EIO; + goto cluster_free_err_out; + } + } + /* Determine the size of the mapping pairs array. */ + mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, INT_MAX); + if (mp_size < 0) { + err = errno; + ntfs_log_debug("Eeek! Failed to get size for mapping pairs array. " + "Aborting...\n"); + goto cluster_free_err_out; + } + /* Calculate new offsets for the name and the mapping pairs array. */ + if (na->ni->flags & FILE_ATTR_COMPRESSED) + name_ofs = (sizeof(ATTR_REC) + 7) & ~7; + else + name_ofs = (sizeof(ATTR_REC) - sizeof(a->compressed_size) + 7) & ~7; + mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; + /* + * Determine the size of the resident part of the non-resident + * attribute record. (Not compressed thus no compressed_size element + * present.) + */ + arec_size = (mp_ofs + mp_size + 7) & ~7; - /* Resize the resident part of the attribute record. */ - if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { - err = errno; - goto cluster_free_err_out; - } + /* Resize the resident part of the attribute record. */ + if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { + err = errno; + goto cluster_free_err_out; + } - /* - * Convert the resident part of the attribute record to describe a - * non-resident attribute. - */ - a->non_resident = 1; + /* + * Convert the resident part of the attribute record to describe a + * non-resident attribute. + */ + a->non_resident = 1; - /* Move the attribute name if it exists and update the offset. */ - if (a->name_length) - memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - a->name_offset = cpu_to_le16(name_ofs); + /* Move the attribute name if it exists and update the offset. */ + if (a->name_length) + memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); + a->name_offset = cpu_to_le16(name_ofs); - /* Setup the fields specific to non-resident attributes. */ - a->lowest_vcn = cpu_to_sle64(0); - a->highest_vcn = cpu_to_sle64((new_allocated_size - 1) >> - vol->cluster_size_bits); + /* Setup the fields specific to non-resident attributes. */ + a->lowest_vcn = cpu_to_sle64(0); + a->highest_vcn = cpu_to_sle64((new_allocated_size - 1) >> + vol->cluster_size_bits); - a->mapping_pairs_offset = cpu_to_le16(mp_ofs); + a->mapping_pairs_offset = cpu_to_le16(mp_ofs); - /* - * Update the flags to match the in-memory ones. - * However cannot change the compression state if we had - * a fuse_file_info open with a mark for release. - * The decisions about compression can only be made when - * creating/recreating the stream, not when making non resident. - */ - a->flags &= ~(ATTR_IS_SPARSE | ATTR_IS_ENCRYPTED); - if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { - /* support only ATTR_IS_COMPRESSED compression mode */ - a->compression_unit = STANDARD_COMPRESSION_UNIT; - a->compressed_size = const_cpu_to_le64(0); - } else { - a->compression_unit = 0; - a->flags &= ~ATTR_COMPRESSION_MASK; - na->data_flags = a->flags; - } + /* + * Update the flags to match the in-memory ones. + * However cannot change the compression state if we had + * a fuse_file_info open with a mark for release. + * The decisions about compression can only be made when + * creating/recreating the stream, not when making non resident. + */ + a->flags &= ~(ATTR_IS_SPARSE | ATTR_IS_ENCRYPTED); + if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { + /* support only ATTR_IS_COMPRESSED compression mode */ + a->compression_unit = STANDARD_COMPRESSION_UNIT; + a->compressed_size = const_cpu_to_le64(0); + } else { + a->compression_unit = 0; + a->flags &= ~ATTR_COMPRESSION_MASK; + na->data_flags = a->flags; + } - memset(&a->reserved1, 0, sizeof(a->reserved1)); + memset(&a->reserved1, 0, sizeof(a->reserved1)); - a->allocated_size = cpu_to_sle64(new_allocated_size); - a->data_size = a->initialized_size = cpu_to_sle64(na->data_size); + a->allocated_size = cpu_to_sle64(new_allocated_size); + a->data_size = a->initialized_size = cpu_to_sle64(na->data_size); - /* Generate the mapping pairs array in the attribute record. */ - if (ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs, arec_size - mp_ofs, - rl, 0, NULL) < 0) { - // FIXME: Eeek! We need rollback! (AIA) - ntfs_log_trace("Eeek! Failed to build mapping pairs. Leaving " - "corrupt attribute record on disk. In memory " - "runlist is still intact! Error code is %i. " - "FIXME: Need to rollback instead!\n", errno); - return -1; - } + /* Generate the mapping pairs array in the attribute record. */ + if (ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs, arec_size - mp_ofs, + rl, 0, NULL) < 0) { + // FIXME: Eeek! We need rollback! (AIA) + ntfs_log_trace("Eeek! Failed to build mapping pairs. Leaving " + "corrupt attribute record on disk. In memory " + "runlist is still intact! Error code is %i. " + "FIXME: Need to rollback instead!\n", errno); + return -1; + } - /* Done! */ - return 0; + /* Done! */ + return 0; cluster_free_err_out: - if (rl && ntfs_cluster_free(vol, na, 0, -1) < 0) - ntfs_log_trace("Eeek! Failed to release allocated clusters in error " - "code path. Leaving inconsistent metadata...\n"); - NAttrClearNonResident(na); - na->allocated_size = na->data_size; - na->rl = NULL; - free(rl); - errno = err; - return -1; + if (rl && ntfs_cluster_free(vol, na, 0, -1) < 0) + ntfs_log_trace("Eeek! Failed to release allocated clusters in error " + "code path. Leaving inconsistent metadata...\n"); + NAttrClearNonResident(na); + na->allocated_size = na->data_size; + na->rl = NULL; + free(rl); + errno = err; + return -1; } @@ -4303,7 +4346,7 @@ static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize); * * Change the size of a resident, open ntfs attribute @na to @newsize bytes. * - * On success return 0 + * On success return 0 * On error return values are: * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT * STATUS_ERROR - otherwise @@ -4312,216 +4355,218 @@ static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize); * ERANGE - @newsize is not valid for the attribute type of @na. * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. */ -static int ntfs_resident_attr_resize_i(ntfs_attr *na, const s64 newsize) { - ntfs_attr_search_ctx *ctx; - ntfs_volume *vol; - ntfs_inode *ni; - int err, ret = STATUS_ERROR; +static int ntfs_resident_attr_resize_i(ntfs_attr *na, const s64 newsize) +{ + ntfs_attr_search_ctx *ctx; + ntfs_volume *vol; + ntfs_inode *ni; + int err, ret = STATUS_ERROR; - ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)newsize); + ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)newsize); - /* Get the attribute record that needs modification. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, 0, NULL, 0, - ctx)) { - err = errno; - ntfs_log_perror("ntfs_attr_lookup failed"); - goto put_err_out; - } - vol = na->ni->vol; - /* - * Check the attribute type and the corresponding minimum and maximum - * sizes against @newsize and fail if @newsize is out of bounds. - */ - if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { - err = errno; - if (err == ENOENT) - err = EIO; - ntfs_log_perror("%s: bounds check failed", __FUNCTION__); - goto put_err_out; - } - /* - * If @newsize is bigger than the mft record we need to make the - * attribute non-resident if the attribute type supports it. If it is - * smaller we can go ahead and attempt the resize. - */ - if (newsize < vol->mft_record_size) { - /* Perform the resize of the attribute record. */ - if (!(ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, - newsize))) { - /* Update attribute size everywhere. */ - na->data_size = na->initialized_size = newsize; - na->allocated_size = (newsize + 7) & ~7; - if ((na->data_flags & ATTR_COMPRESSION_MASK) - || NAttrSparse(na)) - na->compressed_size = na->allocated_size; - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - na->ni->allocated_size = na->allocated_size; - NInoFileNameSetDirty(na->ni); - } - goto resize_done; - } - /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */ - if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { - err = errno; - goto put_err_out; - } - } - /* There is not enough space in the mft record to perform the resize. */ + /* Get the attribute record that needs modification. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, 0, NULL, 0, + ctx)) { + err = errno; + ntfs_log_perror("ntfs_attr_lookup failed"); + goto put_err_out; + } + vol = na->ni->vol; + /* + * Check the attribute type and the corresponding minimum and maximum + * sizes against @newsize and fail if @newsize is out of bounds. + */ + if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { + err = errno; + if (err == ENOENT) + err = EIO; + ntfs_log_perror("%s: bounds check failed", __FUNCTION__); + goto put_err_out; + } + /* + * If @newsize is bigger than the mft record we need to make the + * attribute non-resident if the attribute type supports it. If it is + * smaller we can go ahead and attempt the resize. + */ + if (newsize < vol->mft_record_size) { + /* Perform the resize of the attribute record. */ + if (!(ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, + newsize))) { + /* Update attribute size everywhere. */ + na->data_size = na->initialized_size = newsize; + na->allocated_size = (newsize + 7) & ~7; + if ((na->data_flags & ATTR_COMPRESSION_MASK) + || NAttrSparse(na)) + na->compressed_size = na->allocated_size; + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + na->ni->data_size = na->data_size; + na->ni->allocated_size = na->allocated_size; + NInoFileNameSetDirty(na->ni); + } + goto resize_done; + } + /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */ + if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { + err = errno; + goto put_err_out; + } + } + /* There is not enough space in the mft record to perform the resize. */ - /* Make the attribute non-resident if possible. */ - if (!ntfs_attr_make_non_resident(na, ctx)) { - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - /* Resize non-resident attribute */ - return ntfs_attr_truncate(na, newsize); - } else if (errno != ENOSPC && errno != EPERM) { - err = errno; - ntfs_log_perror("Failed to make attribute non-resident"); - goto put_err_out; - } + /* Make the attribute non-resident if possible. */ + if (!ntfs_attr_make_non_resident(na, ctx)) { + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + /* Resize non-resident attribute */ + return ntfs_attr_truncate(na, newsize); + } else if (errno != ENOSPC && errno != EPERM) { + err = errno; + ntfs_log_perror("Failed to make attribute non-resident"); + goto put_err_out; + } - /* Try to make other attributes non-resident and retry each time. */ - ntfs_attr_init_search_ctx(ctx, NULL, na->ni->mrec); - while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) { - ntfs_attr *tna; - ATTR_RECORD *a; + /* Try to make other attributes non-resident and retry each time. */ + ntfs_attr_init_search_ctx(ctx, NULL, na->ni->mrec); + while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) { + ntfs_attr *tna; + ATTR_RECORD *a; - a = ctx->attr; - if (a->non_resident) - continue; + a = ctx->attr; + if (a->non_resident) + continue; - /* - * Check out whether convert is reasonable. Assume that mapping - * pairs will take 8 bytes. - */ - if (le32_to_cpu(a->length) <= offsetof(ATTR_RECORD, - compressed_size) + ((a->name_length * - sizeof(ntfschar) + 7) & ~7) + 8) - continue; + /* + * Check out whether convert is reasonable. Assume that mapping + * pairs will take 8 bytes. + */ + if (le32_to_cpu(a->length) <= offsetof(ATTR_RECORD, + compressed_size) + ((a->name_length * + sizeof(ntfschar) + 7) & ~7) + 8) + continue; - tna = ntfs_attr_open(na->ni, a->type, (ntfschar*)((u8*)a + - le16_to_cpu(a->name_offset)), a->name_length); - if (!tna) { - err = errno; - ntfs_log_perror("Couldn't open attribute"); - goto put_err_out; - } - if (ntfs_attr_make_non_resident(tna, ctx)) { - ntfs_attr_close(tna); - continue; - } - ntfs_inode_mark_dirty(tna->ni); - ntfs_attr_close(tna); - ntfs_attr_put_search_ctx(ctx); - return ntfs_resident_attr_resize(na, newsize); - } - /* Check whether error occurred. */ - if (errno != ENOENT) { - err = errno; - ntfs_log_perror("%s: Attribute lookup failed 1", __FUNCTION__); - goto put_err_out; - } + tna = ntfs_attr_open(na->ni, a->type, (ntfschar*)((u8*)a + + le16_to_cpu(a->name_offset)), a->name_length); + if (!tna) { + err = errno; + ntfs_log_perror("Couldn't open attribute"); + goto put_err_out; + } + if (ntfs_attr_make_non_resident(tna, ctx)) { + ntfs_attr_close(tna); + continue; + } + ntfs_inode_mark_dirty(tna->ni); + ntfs_attr_close(tna); + ntfs_attr_put_search_ctx(ctx); + return ntfs_resident_attr_resize(na, newsize); + } + /* Check whether error occurred. */ + if (errno != ENOENT) { + err = errno; + ntfs_log_perror("%s: Attribute lookup failed 1", __FUNCTION__); + goto put_err_out; + } + + /* + * The standard information and attribute list attributes can't be + * moved out from the base MFT record, so try to move out others. + */ + if (na->type==AT_STANDARD_INFORMATION || na->type==AT_ATTRIBUTE_LIST) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_free_space(na->ni, offsetof(ATTR_RECORD, + non_resident_end) + 8)) { + ntfs_log_perror("Could not free space in MFT record"); + return -1; + } + return ntfs_resident_attr_resize(na, newsize); + } - /* - * The standard information and attribute list attributes can't be - * moved out from the base MFT record, so try to move out others. - */ - if (na->type==AT_STANDARD_INFORMATION || na->type==AT_ATTRIBUTE_LIST) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_free_space(na->ni, offsetof(ATTR_RECORD, - non_resident_end) + 8)) { - ntfs_log_perror("Could not free space in MFT record"); - return -1; - } - return ntfs_resident_attr_resize(na, newsize); - } + /* + * Move the attribute to a new mft record, creating an attribute list + * attribute or modifying it if it is already present. + */ - /* - * Move the attribute to a new mft record, creating an attribute list - * attribute or modifying it if it is already present. - */ + /* Point search context back to attribute which we need resize. */ + ntfs_attr_init_search_ctx(ctx, na->ni, NULL); + if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + ntfs_log_perror("%s: Attribute lookup failed 2", __FUNCTION__); + err = errno; + goto put_err_out; + } - /* Point search context back to attribute which we need resize. */ - ntfs_attr_init_search_ctx(ctx, na->ni, NULL); - if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - ntfs_log_perror("%s: Attribute lookup failed 2", __FUNCTION__); - err = errno; - goto put_err_out; - } + /* + * Check whether attribute is already single in this MFT record. + * 8 added for the attribute terminator. + */ + if (le32_to_cpu(ctx->mrec->bytes_in_use) == + le16_to_cpu(ctx->mrec->attrs_offset) + + le32_to_cpu(ctx->attr->length) + 8) { + err = ENOSPC; + ntfs_log_trace("MFT record is filled with one attribute\n"); + ret = STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; + goto put_err_out; + } - /* - * Check whether attribute is already single in this MFT record. - * 8 added for the attribute terminator. - */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) == - le16_to_cpu(ctx->mrec->attrs_offset) + - le32_to_cpu(ctx->attr->length) + 8) { - err = ENOSPC; - ntfs_log_trace("MFT record is filled with one attribute\n"); - ret = STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; - goto put_err_out; - } + /* Add attribute list if not present. */ + if (na->ni->nr_extents == -1) + ni = na->ni->base_ni; + else + ni = na->ni; + if (!NInoAttrList(ni)) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_add_attrlist(ni)) + return -1; + return ntfs_resident_attr_resize(na, newsize); + } + /* Allocate new mft record. */ + ni = ntfs_mft_record_alloc(vol, ni); + if (!ni) { + err = errno; + ntfs_log_perror("Couldn't allocate new MFT record"); + goto put_err_out; + } + /* Move attribute to it. */ + if (ntfs_attr_record_move_to(ctx, ni)) { + err = errno; + ntfs_log_perror("Couldn't move attribute to new MFT record"); + goto put_err_out; + } + /* Update ntfs attribute. */ + if (na->ni->nr_extents == -1) + na->ni = ni; - /* Add attribute list if not present. */ - if (na->ni->nr_extents == -1) - ni = na->ni->base_ni; - else - ni = na->ni; - if (!NInoAttrList(ni)) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_add_attrlist(ni)) - return -1; - return ntfs_resident_attr_resize(na, newsize); - } - /* Allocate new mft record. */ - ni = ntfs_mft_record_alloc(vol, ni); - if (!ni) { - err = errno; - ntfs_log_perror("Couldn't allocate new MFT record"); - goto put_err_out; - } - /* Move attribute to it. */ - if (ntfs_attr_record_move_to(ctx, ni)) { - err = errno; - ntfs_log_perror("Couldn't move attribute to new MFT record"); - goto put_err_out; - } - /* Update ntfs attribute. */ - if (na->ni->nr_extents == -1) - na->ni = ni; - - ntfs_attr_put_search_ctx(ctx); - /* Try to perform resize once again. */ - return ntfs_resident_attr_resize(na, newsize); + ntfs_attr_put_search_ctx(ctx); + /* Try to perform resize once again. */ + return ntfs_resident_attr_resize(na, newsize); resize_done: - /* - * Set the inode (and its base inode if it exists) dirty so it is - * written out later. - */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - return 0; + /* + * Set the inode (and its base inode if it exists) dirty so it is + * written out later. + */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return ret; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return ret; } -static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_resident_attr_resize_i(na, newsize); - ntfs_log_leave("\n"); - return ret; +static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) +{ + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_resident_attr_resize_i(na, newsize); + ntfs_log_leave("\n"); + return ret; } /** @@ -4543,160 +4588,161 @@ static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) { * We expect the caller to do this as this is a fairly low level * function and it is likely there will be further changes made. */ -static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) { - ntfs_volume *vol = na->ni->vol; - ATTR_REC *a = ctx->attr; - int name_ofs, val_ofs, err = EIO; - s64 arec_size, bytes_read; +static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) +{ + ntfs_volume *vol = na->ni->vol; + ATTR_REC *a = ctx->attr; + int name_ofs, val_ofs, err = EIO; + s64 arec_size, bytes_read; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long - long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long + long)na->ni->mft_no, na->type); - /* Should be called for the first extent of the attribute. */ - if (sle64_to_cpu(a->lowest_vcn)) { - ntfs_log_trace("Eeek! Should be called for the first extent of the " - "attribute. Aborting...\n"); - err = EINVAL; - return -1; - } + /* Should be called for the first extent of the attribute. */ + if (sle64_to_cpu(a->lowest_vcn)) { + ntfs_log_trace("Eeek! Should be called for the first extent of the " + "attribute. Aborting...\n"); + err = EINVAL; + return -1; + } - /* Some preliminary sanity checking. */ - if (!NAttrNonResident(na)) { - ntfs_log_trace("Eeek! Trying to make resident attribute resident. " - "Aborting...\n"); - errno = EINVAL; - return -1; - } + /* Some preliminary sanity checking. */ + if (!NAttrNonResident(na)) { + ntfs_log_trace("Eeek! Trying to make resident attribute resident. " + "Aborting...\n"); + errno = EINVAL; + return -1; + } - /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */ - if (na->type == AT_BITMAP && na->ni->mft_no == FILE_MFT) { - errno = EPERM; - return -1; - } + /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */ + if (na->type == AT_BITMAP && na->ni->mft_no == FILE_MFT) { + errno = EPERM; + return -1; + } - /* Check that the attribute is allowed to be resident. */ - if (ntfs_attr_can_be_resident(vol, na->type)) - return -1; + /* Check that the attribute is allowed to be resident. */ + if (ntfs_attr_can_be_resident(vol, na->type)) + return -1; - if (na->data_flags & ATTR_IS_ENCRYPTED) { - ntfs_log_trace("Making encrypted streams resident is not " - "implemented yet.\n"); - errno = EOPNOTSUPP; - return -1; - } + if (na->data_flags & ATTR_IS_ENCRYPTED) { + ntfs_log_trace("Making encrypted streams resident is not " + "implemented yet.\n"); + errno = EOPNOTSUPP; + return -1; + } - /* Work out offsets into and size of the resident attribute. */ - name_ofs = 24; /* = sizeof(resident_ATTR_REC); */ - val_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; - arec_size = (val_ofs + na->data_size + 7) & ~7; + /* Work out offsets into and size of the resident attribute. */ + name_ofs = 24; /* = sizeof(resident_ATTR_REC); */ + val_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; + arec_size = (val_ofs + na->data_size + 7) & ~7; - /* Sanity check the size before we start modifying the attribute. */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) + - arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) { - errno = ENOSPC; - ntfs_log_trace("Not enough space to make attribute resident\n"); - return -1; - } + /* Sanity check the size before we start modifying the attribute. */ + if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) + + arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) { + errno = ENOSPC; + ntfs_log_trace("Not enough space to make attribute resident\n"); + return -1; + } - /* Read and cache the whole runlist if not already done. */ - if (ntfs_attr_map_whole_runlist(na)) - return -1; + /* Read and cache the whole runlist if not already done. */ + if (ntfs_attr_map_whole_runlist(na)) + return -1; - /* Move the attribute name if it exists and update the offset. */ - if (a->name_length) { - memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - } - a->name_offset = cpu_to_le16(name_ofs); + /* Move the attribute name if it exists and update the offset. */ + if (a->name_length) { + memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); + } + a->name_offset = cpu_to_le16(name_ofs); - /* Resize the resident part of the attribute record. */ - if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { - /* - * Bug, because ntfs_attr_record_resize should not fail (we - * already checked that attribute fits MFT record). - */ - ntfs_log_error("BUG! Failed to resize attribute record. " - "Please report to the %s. Aborting...\n", - NTFS_DEV_LIST); - errno = EIO; - return -1; - } + /* Resize the resident part of the attribute record. */ + if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { + /* + * Bug, because ntfs_attr_record_resize should not fail (we + * already checked that attribute fits MFT record). + */ + ntfs_log_error("BUG! Failed to resize attribute record. " + "Please report to the %s. Aborting...\n", + NTFS_DEV_LIST); + errno = EIO; + return -1; + } - /* Convert the attribute record to describe a resident attribute. */ - a->non_resident = 0; - a->flags = 0; - a->value_length = cpu_to_le32(na->data_size); - a->value_offset = cpu_to_le16(val_ofs); - /* - * If a data stream was wiped out, adjust the compression mode - * to current state of compression flag - */ - if (!na->data_size - && (na->type == AT_DATA) - && (na->ni->flags & FILE_ATTR_COMPRESSED)) { - a->flags |= ATTR_IS_COMPRESSED; - na->data_flags = a->flags; - } - /* - * File names cannot be non-resident so we would never see this here - * but at least it serves as a reminder that there may be attributes - * for which we do need to set this flag. (AIA) - */ - if (a->type == AT_FILE_NAME) - a->resident_flags = RESIDENT_ATTR_IS_INDEXED; - else - a->resident_flags = 0; - a->reservedR = 0; + /* Convert the attribute record to describe a resident attribute. */ + a->non_resident = 0; + a->flags = 0; + a->value_length = cpu_to_le32(na->data_size); + a->value_offset = cpu_to_le16(val_ofs); + /* + * If a data stream was wiped out, adjust the compression mode + * to current state of compression flag + */ + if (!na->data_size + && (na->type == AT_DATA) + && (na->ni->flags & FILE_ATTR_COMPRESSED)) { + a->flags |= ATTR_IS_COMPRESSED; + na->data_flags = a->flags; + } + /* + * File names cannot be non-resident so we would never see this here + * but at least it serves as a reminder that there may be attributes + * for which we do need to set this flag. (AIA) + */ + if (a->type == AT_FILE_NAME) + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + else + a->resident_flags = 0; + a->reservedR = 0; - /* Sanity fixup... Shouldn't really happen. (AIA) */ - if (na->initialized_size > na->data_size) - na->initialized_size = na->data_size; + /* Sanity fixup... Shouldn't really happen. (AIA) */ + if (na->initialized_size > na->data_size) + na->initialized_size = na->data_size; - /* Copy data from run list to resident attribute value. */ - bytes_read = ntfs_rl_pread(vol, na->rl, 0, na->initialized_size, - (u8*)a + val_ofs); - if (bytes_read != na->initialized_size) { - if (bytes_read < 0) - err = errno; - ntfs_log_trace("Eeek! Failed to read attribute data. Leaving " - "inconstant metadata. Run chkdsk. " - "Aborting...\n"); - errno = err; - return -1; - } + /* Copy data from run list to resident attribute value. */ + bytes_read = ntfs_rl_pread(vol, na->rl, 0, na->initialized_size, + (u8*)a + val_ofs); + if (bytes_read != na->initialized_size) { + if (bytes_read < 0) + err = errno; + ntfs_log_trace("Eeek! Failed to read attribute data. Leaving " + "inconstant metadata. Run chkdsk. " + "Aborting...\n"); + errno = err; + return -1; + } - /* Clear memory in gap between initialized_size and data_size. */ - if (na->initialized_size < na->data_size) - memset((u8*)a + val_ofs + na->initialized_size, 0, - na->data_size - na->initialized_size); + /* Clear memory in gap between initialized_size and data_size. */ + if (na->initialized_size < na->data_size) + memset((u8*)a + val_ofs + na->initialized_size, 0, + na->data_size - na->initialized_size); - /* - * Deallocate clusters from the runlist. - * - * NOTE: We can use ntfs_cluster_free() because we have already mapped - * the whole run list and thus it doesn't matter that the attribute - * record is in a transiently corrupted state at this moment in time. - */ - if (ntfs_cluster_free(vol, na, 0, -1) < 0) { - err = errno; - ntfs_log_perror("Eeek! Failed to release allocated clusters"); - ntfs_log_trace("Ignoring error and leaving behind wasted " - "clusters.\n"); - } + /* + * Deallocate clusters from the runlist. + * + * NOTE: We can use ntfs_cluster_free() because we have already mapped + * the whole run list and thus it doesn't matter that the attribute + * record is in a transiently corrupted state at this moment in time. + */ + if (ntfs_cluster_free(vol, na, 0, -1) < 0) { + err = errno; + ntfs_log_perror("Eeek! Failed to release allocated clusters"); + ntfs_log_trace("Ignoring error and leaving behind wasted " + "clusters.\n"); + } - /* Throw away the now unused runlist. */ - free(na->rl); - na->rl = NULL; + /* Throw away the now unused runlist. */ + free(na->rl); + na->rl = NULL; - /* Update in-memory struct ntfs_attr. */ - NAttrClearNonResident(na); - NAttrClearSparse(na); - NAttrClearEncrypted(na); - na->initialized_size = na->data_size; - na->allocated_size = na->compressed_size = (na->data_size + 7) & ~7; - na->compression_block_size = 0; - na->compression_block_size_bits = na->compression_block_clusters = 0; - return 0; + /* Update in-memory struct ntfs_attr. */ + NAttrClearNonResident(na); + NAttrClearSparse(na); + NAttrClearEncrypted(na); + na->initialized_size = na->data_size; + na->allocated_size = na->compressed_size = (na->data_size + 7) & ~7; + na->compression_block_size = 0; + na->compression_block_size_bits = na->compression_block_clusters = 0; + return 0; } /* @@ -4704,424 +4750,417 @@ static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) { * update allocated and compressed size. */ static int ntfs_attr_update_meta(ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, - ntfs_attr_search_ctx *ctx) { - int sparse, ret = 0; + ntfs_attr_search_ctx *ctx) +{ + int sparse, ret = 0; + + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x\n", + (unsigned long long)na->ni->mft_no, na->type); + + if (a->lowest_vcn) + goto out; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x\n", - (unsigned long long)na->ni->mft_no, na->type); + a->allocated_size = cpu_to_sle64(na->allocated_size); - if (a->lowest_vcn) - goto out; + /* Update sparse bit. */ + sparse = ntfs_rl_sparse(na->rl); + if (sparse == -1) { + errno = EIO; + goto error; + } - a->allocated_size = cpu_to_sle64(na->allocated_size); + /* Attribute become sparse. */ + if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) { + /* + * Move attribute to another mft record, if attribute is too + * small to add compressed_size field to it and we have no + * free space in the current mft record. + */ + if ((le32_to_cpu(a->length) - + le16_to_cpu(a->mapping_pairs_offset) == 8) + && !(le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use))) { - /* Update sparse bit. */ - sparse = ntfs_rl_sparse(na->rl); - if (sparse == -1) { - errno = EIO; - goto error; - } - - /* Attribute become sparse. */ - if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) { - /* - * Move attribute to another mft record, if attribute is too - * small to add compressed_size field to it and we have no - * free space in the current mft record. - */ - if ((le32_to_cpu(a->length) - - le16_to_cpu(a->mapping_pairs_offset) == 8) - && !(le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use))) { - - if (!NInoAttrList(na->ni)) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_add_attrlist(na->ni)) - goto leave; - goto retry; - } - if (ntfs_attr_record_move_away(ctx, 8)) { - ntfs_log_perror("Failed to move attribute"); - goto error; - } - ntfs_attr_put_search_ctx(ctx); - goto retry; - } - if (!(le32_to_cpu(a->length) - le16_to_cpu( - a->mapping_pairs_offset))) { - errno = EIO; - ntfs_log_perror("Mapping pairs space is 0"); - goto error; - } - - NAttrSetSparse(na); - a->flags |= ATTR_IS_SPARSE; - a->compression_unit = STANDARD_COMPRESSION_UNIT; /* Windows + if (!NInoAttrList(na->ni)) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_add_attrlist(na->ni)) + goto leave; + goto retry; + } + if (ntfs_attr_record_move_away(ctx, 8)) { + ntfs_log_perror("Failed to move attribute"); + goto error; + } + ntfs_attr_put_search_ctx(ctx); + goto retry; + } + if (!(le32_to_cpu(a->length) - le16_to_cpu( + a->mapping_pairs_offset))) { + errno = EIO; + ntfs_log_perror("Mapping pairs space is 0"); + goto error; + } + + NAttrSetSparse(na); + a->flags |= ATTR_IS_SPARSE; + a->compression_unit = STANDARD_COMPRESSION_UNIT; /* Windows set it so, even if attribute is not actually compressed. */ + + memmove((u8*)a + le16_to_cpu(a->name_offset) + 8, + (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); - memmove((u8*)a + le16_to_cpu(a->name_offset) + 8, - (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); + a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8); + + a->mapping_pairs_offset = + cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) + 8); + } - a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8); + /* Attribute no longer sparse. */ + if (!sparse && (a->flags & ATTR_IS_SPARSE) && + !(a->flags & ATTR_IS_COMPRESSED)) { + + NAttrClearSparse(na); + a->flags &= ~ATTR_IS_SPARSE; + a->compression_unit = 0; + + memmove((u8*)a + le16_to_cpu(a->name_offset) - 8, + (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); + + if (le16_to_cpu(a->name_offset) >= 8) + a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8); - a->mapping_pairs_offset = - cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) + 8); - } + a->mapping_pairs_offset = + cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) - 8); + } - /* Attribute no longer sparse. */ - if (!sparse && (a->flags & ATTR_IS_SPARSE) && - !(a->flags & ATTR_IS_COMPRESSED)) { + /* Update compressed size if required. */ + if (sparse || (na->data_flags & ATTR_COMPRESSION_MASK)) { + s64 new_compr_size; - NAttrClearSparse(na); - a->flags &= ~ATTR_IS_SPARSE; - a->compression_unit = 0; - - memmove((u8*)a + le16_to_cpu(a->name_offset) - 8, - (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - - if (le16_to_cpu(a->name_offset) >= 8) - a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8); - - a->mapping_pairs_offset = - cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) - 8); - } - - /* Update compressed size if required. */ - if (sparse || (na->data_flags & ATTR_COMPRESSION_MASK)) { - s64 new_compr_size; - - new_compr_size = ntfs_rl_get_compressed_size(na->ni->vol, na->rl); - if (new_compr_size == -1) - goto error; - - na->compressed_size = new_compr_size; - a->compressed_size = cpu_to_sle64(new_compr_size); - } - /* - * Set FILE_NAME dirty flag, to update sparse bit and - * allocated size in the index. - */ - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - if (sparse) - na->ni->allocated_size = na->compressed_size; - else - na->ni->allocated_size = na->allocated_size; - NInoFileNameSetDirty(na->ni); - } + new_compr_size = ntfs_rl_get_compressed_size(na->ni->vol, na->rl); + if (new_compr_size == -1) + goto error; + + na->compressed_size = new_compr_size; + a->compressed_size = cpu_to_sle64(new_compr_size); + } + /* + * Set FILE_NAME dirty flag, to update sparse bit and + * allocated size in the index. + */ + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + if (sparse) + na->ni->allocated_size = na->compressed_size; + else + na->ni->allocated_size = na->allocated_size; + NInoFileNameSetDirty(na->ni); + } out: - return ret; -leave: - ret = -1; - goto out; /* return -1 */ -retry: - ret = -2; - goto out; -error: - ret = -3; - goto out; + return ret; +leave: ret = -1; goto out; /* return -1 */ +retry: ret = -2; goto out; +error: ret = -3; goto out; } #define NTFS_VCN_DELETE_MARK -2 /** * ntfs_attr_update_mapping_pairs_i - see ntfs_attr_update_mapping_pairs */ -static int ntfs_attr_update_mapping_pairs_i(ntfs_attr *na, VCN from_vcn) { - ntfs_attr_search_ctx *ctx; - ntfs_inode *ni, *base_ni; - MFT_RECORD *m; - ATTR_RECORD *a; - VCN stop_vcn; - const runlist_element *stop_rl; - int err, mp_size, cur_max_mp_size, exp_max_mp_size, ret = -1; - BOOL finished_build; +static int ntfs_attr_update_mapping_pairs_i(ntfs_attr *na, VCN from_vcn) +{ + ntfs_attr_search_ctx *ctx; + ntfs_inode *ni, *base_ni; + MFT_RECORD *m; + ATTR_RECORD *a; + VCN stop_vcn; + const runlist_element *stop_rl; + int err, mp_size, cur_max_mp_size, exp_max_mp_size, ret = -1; + BOOL finished_build; retry: - if (!na || !na->rl || from_vcn) { - errno = EINVAL; - ntfs_log_perror("%s: na=%p", __FUNCTION__, na); - return -1; - } + if (!na || !na->rl || from_vcn) { + errno = EINVAL; + ntfs_log_perror("%s: na=%p", __FUNCTION__, na); + return -1; + } - ntfs_log_trace("Entering for inode %llu, attr 0x%x\n", - (unsigned long long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode %llu, attr 0x%x\n", + (unsigned long long)na->ni->mft_no, na->type); - if (!NAttrNonResident(na)) { - errno = EINVAL; - ntfs_log_perror("%s: resident attribute", __FUNCTION__); - return -1; - } + if (!NAttrNonResident(na)) { + errno = EINVAL; + ntfs_log_perror("%s: resident attribute", __FUNCTION__); + return -1; + } - if (na->ni->nr_extents == -1) - base_ni = na->ni->base_ni; - else - base_ni = na->ni; + if (na->ni->nr_extents == -1) + base_ni = na->ni->base_ni; + else + base_ni = na->ni; - ctx = ntfs_attr_get_search_ctx(base_ni, NULL); - if (!ctx) - return -1; + ctx = ntfs_attr_get_search_ctx(base_ni, NULL); + if (!ctx) + return -1; - /* Fill attribute records with new mapping pairs. */ - stop_vcn = 0; - stop_rl = na->rl; - finished_build = FALSE; - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, from_vcn, NULL, 0, ctx)) { - a = ctx->attr; - m = ctx->mrec; - /* - * If runlist is updating not from the beginning, then set - * @stop_vcn properly, i.e. to the lowest vcn of record that - * contain @from_vcn. Also we do not need @from_vcn anymore, - * set it to 0 to make ntfs_attr_lookup enumerate attributes. - */ - if (from_vcn) { - LCN first_lcn; + /* Fill attribute records with new mapping pairs. */ + stop_vcn = 0; + stop_rl = na->rl; + finished_build = FALSE; + while (!ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, from_vcn, NULL, 0, ctx)) { + a = ctx->attr; + m = ctx->mrec; + /* + * If runlist is updating not from the beginning, then set + * @stop_vcn properly, i.e. to the lowest vcn of record that + * contain @from_vcn. Also we do not need @from_vcn anymore, + * set it to 0 to make ntfs_attr_lookup enumerate attributes. + */ + if (from_vcn) { + LCN first_lcn; - stop_vcn = sle64_to_cpu(a->lowest_vcn); - from_vcn = 0; - /* - * Check whether the first run we need to update is - * the last run in runlist, if so, then deallocate - * all attrubute extents starting this one. - */ - first_lcn = ntfs_rl_vcn_to_lcn(na->rl, stop_vcn); - if (first_lcn == LCN_EINVAL) { - errno = EIO; - ntfs_log_perror("Bad runlist"); - goto put_err_out; - } - if (first_lcn == LCN_ENOENT || - first_lcn == LCN_RL_NOT_MAPPED) - finished_build = TRUE; - } + stop_vcn = sle64_to_cpu(a->lowest_vcn); + from_vcn = 0; + /* + * Check whether the first run we need to update is + * the last run in runlist, if so, then deallocate + * all attrubute extents starting this one. + */ + first_lcn = ntfs_rl_vcn_to_lcn(na->rl, stop_vcn); + if (first_lcn == LCN_EINVAL) { + errno = EIO; + ntfs_log_perror("Bad runlist"); + goto put_err_out; + } + if (first_lcn == LCN_ENOENT || + first_lcn == LCN_RL_NOT_MAPPED) + finished_build = TRUE; + } - /* - * Check whether we finished mapping pairs build, if so mark - * extent as need to delete (by setting highest vcn to - * NTFS_VCN_DELETE_MARK (-2), we shall check it later and - * delete extent) and continue search. - */ - if (finished_build) { - ntfs_log_trace("Mark attr 0x%x for delete in inode " - "%lld.\n", (unsigned)le32_to_cpu(a->type), - (long long)ctx->ntfs_ino->mft_no); - a->highest_vcn = cpu_to_sle64(NTFS_VCN_DELETE_MARK); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - continue; - } + /* + * Check whether we finished mapping pairs build, if so mark + * extent as need to delete (by setting highest vcn to + * NTFS_VCN_DELETE_MARK (-2), we shall check it later and + * delete extent) and continue search. + */ + if (finished_build) { + ntfs_log_trace("Mark attr 0x%x for delete in inode " + "%lld.\n", (unsigned)le32_to_cpu(a->type), + (long long)ctx->ntfs_ino->mft_no); + a->highest_vcn = cpu_to_sle64(NTFS_VCN_DELETE_MARK); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + continue; + } - switch (ntfs_attr_update_meta(a, na, m, ctx)) { - case -1: - return -1; - case -2: - goto retry; - case -3: - goto put_err_out; - } + switch (ntfs_attr_update_meta(a, na, m, ctx)) { + case -1: return -1; + case -2: goto retry; + case -3: goto put_err_out; + } - /* - * Determine maximum possible length of mapping pairs, - * if we shall *not* expand space for mapping pairs. - */ - cur_max_mp_size = le32_to_cpu(a->length) - - le16_to_cpu(a->mapping_pairs_offset); - /* - * Determine maximum possible length of mapping pairs in the - * current mft record, if we shall expand space for mapping - * pairs. - */ - exp_max_mp_size = le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) + cur_max_mp_size; - /* Get the size for the rest of mapping pairs array. */ - mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, stop_rl, - stop_vcn, exp_max_mp_size); - if (mp_size <= 0) { - ntfs_log_perror("%s: get MP size failed", __FUNCTION__); - goto put_err_out; - } - /* Test mapping pairs for fitting in the current mft record. */ - if (mp_size > exp_max_mp_size) { - /* - * Mapping pairs of $ATTRIBUTE_LIST attribute must fit - * in the base mft record. Try to move out other - * attributes and try again. - */ - if (na->type == AT_ATTRIBUTE_LIST) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_free_space(na->ni, mp_size - - cur_max_mp_size)) { - ntfs_log_perror("Attribute list is too " - "big. Defragment the " - "volume\n"); - return -1; - } - goto retry; - } + /* + * Determine maximum possible length of mapping pairs, + * if we shall *not* expand space for mapping pairs. + */ + cur_max_mp_size = le32_to_cpu(a->length) - + le16_to_cpu(a->mapping_pairs_offset); + /* + * Determine maximum possible length of mapping pairs in the + * current mft record, if we shall expand space for mapping + * pairs. + */ + exp_max_mp_size = le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use) + cur_max_mp_size; + /* Get the size for the rest of mapping pairs array. */ + mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, stop_rl, + stop_vcn, exp_max_mp_size); + if (mp_size <= 0) { + ntfs_log_perror("%s: get MP size failed", __FUNCTION__); + goto put_err_out; + } + /* Test mapping pairs for fitting in the current mft record. */ + if (mp_size > exp_max_mp_size) { + /* + * Mapping pairs of $ATTRIBUTE_LIST attribute must fit + * in the base mft record. Try to move out other + * attributes and try again. + */ + if (na->type == AT_ATTRIBUTE_LIST) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_free_space(na->ni, mp_size - + cur_max_mp_size)) { + ntfs_log_perror("Attribute list is too " + "big. Defragment the " + "volume\n"); + return -1; + } + goto retry; + } - /* Add attribute list if it isn't present, and retry. */ - if (!NInoAttrList(base_ni)) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_add_attrlist(base_ni)) { - ntfs_log_perror("Can not add attrlist"); - return -1; - } - goto retry; - } + /* Add attribute list if it isn't present, and retry. */ + if (!NInoAttrList(base_ni)) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_add_attrlist(base_ni)) { + ntfs_log_perror("Can not add attrlist"); + return -1; + } + goto retry; + } - /* - * Set mapping pairs size to maximum possible for this - * mft record. We shall write the rest of mapping pairs - * to another MFT records. - */ - mp_size = exp_max_mp_size; - } + /* + * Set mapping pairs size to maximum possible for this + * mft record. We shall write the rest of mapping pairs + * to another MFT records. + */ + mp_size = exp_max_mp_size; + } - /* Change space for mapping pairs if we need it. */ - if (((mp_size + 7) & ~7) != cur_max_mp_size) { - if (ntfs_attr_record_resize(m, a, - le16_to_cpu(a->mapping_pairs_offset) + - mp_size)) { - errno = EIO; - ntfs_log_perror("Failed to resize attribute"); - goto put_err_out; - } - } + /* Change space for mapping pairs if we need it. */ + if (((mp_size + 7) & ~7) != cur_max_mp_size) { + if (ntfs_attr_record_resize(m, a, + le16_to_cpu(a->mapping_pairs_offset) + + mp_size)) { + errno = EIO; + ntfs_log_perror("Failed to resize attribute"); + goto put_err_out; + } + } - /* Update lowest vcn. */ - a->lowest_vcn = cpu_to_sle64(stop_vcn); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - if ((ctx->ntfs_ino->nr_extents == -1 || - NInoAttrList(ctx->ntfs_ino)) && - ctx->attr->type != AT_ATTRIBUTE_LIST) { - ctx->al_entry->lowest_vcn = cpu_to_sle64(stop_vcn); - ntfs_attrlist_mark_dirty(ctx->ntfs_ino); - } + /* Update lowest vcn. */ + a->lowest_vcn = cpu_to_sle64(stop_vcn); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + if ((ctx->ntfs_ino->nr_extents == -1 || + NInoAttrList(ctx->ntfs_ino)) && + ctx->attr->type != AT_ATTRIBUTE_LIST) { + ctx->al_entry->lowest_vcn = cpu_to_sle64(stop_vcn); + ntfs_attrlist_mark_dirty(ctx->ntfs_ino); + } - /* - * Generate the new mapping pairs array directly into the - * correct destination, i.e. the attribute record itself. - */ - if (!ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + le16_to_cpu( - a->mapping_pairs_offset), mp_size, na->rl, - stop_vcn, &stop_rl)) - finished_build = TRUE; - if (stop_rl) - stop_vcn = stop_rl->vcn; - else - stop_vcn = 0; - if (!finished_build && errno != ENOSPC) { - ntfs_log_perror("Failed to build mapping pairs"); - goto put_err_out; - } - a->highest_vcn = cpu_to_sle64(stop_vcn - 1); - } - /* Check whether error occurred. */ - if (errno != ENOENT) { - ntfs_log_perror("%s: Attribute lookup failed", __FUNCTION__); - goto put_err_out; - } + /* + * Generate the new mapping pairs array directly into the + * correct destination, i.e. the attribute record itself. + */ + if (!ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + le16_to_cpu( + a->mapping_pairs_offset), mp_size, na->rl, + stop_vcn, &stop_rl)) + finished_build = TRUE; + if (stop_rl) + stop_vcn = stop_rl->vcn; + else + stop_vcn = 0; + if (!finished_build && errno != ENOSPC) { + ntfs_log_perror("Failed to build mapping pairs"); + goto put_err_out; + } + a->highest_vcn = cpu_to_sle64(stop_vcn - 1); + } + /* Check whether error occurred. */ + if (errno != ENOENT) { + ntfs_log_perror("%s: Attribute lookup failed", __FUNCTION__); + goto put_err_out; + } - /* Deallocate not used attribute extents and return with success. */ - if (finished_build) { - ntfs_attr_reinit_search_ctx(ctx); - ntfs_log_trace("Deallocate marked extents.\n"); - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (sle64_to_cpu(ctx->attr->highest_vcn) != - NTFS_VCN_DELETE_MARK) - continue; - /* Remove unused attribute record. */ - if (ntfs_attr_record_rm(ctx)) { - ntfs_log_perror("Could not remove unused attr"); - goto put_err_out; - } - ntfs_attr_reinit_search_ctx(ctx); - } - if (errno != ENOENT) { - ntfs_log_perror("%s: Attr lookup failed", __FUNCTION__); - goto put_err_out; - } - ntfs_log_trace("Deallocate done.\n"); - ntfs_attr_put_search_ctx(ctx); - goto ok; - } - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; + /* Deallocate not used attribute extents and return with success. */ + if (finished_build) { + ntfs_attr_reinit_search_ctx(ctx); + ntfs_log_trace("Deallocate marked extents.\n"); + while (!ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (sle64_to_cpu(ctx->attr->highest_vcn) != + NTFS_VCN_DELETE_MARK) + continue; + /* Remove unused attribute record. */ + if (ntfs_attr_record_rm(ctx)) { + ntfs_log_perror("Could not remove unused attr"); + goto put_err_out; + } + ntfs_attr_reinit_search_ctx(ctx); + } + if (errno != ENOENT) { + ntfs_log_perror("%s: Attr lookup failed", __FUNCTION__); + goto put_err_out; + } + ntfs_log_trace("Deallocate done.\n"); + ntfs_attr_put_search_ctx(ctx); + goto ok; + } + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; - /* Allocate new MFT records for the rest of mapping pairs. */ - while (1) { - /* Calculate size of rest mapping pairs. */ - mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, - na->rl, stop_vcn, INT_MAX); - if (mp_size <= 0) { - ntfs_log_perror("%s: get mp size failed", __FUNCTION__); - goto put_err_out; - } - /* Allocate new mft record. */ - ni = ntfs_mft_record_alloc(na->ni->vol, base_ni); - if (!ni) { - ntfs_log_perror("Could not allocate new MFT record"); - goto put_err_out; - } - m = ni->mrec; - /* - * If mapping size exceed available space, set them to - * possible maximum. - */ - cur_max_mp_size = le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) - - (offsetof(ATTR_RECORD, compressed_size) + - (((na->data_flags & ATTR_COMPRESSION_MASK) - || NAttrSparse(na)) ? - sizeof(a->compressed_size) : 0)) - - ((sizeof(ntfschar) * na->name_len + 7) & ~7); - if (mp_size > cur_max_mp_size) - mp_size = cur_max_mp_size; - /* Add attribute extent to new record. */ - err = ntfs_non_resident_attr_record_add(ni, na->type, - na->name, na->name_len, stop_vcn, mp_size, - na->data_flags); - if (err == -1) { - err = errno; - ntfs_log_perror("Could not add attribute extent"); - if (ntfs_mft_record_free(na->ni->vol, ni)) - ntfs_log_perror("Could not free MFT record"); - errno = err; - goto put_err_out; - } - a = (ATTR_RECORD*)((u8*)m + err); + /* Allocate new MFT records for the rest of mapping pairs. */ + while (1) { + /* Calculate size of rest mapping pairs. */ + mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, + na->rl, stop_vcn, INT_MAX); + if (mp_size <= 0) { + ntfs_log_perror("%s: get mp size failed", __FUNCTION__); + goto put_err_out; + } + /* Allocate new mft record. */ + ni = ntfs_mft_record_alloc(na->ni->vol, base_ni); + if (!ni) { + ntfs_log_perror("Could not allocate new MFT record"); + goto put_err_out; + } + m = ni->mrec; + /* + * If mapping size exceed available space, set them to + * possible maximum. + */ + cur_max_mp_size = le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use) - + (offsetof(ATTR_RECORD, compressed_size) + + (((na->data_flags & ATTR_COMPRESSION_MASK) + || NAttrSparse(na)) ? + sizeof(a->compressed_size) : 0)) - + ((sizeof(ntfschar) * na->name_len + 7) & ~7); + if (mp_size > cur_max_mp_size) + mp_size = cur_max_mp_size; + /* Add attribute extent to new record. */ + err = ntfs_non_resident_attr_record_add(ni, na->type, + na->name, na->name_len, stop_vcn, mp_size, + na->data_flags); + if (err == -1) { + err = errno; + ntfs_log_perror("Could not add attribute extent"); + if (ntfs_mft_record_free(na->ni->vol, ni)) + ntfs_log_perror("Could not free MFT record"); + errno = err; + goto put_err_out; + } + a = (ATTR_RECORD*)((u8*)m + err); - err = ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), mp_size, na->rl, - stop_vcn, &stop_rl); - if (stop_rl) - stop_vcn = stop_rl->vcn; - else - stop_vcn = 0; - if (err < 0 && errno != ENOSPC) { - err = errno; - ntfs_log_perror("Failed to build MP"); - if (ntfs_mft_record_free(na->ni->vol, ni)) - ntfs_log_perror("Couldn't free MFT record"); - errno = err; - goto put_err_out; - } - a->highest_vcn = cpu_to_sle64(stop_vcn - 1); - ntfs_inode_mark_dirty(ni); - /* All mapping pairs has been written. */ - if (!err) - break; - } + err = ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + + le16_to_cpu(a->mapping_pairs_offset), mp_size, na->rl, + stop_vcn, &stop_rl); + if (stop_rl) + stop_vcn = stop_rl->vcn; + else + stop_vcn = 0; + if (err < 0 && errno != ENOSPC) { + err = errno; + ntfs_log_perror("Failed to build MP"); + if (ntfs_mft_record_free(na->ni->vol, ni)) + ntfs_log_perror("Couldn't free MFT record"); + errno = err; + goto put_err_out; + } + a->highest_vcn = cpu_to_sle64(stop_vcn - 1); + ntfs_inode_mark_dirty(ni); + /* All mapping pairs has been written. */ + if (!err) + break; + } ok: - ret = 0; + ret = 0; out: - return ret; + return ret; put_err_out: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - goto out; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + goto out; } #undef NTFS_VCN_DELETE_MARK @@ -5150,13 +5189,14 @@ put_err_out: * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST * or there is no free MFT records left to allocate. */ -int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_attr_update_mapping_pairs_i(na, from_vcn); - ntfs_log_leave("\n"); - return ret; +int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) +{ + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_attr_update_mapping_pairs_i(na, from_vcn); + ntfs_log_leave("\n"); + return ret; } /** @@ -5171,123 +5211,124 @@ int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) { * ENOMEM - Not enough memory to complete operation. * ERANGE - @newsize is not valid for the attribute type of @na. */ -static int ntfs_non_resident_attr_shrink(ntfs_attr *na, const s64 newsize) { - ntfs_volume *vol; - ntfs_attr_search_ctx *ctx; - VCN first_free_vcn; - s64 nr_freed_clusters; - int err; +static int ntfs_non_resident_attr_shrink(ntfs_attr *na, const s64 newsize) +{ + ntfs_volume *vol; + ntfs_attr_search_ctx *ctx; + VCN first_free_vcn; + s64 nr_freed_clusters; + int err; - ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", (unsigned long long) - na->ni->mft_no, na->type, (long long)newsize); + ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", (unsigned long long) + na->ni->mft_no, na->type, (long long)newsize); - vol = na->ni->vol; + vol = na->ni->vol; - /* - * Check the attribute type and the corresponding minimum size - * against @newsize and fail if @newsize is too small. - */ - if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { - if (errno == ERANGE) { - ntfs_log_trace("Eeek! Size bounds check failed. " - "Aborting...\n"); - } else if (errno == ENOENT) - errno = EIO; - return -1; - } + /* + * Check the attribute type and the corresponding minimum size + * against @newsize and fail if @newsize is too small. + */ + if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { + if (errno == ERANGE) { + ntfs_log_trace("Eeek! Size bounds check failed. " + "Aborting...\n"); + } else if (errno == ENOENT) + errno = EIO; + return -1; + } - /* The first cluster outside the new allocation. */ - first_free_vcn = (newsize + vol->cluster_size - 1) >> - vol->cluster_size_bits; - /* - * Compare the new allocation with the old one and only deallocate - * clusters if there is a change. - */ - if ((na->allocated_size >> vol->cluster_size_bits) != first_free_vcn) { - if (ntfs_attr_map_whole_runlist(na)) { - ntfs_log_trace("Eeek! ntfs_attr_map_whole_runlist " - "failed.\n"); - return -1; - } - /* Deallocate all clusters starting with the first free one. */ - nr_freed_clusters = ntfs_cluster_free(vol, na, first_free_vcn, - -1); - if (nr_freed_clusters < 0) { - ntfs_log_trace("Eeek! Freeing of clusters failed. " - "Aborting...\n"); - return -1; - } + /* The first cluster outside the new allocation. */ + first_free_vcn = (newsize + vol->cluster_size - 1) >> + vol->cluster_size_bits; + /* + * Compare the new allocation with the old one and only deallocate + * clusters if there is a change. + */ + if ((na->allocated_size >> vol->cluster_size_bits) != first_free_vcn) { + if (ntfs_attr_map_whole_runlist(na)) { + ntfs_log_trace("Eeek! ntfs_attr_map_whole_runlist " + "failed.\n"); + return -1; + } + /* Deallocate all clusters starting with the first free one. */ + nr_freed_clusters = ntfs_cluster_free(vol, na, first_free_vcn, + -1); + if (nr_freed_clusters < 0) { + ntfs_log_trace("Eeek! Freeing of clusters failed. " + "Aborting...\n"); + return -1; + } - /* Truncate the runlist itself. */ - if (ntfs_rl_truncate(&na->rl, first_free_vcn)) { - /* - * Failed to truncate the runlist, so just throw it - * away, it will be mapped afresh on next use. - */ - free(na->rl); - na->rl = NULL; - ntfs_log_trace("Eeek! Run list truncation failed.\n"); - return -1; - } + /* Truncate the runlist itself. */ + if (ntfs_rl_truncate(&na->rl, first_free_vcn)) { + /* + * Failed to truncate the runlist, so just throw it + * away, it will be mapped afresh on next use. + */ + free(na->rl); + na->rl = NULL; + ntfs_log_trace("Eeek! Run list truncation failed.\n"); + return -1; + } - /* Prepare to mapping pairs update. */ - na->allocated_size = first_free_vcn << vol->cluster_size_bits; - /* Write mapping pairs for new runlist. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*first_free_vcn*/)) { - ntfs_log_trace("Eeek! Mapping pairs update failed. " - "Leaving inconstant metadata. " - "Run chkdsk.\n"); - return -1; - } - } + /* Prepare to mapping pairs update. */ + na->allocated_size = first_free_vcn << vol->cluster_size_bits; + /* Write mapping pairs for new runlist. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*first_free_vcn*/)) { + ntfs_log_trace("Eeek! Mapping pairs update failed. " + "Leaving inconstant metadata. " + "Run chkdsk.\n"); + return -1; + } + } - /* Get the first attribute record. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; + /* Get the first attribute record. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - err = errno; - if (err == ENOENT) - err = EIO; - ntfs_log_trace("Eeek! Lookup of first attribute extent failed. " - "Leaving inconstant metadata.\n"); - goto put_err_out; - } + if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + err = errno; + if (err == ENOENT) + err = EIO; + ntfs_log_trace("Eeek! Lookup of first attribute extent failed. " + "Leaving inconstant metadata.\n"); + goto put_err_out; + } - /* Update data and initialized size. */ - na->data_size = newsize; - ctx->attr->data_size = cpu_to_sle64(newsize); - if (newsize < na->initialized_size) { - na->initialized_size = newsize; - ctx->attr->initialized_size = cpu_to_sle64(newsize); - } - /* Update data size in the index. */ - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - NInoFileNameSetDirty(na->ni); - } + /* Update data and initialized size. */ + na->data_size = newsize; + ctx->attr->data_size = cpu_to_sle64(newsize); + if (newsize < na->initialized_size) { + na->initialized_size = newsize; + ctx->attr->initialized_size = cpu_to_sle64(newsize); + } + /* Update data size in the index. */ + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + na->ni->data_size = na->data_size; + NInoFileNameSetDirty(na->ni); + } - /* If the attribute now has zero size, make it resident. */ - if (!newsize) { - if (ntfs_attr_make_resident(na, ctx)) { - /* If couldn't make resident, just continue. */ - if (errno != EPERM) - ntfs_log_error("Failed to make attribute " - "resident. Leaving as is...\n"); - } - } + /* If the attribute now has zero size, make it resident. */ + if (!newsize) { + if (ntfs_attr_make_resident(na, ctx)) { + /* If couldn't make resident, just continue. */ + if (errno != EPERM) + ntfs_log_error("Failed to make attribute " + "resident. Leaving as is...\n"); + } + } - /* Set the inode dirty so it is written out later. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - /* Done! */ - ntfs_attr_put_search_ctx(ctx); - return 0; + /* Set the inode dirty so it is written out later. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + /* Done! */ + ntfs_attr_put_search_ctx(ctx); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } /** @@ -5304,207 +5345,209 @@ put_err_out: * ERANGE - @newsize is not valid for the attribute type of @na. * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. */ -static int ntfs_non_resident_attr_expand_i(ntfs_attr *na, const s64 newsize) { - LCN lcn_seek_from; - VCN first_free_vcn; - ntfs_volume *vol; - ntfs_attr_search_ctx *ctx; - runlist *rl, *rln; - s64 org_alloc_size; - int err; +static int ntfs_non_resident_attr_expand_i(ntfs_attr *na, const s64 newsize) +{ + LCN lcn_seek_from; + VCN first_free_vcn; + ntfs_volume *vol; + ntfs_attr_search_ctx *ctx; + runlist *rl, *rln; + s64 org_alloc_size; + int err; - ntfs_log_trace("Inode %lld, attr 0x%x, new size %lld old size %lld\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)newsize, (long long)na->data_size); + ntfs_log_trace("Inode %lld, attr 0x%x, new size %lld old size %lld\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)newsize, (long long)na->data_size); - vol = na->ni->vol; + vol = na->ni->vol; - /* - * Check the attribute type and the corresponding maximum size - * against @newsize and fail if @newsize is too big. - */ - if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { - if (errno == ENOENT) - errno = EIO; - ntfs_log_perror("%s: bounds check failed", __FUNCTION__); - return -1; - } + /* + * Check the attribute type and the corresponding maximum size + * against @newsize and fail if @newsize is too big. + */ + if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { + if (errno == ENOENT) + errno = EIO; + ntfs_log_perror("%s: bounds check failed", __FUNCTION__); + return -1; + } - /* Save for future use. */ - org_alloc_size = na->allocated_size; - /* The first cluster outside the new allocation. */ - first_free_vcn = (newsize + vol->cluster_size - 1) >> - vol->cluster_size_bits; - /* - * Compare the new allocation with the old one and only allocate - * clusters if there is a change. - */ - if ((na->allocated_size >> vol->cluster_size_bits) < first_free_vcn) { - if (ntfs_attr_map_whole_runlist(na)) { - ntfs_log_perror("ntfs_attr_map_whole_runlist failed"); - return -1; - } + /* Save for future use. */ + org_alloc_size = na->allocated_size; + /* The first cluster outside the new allocation. */ + first_free_vcn = (newsize + vol->cluster_size - 1) >> + vol->cluster_size_bits; + /* + * Compare the new allocation with the old one and only allocate + * clusters if there is a change. + */ + if ((na->allocated_size >> vol->cluster_size_bits) < first_free_vcn) { + if (ntfs_attr_map_whole_runlist(na)) { + ntfs_log_perror("ntfs_attr_map_whole_runlist failed"); + return -1; + } - /* - * If we extend $DATA attribute on NTFS 3+ volume, we can add - * sparse runs instead of real allocation of clusters. - */ - if (na->type == AT_DATA && vol->major_ver >= 3) { - rl = ntfs_malloc(0x1000); - if (!rl) - return -1; + /* + * If we extend $DATA attribute on NTFS 3+ volume, we can add + * sparse runs instead of real allocation of clusters. + */ + if (na->type == AT_DATA && vol->major_ver >= 3) { + rl = ntfs_malloc(0x1000); + if (!rl) + return -1; + + rl[0].vcn = (na->allocated_size >> + vol->cluster_size_bits); + rl[0].lcn = LCN_HOLE; + rl[0].length = first_free_vcn - + (na->allocated_size >> vol->cluster_size_bits); + rl[1].vcn = first_free_vcn; + rl[1].lcn = LCN_ENOENT; + rl[1].length = 0; + } else { + /* + * Determine first after last LCN of attribute. + * We will start seek clusters from this LCN to avoid + * fragmentation. If there are no valid LCNs in the + * attribute let the cluster allocator choose the + * starting LCN. + */ + lcn_seek_from = -1; + if (na->rl->length) { + /* Seek to the last run list element. */ + for (rl = na->rl; (rl + 1)->length; rl++) + ; + /* + * If the last LCN is a hole or similar seek + * back to last valid LCN. + */ + while (rl->lcn < 0 && rl != na->rl) + rl--; + /* + * Only set lcn_seek_from it the LCN is valid. + */ + if (rl->lcn >= 0) + lcn_seek_from = rl->lcn + rl->length; + } - rl[0].vcn = (na->allocated_size >> - vol->cluster_size_bits); - rl[0].lcn = LCN_HOLE; - rl[0].length = first_free_vcn - - (na->allocated_size >> vol->cluster_size_bits); - rl[1].vcn = first_free_vcn; - rl[1].lcn = LCN_ENOENT; - rl[1].length = 0; - } else { - /* - * Determine first after last LCN of attribute. - * We will start seek clusters from this LCN to avoid - * fragmentation. If there are no valid LCNs in the - * attribute let the cluster allocator choose the - * starting LCN. - */ - lcn_seek_from = -1; - if (na->rl->length) { - /* Seek to the last run list element. */ - for (rl = na->rl; (rl + 1)->length; rl++) - ; - /* - * If the last LCN is a hole or similar seek - * back to last valid LCN. - */ - while (rl->lcn < 0 && rl != na->rl) - rl--; - /* - * Only set lcn_seek_from it the LCN is valid. - */ - if (rl->lcn >= 0) - lcn_seek_from = rl->lcn + rl->length; - } + rl = ntfs_cluster_alloc(vol, na->allocated_size >> + vol->cluster_size_bits, first_free_vcn - + (na->allocated_size >> + vol->cluster_size_bits), lcn_seek_from, + DATA_ZONE); + if (!rl) { + ntfs_log_perror("Cluster allocation failed " + "(%lld)", + (long long)first_free_vcn - + ((long long)na->allocated_size >> + vol->cluster_size_bits)); + return -1; + } + } - rl = ntfs_cluster_alloc(vol, na->allocated_size >> - vol->cluster_size_bits, first_free_vcn - - (na->allocated_size >> - vol->cluster_size_bits), lcn_seek_from, - DATA_ZONE); - if (!rl) { - ntfs_log_perror("Cluster allocation failed " - "(%lld)", - (long long)first_free_vcn - - ((long long)na->allocated_size >> - vol->cluster_size_bits)); - return -1; - } - } + /* Append new clusters to attribute runlist. */ + rln = ntfs_runlists_merge(na->rl, rl); + if (!rln) { + /* Failed, free just allocated clusters. */ + err = errno; + ntfs_log_perror("Run list merge failed"); + ntfs_cluster_free_from_rl(vol, rl); + free(rl); + errno = err; + return -1; + } + na->rl = rln; - /* Append new clusters to attribute runlist. */ - rln = ntfs_runlists_merge(na->rl, rl); - if (!rln) { - /* Failed, free just allocated clusters. */ - err = errno; - ntfs_log_perror("Run list merge failed"); - ntfs_cluster_free_from_rl(vol, rl); - free(rl); - errno = err; - return -1; - } - na->rl = rln; - - /* Prepare to mapping pairs update. */ - na->allocated_size = first_free_vcn << vol->cluster_size_bits; - /* Write mapping pairs for new runlist. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> + /* Prepare to mapping pairs update. */ + na->allocated_size = first_free_vcn << vol->cluster_size_bits; + /* Write mapping pairs for new runlist. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> vol->cluster_size_bits*/)) { - err = errno; - ntfs_log_perror("Mapping pairs update failed"); - goto rollback; - } - } + err = errno; + ntfs_log_perror("Mapping pairs update failed"); + goto rollback; + } + } - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) { - err = errno; - if (na->allocated_size == org_alloc_size) { - errno = err; - return -1; - } else - goto rollback; - } + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) { + err = errno; + if (na->allocated_size == org_alloc_size) { + errno = err; + return -1; + } else + goto rollback; + } - if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - err = errno; - ntfs_log_perror("Lookup of first attribute extent failed"); - if (err == ENOENT) - err = EIO; - if (na->allocated_size != org_alloc_size) { - ntfs_attr_put_search_ctx(ctx); - goto rollback; - } else - goto put_err_out; - } + if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + err = errno; + ntfs_log_perror("Lookup of first attribute extent failed"); + if (err == ENOENT) + err = EIO; + if (na->allocated_size != org_alloc_size) { + ntfs_attr_put_search_ctx(ctx); + goto rollback; + } else + goto put_err_out; + } - /* Update data size. */ - na->data_size = newsize; - ctx->attr->data_size = cpu_to_sle64(newsize); - /* Update data size in the index. */ - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - NInoFileNameSetDirty(na->ni); - } - /* Set the inode dirty so it is written out later. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - /* Done! */ - ntfs_attr_put_search_ctx(ctx); - return 0; + /* Update data size. */ + na->data_size = newsize; + ctx->attr->data_size = cpu_to_sle64(newsize); + /* Update data size in the index. */ + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + na->ni->data_size = na->data_size; + NInoFileNameSetDirty(na->ni); + } + /* Set the inode dirty so it is written out later. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + /* Done! */ + ntfs_attr_put_search_ctx(ctx); + return 0; rollback: - /* Free allocated clusters. */ - if (ntfs_cluster_free(vol, na, org_alloc_size >> - vol->cluster_size_bits, -1) < 0) { - err = EIO; - ntfs_log_perror("Leaking clusters"); - } - /* Now, truncate the runlist itself. */ - if (ntfs_rl_truncate(&na->rl, org_alloc_size >> - vol->cluster_size_bits)) { - /* - * Failed to truncate the runlist, so just throw it away, it - * will be mapped afresh on next use. - */ - free(na->rl); - na->rl = NULL; - ntfs_log_perror("Couldn't truncate runlist. Rollback failed"); - } else { - /* Prepare to mapping pairs update. */ - na->allocated_size = org_alloc_size; - /* Restore mapping pairs. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> + /* Free allocated clusters. */ + if (ntfs_cluster_free(vol, na, org_alloc_size >> + vol->cluster_size_bits, -1) < 0) { + err = EIO; + ntfs_log_perror("Leaking clusters"); + } + /* Now, truncate the runlist itself. */ + if (ntfs_rl_truncate(&na->rl, org_alloc_size >> + vol->cluster_size_bits)) { + /* + * Failed to truncate the runlist, so just throw it away, it + * will be mapped afresh on next use. + */ + free(na->rl); + na->rl = NULL; + ntfs_log_perror("Couldn't truncate runlist. Rollback failed"); + } else { + /* Prepare to mapping pairs update. */ + na->allocated_size = org_alloc_size; + /* Restore mapping pairs. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> vol->cluster_size_bits*/)) { - ntfs_log_perror("Failed to restore old mapping pairs"); - } - } - errno = err; - return -1; + ntfs_log_perror("Failed to restore old mapping pairs"); + } + } + errno = err; + return -1; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } -static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_non_resident_attr_expand_i(na, newsize); - ntfs_log_leave("\n"); - return ret; +static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) +{ + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_non_resident_attr_expand_i(na, newsize); + ntfs_log_leave("\n"); + return ret; } /** @@ -5527,81 +5570,82 @@ static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) { * EOPNOTSUPP - The desired resize is not implemented yet. * EACCES - Encrypted attribute. */ -int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize) { - int ret = STATUS_ERROR; - s64 fullsize; - BOOL compressed; +int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize) +{ + int ret = STATUS_ERROR; + s64 fullsize; + BOOL compressed; - if (!na || newsize < 0 || - (na->ni->mft_no == FILE_MFT && na->type == AT_DATA)) { - ntfs_log_trace("Invalid arguments passed.\n"); - errno = EINVAL; - return STATUS_ERROR; - } + if (!na || newsize < 0 || + (na->ni->mft_no == FILE_MFT && na->type == AT_DATA)) { + ntfs_log_trace("Invalid arguments passed.\n"); + errno = EINVAL; + return STATUS_ERROR; + } - ntfs_log_enter("Entering for inode %lld, attr 0x%x, size %lld\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)newsize); + ntfs_log_enter("Entering for inode %lld, attr 0x%x, size %lld\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)newsize); - if (na->data_size == newsize) { - ntfs_log_trace("Size is already ok\n"); - ret = STATUS_OK; - goto out; - } - /* - * Encrypted attributes are not supported. We return access denied, - * which is what Windows NT4 does, too. - */ - if (na->data_flags & ATTR_IS_ENCRYPTED) { - errno = EACCES; - ntfs_log_info("Failed to truncate encrypted attribute"); - goto out; - } - /* - * TODO: Implement making handling of compressed attributes. - * Currently we can only expand the attribute or delete it, - * and only for ATTR_IS_COMPRESSED. This is however possible - * for resident attributes when there is no open fuse context - * (important case : $INDEX_ROOT:$I30) - */ - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - if (compressed - && NAttrNonResident(na) - && (((na->data_flags & ATTR_COMPRESSION_MASK) != ATTR_IS_COMPRESSED) - || (newsize && (newsize < na->data_size)))) { - errno = EOPNOTSUPP; - ntfs_log_perror("Failed to truncate compressed attribute"); - goto out; - } - if (NAttrNonResident(na)) { - /* - * For compressed data, the last block must be fully - * allocated, and we do not known the size of compression - * block until the attribute has been made non-resident. - * Moreover we can only process a single compression - * block at a time (from where we are about to write), - * so we silently do not allocate more. - * - * Note : do not request truncate on compressed files - * unless being able to face the consequences ! - */ - if (compressed && newsize) - fullsize = (na->initialized_size - | (na->compression_block_size - 1)) + 1; - else - fullsize = newsize; - if (fullsize > na->data_size) - ret = ntfs_non_resident_attr_expand(na, fullsize); - else - ret = ntfs_non_resident_attr_shrink(na, fullsize); - } else - ret = ntfs_resident_attr_resize(na, newsize); -out: - ntfs_log_leave("Return status %d\n", ret); - return ret; + if (na->data_size == newsize) { + ntfs_log_trace("Size is already ok\n"); + ret = STATUS_OK; + goto out; + } + /* + * Encrypted attributes are not supported. We return access denied, + * which is what Windows NT4 does, too. + */ + if (na->data_flags & ATTR_IS_ENCRYPTED) { + errno = EACCES; + ntfs_log_info("Failed to truncate encrypted attribute"); + goto out; + } + /* + * TODO: Implement making handling of compressed attributes. + * Currently we can only expand the attribute or delete it, + * and only for ATTR_IS_COMPRESSED. This is however possible + * for resident attributes when there is no open fuse context + * (important case : $INDEX_ROOT:$I30) + */ + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + if (compressed + && NAttrNonResident(na) + && (((na->data_flags & ATTR_COMPRESSION_MASK) != ATTR_IS_COMPRESSED) + || (newsize && (newsize < na->data_size)))) { + errno = EOPNOTSUPP; + ntfs_log_perror("Failed to truncate compressed attribute"); + goto out; + } + if (NAttrNonResident(na)) { + /* + * For compressed data, the last block must be fully + * allocated, and we do not known the size of compression + * block until the attribute has been made non-resident. + * Moreover we can only process a single compression + * block at a time (from where we are about to write), + * so we silently do not allocate more. + * + * Note : do not request truncate on compressed files + * unless being able to face the consequences ! + */ + if (compressed && newsize) + fullsize = (na->initialized_size + | (na->compression_block_size - 1)) + 1; + else + fullsize = newsize; + if (fullsize > na->data_size) + ret = ntfs_non_resident_attr_expand(na, fullsize); + else + ret = ntfs_non_resident_attr_shrink(na, fullsize); + } else + ret = ntfs_resident_attr_resize(na, newsize); +out: + ntfs_log_leave("Return status %d\n", ret); + return ret; } - + /* * Stuff a hole in a compressed file * @@ -5612,80 +5656,81 @@ out: * -1 if it failed (as explained in errno) */ -static int stuff_hole(ntfs_attr *na, const s64 pos) { - s64 size; - s64 begin_size; - s64 end_size; - char *buf; - int ret; +static int stuff_hole(ntfs_attr *na, const s64 pos) +{ + s64 size; + s64 begin_size; + s64 end_size; + char *buf; + int ret; - ret = 0; - /* - * If the attribute is resident, the compression block size - * is not defined yet and we can make no decision. - * So we first try resizing to the target and if the - * attribute is still resident, we're done - */ - if (!NAttrNonResident(na)) { - ret = ntfs_resident_attr_resize(na, pos); - if (!ret && !NAttrNonResident(na)) - na->initialized_size = na->data_size = pos; - } - if (!ret && NAttrNonResident(na)) { - /* does the hole span over several compression block ? */ - if ((pos ^ na->initialized_size) - & ~(na->compression_block_size - 1)) { - begin_size = ((na->initialized_size - 1) - | (na->compression_block_size - 1)) - + 1 - na->initialized_size; - end_size = pos & (na->compression_block_size - 1); - size = (begin_size > end_size ? begin_size : end_size); - } else { - /* short stuffing in a single compression block */ - begin_size = size = pos - na->initialized_size; - end_size = 0; - } - if (size) - buf = (char*)ntfs_malloc(size); - else - buf = (char*)NULL; - if (buf || !size) { - memset(buf,0,size); - /* stuff into current block */ - if (begin_size - && (ntfs_attr_pwrite(na, - na->initialized_size, begin_size, buf) - != begin_size)) - ret = -1; - /* create an unstuffed hole */ - if (!ret - && ((na->initialized_size + end_size) < pos) - && ntfs_non_resident_attr_expand(na, - pos - end_size)) - ret = -1; - else - na->initialized_size - = na->data_size = pos - end_size; - /* stuff into the target block */ - if (!ret && end_size - && (ntfs_attr_pwrite(na, - na->initialized_size, end_size, buf) - != end_size)) - ret = -1; - if (buf) - free(buf); - } else - ret = -1; - } - /* make absolutely sure we have reached the target */ - if (!ret && (na->initialized_size != pos)) { - ntfs_log_error("Failed to stuff a compressed file" - "target %lld reached %lld\n", - (long long)pos, (long long)na->initialized_size); - errno = EIO; - ret = -1; - } - return (ret); + ret = 0; + /* + * If the attribute is resident, the compression block size + * is not defined yet and we can make no decision. + * So we first try resizing to the target and if the + * attribute is still resident, we're done + */ + if (!NAttrNonResident(na)) { + ret = ntfs_resident_attr_resize(na, pos); + if (!ret && !NAttrNonResident(na)) + na->initialized_size = na->data_size = pos; + } + if (!ret && NAttrNonResident(na)) { + /* does the hole span over several compression block ? */ + if ((pos ^ na->initialized_size) + & ~(na->compression_block_size - 1)) { + begin_size = ((na->initialized_size - 1) + | (na->compression_block_size - 1)) + + 1 - na->initialized_size; + end_size = pos & (na->compression_block_size - 1); + size = (begin_size > end_size ? begin_size : end_size); + } else { + /* short stuffing in a single compression block */ + begin_size = size = pos - na->initialized_size; + end_size = 0; + } + if (size) + buf = (char*)ntfs_malloc(size); + else + buf = (char*)NULL; + if (buf || !size) { + memset(buf,0,size); + /* stuff into current block */ + if (begin_size + && (ntfs_attr_pwrite(na, + na->initialized_size, begin_size, buf) + != begin_size)) + ret = -1; + /* create an unstuffed hole */ + if (!ret + && ((na->initialized_size + end_size) < pos) + && ntfs_non_resident_attr_expand(na, + pos - end_size)) + ret = -1; + else + na->initialized_size + = na->data_size = pos - end_size; + /* stuff into the target block */ + if (!ret && end_size + && (ntfs_attr_pwrite(na, + na->initialized_size, end_size, buf) + != end_size)) + ret = -1; + if (buf) + free(buf); + } else + ret = -1; + } + /* make absolutely sure we have reached the target */ + if (!ret && (na->initialized_size != pos)) { + ntfs_log_error("Failed to stuff a compressed file" + "target %lld reached %lld\n", + (long long)pos, (long long)na->initialized_size); + errno = EIO; + ret = -1; + } + return (ret); } /** @@ -5694,103 +5739,106 @@ static int stuff_hole(ntfs_attr *na, const s64 pos) { * @type: attribute type * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL * @name_len: length of attribute @name in Unicode characters (if @name given) - * @data_size: if non-NULL then store here the data size + * @data_size: if non-NULL then store here the data size * * This function will read the entire content of an ntfs attribute. * If @name is AT_UNNAMED then look specifically for an unnamed attribute. - * If @name is NULL then the attribute could be either named or not. + * If @name is NULL then the attribute could be either named or not. * In both those cases @name_len is not used at all. * - * On success a buffer is allocated with the content of the attribute + * On success a buffer is allocated with the content of the attribute * and which needs to be freed when it's not needed anymore. If the * @data_size parameter is non-NULL then the data size is set there. * * On error NULL is returned with errno set to the error code. */ void *ntfs_attr_readall(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len, s64 *data_size) { - ntfs_attr *na; - void *data, *ret = NULL; - s64 size; - - ntfs_log_enter("Entering\n"); - - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - ntfs_log_perror("ntfs_attr_open failed"); - goto err_exit; - } - data = ntfs_malloc(na->data_size); - if (!data) - goto out; - - size = ntfs_attr_pread(na, 0, na->data_size, data); - if (size != na->data_size) { - ntfs_log_perror("ntfs_attr_pread failed"); - free(data); - goto out; - } - ret = data; - if (data_size) - *data_size = size; + ntfschar *name, u32 name_len, s64 *data_size) +{ + ntfs_attr *na; + void *data, *ret = NULL; + s64 size; + + ntfs_log_enter("Entering\n"); + + na = ntfs_attr_open(ni, type, name, name_len); + if (!na) { + ntfs_log_perror("ntfs_attr_open failed"); + goto err_exit; + } + data = ntfs_malloc(na->data_size); + if (!data) + goto out; + + size = ntfs_attr_pread(na, 0, na->data_size, data); + if (size != na->data_size) { + ntfs_log_perror("ntfs_attr_pread failed"); + free(data); + goto out; + } + ret = data; + if (data_size) + *data_size = size; out: - ntfs_attr_close(na); + ntfs_attr_close(na); err_exit: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) { - ntfs_attr_search_ctx *ctx; - int ret; + u32 name_len) +{ + ntfs_attr_search_ctx *ctx; + int ret; + + ntfs_log_trace("Entering\n"); + + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return 0; + + ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, 0, NULL, 0, + ctx); - ntfs_log_trace("Entering\n"); - - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return 0; - - ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, 0, NULL, 0, - ctx); - - ntfs_attr_put_search_ctx(ctx); - - return !ret; + ntfs_attr_put_search_ctx(ctx); + + return !ret; } -int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) { - ntfs_attr *na; - int ret; +int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, + u32 name_len) +{ + ntfs_attr *na; + int ret; - ntfs_log_trace("Entering\n"); - - if (!ni) { - ntfs_log_error("%s: NULL inode pointer", __FUNCTION__); - errno = EINVAL; - return -1; - } - - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - /* do not log removal of non-existent stream */ - if (type != AT_DATA) { - ntfs_log_perror("Failed to open attribute 0x%02x of inode " - "0x%llx", type, (unsigned long long)ni->mft_no); - } - return -1; - } - - ret = ntfs_attr_rm(na); - if (ret) - ntfs_log_perror("Failed to remove attribute 0x%02x of inode " - "0x%llx", type, (unsigned long long)ni->mft_no); - ntfs_attr_close(na); - - return ret; + ntfs_log_trace("Entering\n"); + + if (!ni) { + ntfs_log_error("%s: NULL inode pointer", __FUNCTION__); + errno = EINVAL; + return -1; + } + + na = ntfs_attr_open(ni, type, name, name_len); + if (!na) { + /* do not log removal of non-existent stream */ + if (type != AT_DATA) { + ntfs_log_perror("Failed to open attribute 0x%02x of inode " + "0x%llx", type, (unsigned long long)ni->mft_no); + } + return -1; + } + + ret = ntfs_attr_rm(na); + if (ret) + ntfs_log_perror("Failed to remove attribute 0x%02x of inode " + "0x%llx", type, (unsigned long long)ni->mft_no); + ntfs_attr_close(na); + + return ret; } /* Below macros are 32-bit ready. */ @@ -5799,57 +5847,56 @@ int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, (((x) >> 3) & 0x11111111)) #define BITCOUNT(x) (((BCX(x) + (BCX(x) >> 4)) & 0x0F0F0F0F) % 255) -static u8 *ntfs_init_lut256(void) { - int i; - u8 *lut; - - lut = ntfs_malloc(256); - if (lut) - for (i = 0; i < 256; i++) - *(lut + i) = 8 - BITCOUNT(i); - return lut; +static u8 *ntfs_init_lut256(void) +{ + int i; + u8 *lut; + + lut = ntfs_malloc(256); + if (lut) + for(i = 0; i < 256; i++) + *(lut + i) = 8 - BITCOUNT(i); + return lut; } -s64 ntfs_attr_get_free_bits(ntfs_attr *na) { - u8 *buf, *lut; - s64 br = 0; - s64 total = 0; - s64 nr_free = 0; +s64 ntfs_attr_get_free_bits(ntfs_attr *na) +{ + u8 *buf, *lut; + s64 br = 0; + s64 total = 0; + s64 nr_free = 0; - lut = ntfs_init_lut256(); - if (!lut) - return -1; + lut = ntfs_init_lut256(); + if (!lut) + return -1; + + buf = ntfs_malloc(65536); + if (!buf) + goto out; - buf = ntfs_malloc(65536); - if (!buf) - goto out; - - while (1) { - u32 *p; - br = ntfs_attr_pread(na, total, 65536, buf); - if (br <= 0) - break; - total += br; - p = (u32 *)buf + br / 4 - 1; - for (; (u8 *)p >= buf; p--) { - nr_free += lut[ *p & 255] + - lut[(*p >> 8) & 255] + - lut[(*p >> 16) & 255] + - lut[(*p >> 24) ]; - } - switch (br % 4) { - case 3: - nr_free += lut[*(buf + br - 3)]; - case 2: - nr_free += lut[*(buf + br - 2)]; - case 1: - nr_free += lut[*(buf + br - 1)]; - } - } - free(buf); + while (1) { + u32 *p; + br = ntfs_attr_pread(na, total, 65536, buf); + if (br <= 0) + break; + total += br; + p = (u32 *)buf + br / 4 - 1; + for (; (u8 *)p >= buf; p--) { + nr_free += lut[ *p & 255] + + lut[(*p >> 8) & 255] + + lut[(*p >> 16) & 255] + + lut[(*p >> 24) ]; + } + switch (br % 4) { + case 3: nr_free += lut[*(buf + br - 3)]; + case 2: nr_free += lut[*(buf + br - 2)]; + case 1: nr_free += lut[*(buf + br - 1)]; + } + } + free(buf); out: - free(lut); - if (!total || br < 0) - return -1; - return nr_free; + free(lut); + if (!total || br < 0) + return -1; + return nr_free; } diff --git a/source/libntfs/attrib.h b/source/libntfs/attrib.h index 0e9603af..bcdb0117 100644 --- a/source/libntfs/attrib.h +++ b/source/libntfs/attrib.h @@ -50,11 +50,11 @@ extern ntfschar TXF_DATA[10]; * TODO: Describe them. */ typedef enum { - LCN_HOLE = -1, /* Keep this as highest value or die! */ - LCN_RL_NOT_MAPPED = -2, - LCN_ENOENT = -3, - LCN_EINVAL = -4, - LCN_EIO = -5, + LCN_HOLE = -1, /* Keep this as highest value or die! */ + LCN_RL_NOT_MAPPED = -2, + LCN_ENOENT = -3, + LCN_EINVAL = -4, + LCN_EIO = -5, } ntfs_lcn_special_values; /** @@ -76,30 +76,30 @@ typedef enum { * matching attribute. */ struct _ntfs_attr_search_ctx { - MFT_RECORD *mrec; - ATTR_RECORD *attr; - BOOL is_first; - ntfs_inode *ntfs_ino; - ATTR_LIST_ENTRY *al_entry; - ntfs_inode *base_ntfs_ino; - MFT_RECORD *base_mrec; - ATTR_RECORD *base_attr; + MFT_RECORD *mrec; + ATTR_RECORD *attr; + BOOL is_first; + ntfs_inode *ntfs_ino; + ATTR_LIST_ENTRY *al_entry; + ntfs_inode *base_ntfs_ino; + MFT_RECORD *base_mrec; + ATTR_RECORD *base_attr; }; extern void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx); extern ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, - MFT_RECORD *mrec); + MFT_RECORD *mrec); extern void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx); extern int ntfs_attr_lookup(const ATTR_TYPES type, const ntfschar *name, - const u32 name_len, const IGNORE_CASE_BOOL ic, - const VCN lowest_vcn, const u8 *val, const u32 val_len, - ntfs_attr_search_ctx *ctx); + const u32 name_len, const IGNORE_CASE_BOOL ic, + const VCN lowest_vcn, const u8 *val, const u32 val_len, + ntfs_attr_search_ctx *ctx); extern int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx); extern ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, - const ATTR_TYPES type); + const ATTR_TYPES type); /** * ntfs_attrs_walk - syntactic sugar for walking all attributes in an inode @@ -126,9 +126,10 @@ extern ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, * // Ooops. An error occurred! You should handle this case. * // Now finished with all attributes in the inode. */ -static __inline__ int ntfs_attrs_walk(ntfs_attr_search_ctx *ctx) { - return ntfs_attr_lookup(AT_UNUSED, NULL, 0, CASE_SENSITIVE, 0, - NULL, 0, ctx); +static __inline__ int ntfs_attrs_walk(ntfs_attr_search_ctx *ctx) +{ + return ntfs_attr_lookup(AT_UNUSED, NULL, 0, CASE_SENSITIVE, 0, + NULL, 0, ctx); } /** @@ -174,20 +175,20 @@ static __inline__ int ntfs_attrs_walk(ntfs_attr_search_ctx *ctx) { * structure. See ntfs_attr_state_bits above. */ struct _ntfs_attr { - runlist_element *rl; - ntfs_inode *ni; - ATTR_TYPES type; - ATTR_FLAGS data_flags; - ntfschar *name; - u32 name_len; - unsigned long state; - s64 allocated_size; - s64 data_size; - s64 initialized_size; - s64 compressed_size; - u32 compression_block_size; - u8 compression_block_size_bits; - u8 compression_block_clusters; + runlist_element *rl; + ntfs_inode *ni; + ATTR_TYPES type; + ATTR_FLAGS data_flags; + ntfschar *name; + u32 name_len; + unsigned long state; + s64 allocated_size; + s64 data_size; + s64 initialized_size; + s64 compressed_size; + u32 compression_block_size; + u8 compression_block_size_bits; + u8 compression_block_clusters; }; /** @@ -195,8 +196,8 @@ struct _ntfs_attr { * structure */ typedef enum { - NA_Initialized, /* 1: structure is initialized. */ - NA_NonResident, /* 1: Attribute is not resident. */ + NA_Initialized, /* 1: structure is initialized. */ + NA_NonResident, /* 1: Attribute is not resident. */ } ntfs_attr_state_bits; #define test_nattr_flag(na, flag) test_bit(NA_##flag, (na)->state) @@ -227,53 +228,53 @@ GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) * For convenience. Used in the attr structure. */ typedef union { - u8 _default; /* Unnamed u8 to serve as default when just using + u8 _default; /* Unnamed u8 to serve as default when just using a_val without specifying any of the below. */ - STANDARD_INFORMATION std_inf; - ATTR_LIST_ENTRY al_entry; - FILE_NAME_ATTR filename; - OBJECT_ID_ATTR obj_id; - SECURITY_DESCRIPTOR_ATTR sec_desc; - VOLUME_NAME vol_name; - VOLUME_INFORMATION vol_inf; - DATA_ATTR data; - INDEX_ROOT index_root; - INDEX_BLOCK index_blk; - BITMAP_ATTR bmp; - REPARSE_POINT reparse; - EA_INFORMATION ea_inf; - EA_ATTR ea; - PROPERTY_SET property_set; - LOGGED_UTILITY_STREAM logged_util_stream; - EFS_ATTR_HEADER efs; + STANDARD_INFORMATION std_inf; + ATTR_LIST_ENTRY al_entry; + FILE_NAME_ATTR filename; + OBJECT_ID_ATTR obj_id; + SECURITY_DESCRIPTOR_ATTR sec_desc; + VOLUME_NAME vol_name; + VOLUME_INFORMATION vol_inf; + DATA_ATTR data; + INDEX_ROOT index_root; + INDEX_BLOCK index_blk; + BITMAP_ATTR bmp; + REPARSE_POINT reparse; + EA_INFORMATION ea_inf; + EA_ATTR ea; + PROPERTY_SET property_set; + LOGGED_UTILITY_STREAM logged_util_stream; + EFS_ATTR_HEADER efs; } attr_val; extern void ntfs_attr_init(ntfs_attr *na, const BOOL non_resident, - const ATTR_FLAGS data_flags, const BOOL encrypted, - const BOOL sparse, - const s64 allocated_size, const s64 data_size, - const s64 initialized_size, const s64 compressed_size, - const u8 compression_unit); + const ATTR_FLAGS data_flags, const BOOL encrypted, + const BOOL sparse, + const s64 allocated_size, const s64 data_size, + const s64 initialized_size, const s64 compressed_size, + const u8 compression_unit); -/* warning : in the following "name" has to be freeable */ -/* or one of constants AT_UNNAMED, NTFS_INDEX_I30 or STREAM_SDS */ + /* warning : in the following "name" has to be freeable */ + /* or one of constants AT_UNNAMED, NTFS_INDEX_I30 or STREAM_SDS */ extern ntfs_attr *ntfs_attr_open(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len); + ntfschar *name, u32 name_len); extern void ntfs_attr_close(ntfs_attr *na); extern s64 ntfs_attr_pread(ntfs_attr *na, const s64 pos, s64 count, - void *b); + void *b); extern s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, - const void *b); + const void *b); extern int ntfs_attr_pclose(ntfs_attr *na); extern void *ntfs_attr_readall(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len, s64 *data_size); + ntfschar *name, u32 name_len, s64 *data_size); extern s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, - const s64 bk_cnt, const u32 bk_size, void *dst); + const s64 bk_cnt, const u32 bk_size, void *dst); extern s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, - s64 bk_cnt, const u32 bk_size, void *src); + s64 bk_cnt, const u32 bk_size, void *src); extern int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn); extern int ntfs_attr_map_whole_runlist(ntfs_attr *na); @@ -282,31 +283,31 @@ extern LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn); extern runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn); extern int ntfs_attr_size_bounds_check(const ntfs_volume *vol, - const ATTR_TYPES type, const s64 size); + const ATTR_TYPES type, const s64 size); extern int ntfs_attr_can_be_resident(const ntfs_volume *vol, - const ATTR_TYPES type); + const ATTR_TYPES type); int ntfs_attr_make_non_resident(ntfs_attr *na, - ntfs_attr_search_ctx *ctx); + ntfs_attr_search_ctx *ctx); extern int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size); extern int ntfs_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, u8 *val, u32 size, - ATTR_FLAGS flags); + ntfschar *name, u8 name_len, u8 *val, u32 size, + ATTR_FLAGS flags); extern int ntfs_non_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size, - ATTR_FLAGS flags); + ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size, + ATTR_FLAGS flags); extern int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx); extern int ntfs_attr_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, u8 *val, s64 size); + ntfschar *name, u8 name_len, u8 *val, s64 size); extern int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask); + ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask); extern int ntfs_attr_rm(ntfs_attr *na); extern int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size); extern int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, - const u32 new_size); + const u32 new_size); extern int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni); extern int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra); @@ -342,15 +343,15 @@ extern s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a); * then nothing was read due to a zero-length attribute value, otherwise * errno describes the error. */ -extern s64 ntfs_get_attribute_value(const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b); +extern s64 ntfs_get_attribute_value(const ntfs_volume *vol, + const ATTR_RECORD *a, u8 *b); extern void ntfs_attr_name_free(char **name); extern char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len); extern int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len); + ntfschar *name, u32 name_len); extern int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len); + ntfschar *name, u32 name_len); extern s64 ntfs_attr_get_free_bits(ntfs_attr *na); #endif /* defined _NTFS_ATTRIB_H */ diff --git a/source/libntfs/attrib_frag.c b/source/libntfs/attrib_frag.c index e543888d..7f5a659e 100644 --- a/source/libntfs/attrib_frag.c +++ b/source/libntfs/attrib_frag.c @@ -67,29 +67,31 @@ ntfschar AT_UNNAMED[] = { const_cpu_to_le16('\0') }; ntfschar STREAM_SDS[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('S'), - const_cpu_to_le16('D'), - const_cpu_to_le16('S'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('S'), + const_cpu_to_le16('D'), + const_cpu_to_le16('S'), + const_cpu_to_le16('\0') }; -static int NAttrFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) { - if (na->type == AT_DATA && na->name == AT_UNNAMED) - return (na->ni->flags & flag); - return 0; +static int NAttrFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) +{ + if (na->type == AT_DATA && na->name == AT_UNNAMED) + return (na->ni->flags & flag); + return 0; } -static void NAttrSetFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) { - if (na->type == AT_DATA && na->name == AT_UNNAMED) - na->ni->flags |= flag; - else - ntfs_log_trace("Denied setting flag %d for not unnamed data " - "attribute\n", flag); +static void NAttrSetFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) +{ + if (na->type == AT_DATA && na->name == AT_UNNAMED) + na->ni->flags |= flag; + else + ntfs_log_trace("Denied setting flag %d for not unnamed data " + "attribute\n", flag); } -static void NAttrClearFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) { - if (na->type == AT_DATA && na->name == AT_UNNAMED) - na->ni->flags &= ~flag; +static void NAttrClearFlag(ntfs_attr *na, FILE_ATTR_FLAGS flag) +{ + if (na->type == AT_DATA && na->name == AT_UNNAMED) + na->ni->flags &= ~flag; } #define GenNAttrIno(func_name, flag) \ @@ -109,186 +111,188 @@ GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) * * Returns: */ -s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a) { - if (!a) { - errno = EINVAL; - return 0; - } - errno = 0; - if (a->non_resident) - return sle64_to_cpu(a->data_size); - - return (s64)le32_to_cpu(a->value_length); +s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a) +{ + if (!a) { + errno = EINVAL; + return 0; + } + errno = 0; + if (a->non_resident) + return sle64_to_cpu(a->data_size); + + return (s64)le32_to_cpu(a->value_length); } /** * ntfs_get_attribute_value - Get a copy of an attribute - * @vol: - * @a: - * @b: + * @vol: + * @a: + * @b: * * Description... * * Returns: */ s64 ntfs_get_attribute_value(const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b) { - runlist *rl; - s64 total, r; - int i; + const ATTR_RECORD *a, u8 *b) +{ + runlist *rl; + s64 total, r; + int i; - /* Sanity checks. */ - if (!vol || !a || !b) { - errno = EINVAL; - return 0; - } - /* Complex attribute? */ - /* - * Ignore the flags in case they are not zero for an attribute list - * attribute. Windows does not complain about invalid flags and chkdsk - * does not detect or fix them so we need to cope with it, too. - */ - if (a->type != AT_ATTRIBUTE_LIST && a->flags) { - ntfs_log_error("Non-zero (%04x) attribute flags. Cannot handle " - "this yet.\n", le16_to_cpu(a->flags)); - errno = EOPNOTSUPP; - return 0; - } - if (!a->non_resident) { - /* Attribute is resident. */ + /* Sanity checks. */ + if (!vol || !a || !b) { + errno = EINVAL; + return 0; + } + /* Complex attribute? */ + /* + * Ignore the flags in case they are not zero for an attribute list + * attribute. Windows does not complain about invalid flags and chkdsk + * does not detect or fix them so we need to cope with it, too. + */ + if (a->type != AT_ATTRIBUTE_LIST && a->flags) { + ntfs_log_error("Non-zero (%04x) attribute flags. Cannot handle " + "this yet.\n", le16_to_cpu(a->flags)); + errno = EOPNOTSUPP; + return 0; + } + if (!a->non_resident) { + /* Attribute is resident. */ - /* Sanity check. */ - if (le32_to_cpu(a->value_length) + le16_to_cpu(a->value_offset) - > le32_to_cpu(a->length)) { - return 0; - } + /* Sanity check. */ + if (le32_to_cpu(a->value_length) + le16_to_cpu(a->value_offset) + > le32_to_cpu(a->length)) { + return 0; + } - memcpy(b, (const char*)a + le16_to_cpu(a->value_offset), - le32_to_cpu(a->value_length)); - errno = 0; - return (s64)le32_to_cpu(a->value_length); - } + memcpy(b, (const char*)a + le16_to_cpu(a->value_offset), + le32_to_cpu(a->value_length)); + errno = 0; + return (s64)le32_to_cpu(a->value_length); + } - /* Attribute is not resident. */ + /* Attribute is not resident. */ - /* If no data, return 0. */ - if (!(a->data_size)) { - errno = 0; - return 0; - } - /* - * FIXME: What about attribute lists?!? (AIA) - */ - /* Decompress the mapping pairs array into a runlist. */ - rl = ntfs_mapping_pairs_decompress(vol, a, NULL); - if (!rl) { - errno = EINVAL; - return 0; - } - /* - * FIXED: We were overflowing here in a nasty fashion when we - * reach the last cluster in the runlist as the buffer will - * only be big enough to hold data_size bytes while we are - * reading in allocated_size bytes which is usually larger - * than data_size, since the actual data is unlikely to have a - * size equal to a multiple of the cluster size! - * FIXED2: We were also overflowing here in the same fashion - * when the data_size was more than one run smaller than the - * allocated size which happens with Windows XP sometimes. - */ - /* Now load all clusters in the runlist into b. */ - for (i = 0, total = 0; rl[i].length; i++) { - if (total + (rl[i].length << vol->cluster_size_bits) >= - sle64_to_cpu(a->data_size)) { - unsigned char *intbuf = NULL; - /* - * We have reached the last run so we were going to - * overflow when executing the ntfs_pread() which is - * BAAAAAAAD! - * Temporary fix: - * Allocate a new buffer with size: - * rl[i].length << vol->cluster_size_bits, do the - * read into our buffer, then memcpy the correct - * amount of data into the caller supplied buffer, - * free our buffer, and continue. - * We have reached the end of data size so we were - * going to overflow in the same fashion. - * Temporary fix: same as above. - */ - intbuf = ntfs_malloc(rl[i].length << vol->cluster_size_bits); - if (!intbuf) { - free(rl); - return 0; - } - /* - * FIXME: If compressed file: Only read if lcn != -1. - * Otherwise, we are dealing with a sparse run and we - * just memset the user buffer to 0 for the length of - * the run, which should be 16 (= compression unit - * size). - * FIXME: Really only when file is compressed, or can - * we have sparse runs in uncompressed files as well? - * - Yes we can, in sparse files! But not necessarily - * size of 16, just run length. - */ - r = ntfs_pread(vol->dev, rl[i].lcn << - vol->cluster_size_bits, rl[i].length << - vol->cluster_size_bits, intbuf); - if (r != rl[i].length << vol->cluster_size_bits) { + /* If no data, return 0. */ + if (!(a->data_size)) { + errno = 0; + return 0; + } + /* + * FIXME: What about attribute lists?!? (AIA) + */ + /* Decompress the mapping pairs array into a runlist. */ + rl = ntfs_mapping_pairs_decompress(vol, a, NULL); + if (!rl) { + errno = EINVAL; + return 0; + } + /* + * FIXED: We were overflowing here in a nasty fashion when we + * reach the last cluster in the runlist as the buffer will + * only be big enough to hold data_size bytes while we are + * reading in allocated_size bytes which is usually larger + * than data_size, since the actual data is unlikely to have a + * size equal to a multiple of the cluster size! + * FIXED2: We were also overflowing here in the same fashion + * when the data_size was more than one run smaller than the + * allocated size which happens with Windows XP sometimes. + */ + /* Now load all clusters in the runlist into b. */ + for (i = 0, total = 0; rl[i].length; i++) { + if (total + (rl[i].length << vol->cluster_size_bits) >= + sle64_to_cpu(a->data_size)) { + unsigned char *intbuf = NULL; + /* + * We have reached the last run so we were going to + * overflow when executing the ntfs_pread() which is + * BAAAAAAAD! + * Temporary fix: + * Allocate a new buffer with size: + * rl[i].length << vol->cluster_size_bits, do the + * read into our buffer, then memcpy the correct + * amount of data into the caller supplied buffer, + * free our buffer, and continue. + * We have reached the end of data size so we were + * going to overflow in the same fashion. + * Temporary fix: same as above. + */ + intbuf = ntfs_malloc(rl[i].length << vol->cluster_size_bits); + if (!intbuf) { + free(rl); + return 0; + } + /* + * FIXME: If compressed file: Only read if lcn != -1. + * Otherwise, we are dealing with a sparse run and we + * just memset the user buffer to 0 for the length of + * the run, which should be 16 (= compression unit + * size). + * FIXME: Really only when file is compressed, or can + * we have sparse runs in uncompressed files as well? + * - Yes we can, in sparse files! But not necessarily + * size of 16, just run length. + */ + r = ntfs_pread(vol->dev, rl[i].lcn << + vol->cluster_size_bits, rl[i].length << + vol->cluster_size_bits, intbuf); + if (r != rl[i].length << vol->cluster_size_bits) { #define ESTR "Error reading attribute value" - if (r == -1) - ntfs_log_perror(ESTR); - else if (r < rl[i].length << - vol->cluster_size_bits) { - ntfs_log_debug(ESTR ": Ran out of input data.\n"); - errno = EIO; - } else { - ntfs_log_debug(ESTR ": unknown error\n"); - errno = EIO; - } + if (r == -1) + ntfs_log_perror(ESTR); + else if (r < rl[i].length << + vol->cluster_size_bits) { + ntfs_log_debug(ESTR ": Ran out of input data.\n"); + errno = EIO; + } else { + ntfs_log_debug(ESTR ": unknown error\n"); + errno = EIO; + } #undef ESTR - free(rl); - free(intbuf); - return 0; - } - memcpy(b + total, intbuf, sle64_to_cpu(a->data_size) - - total); - free(intbuf); - total = sle64_to_cpu(a->data_size); - break; - } - /* - * FIXME: If compressed file: Only read if lcn != -1. - * Otherwise, we are dealing with a sparse run and we just - * memset the user buffer to 0 for the length of the run, which - * should be 16 (= compression unit size). - * FIXME: Really only when file is compressed, or can - * we have sparse runs in uncompressed files as well? - * - Yes we can, in sparse files! But not necessarily size of - * 16, just run length. - */ - r = ntfs_pread(vol->dev, rl[i].lcn << vol->cluster_size_bits, - rl[i].length << vol->cluster_size_bits, - b + total); - if (r != rl[i].length << vol->cluster_size_bits) { + free(rl); + free(intbuf); + return 0; + } + memcpy(b + total, intbuf, sle64_to_cpu(a->data_size) - + total); + free(intbuf); + total = sle64_to_cpu(a->data_size); + break; + } + /* + * FIXME: If compressed file: Only read if lcn != -1. + * Otherwise, we are dealing with a sparse run and we just + * memset the user buffer to 0 for the length of the run, which + * should be 16 (= compression unit size). + * FIXME: Really only when file is compressed, or can + * we have sparse runs in uncompressed files as well? + * - Yes we can, in sparse files! But not necessarily size of + * 16, just run length. + */ + r = ntfs_pread(vol->dev, rl[i].lcn << vol->cluster_size_bits, + rl[i].length << vol->cluster_size_bits, + b + total); + if (r != rl[i].length << vol->cluster_size_bits) { #define ESTR "Error reading attribute value" - if (r == -1) - ntfs_log_perror(ESTR); - else if (r < rl[i].length << vol->cluster_size_bits) { - ntfs_log_debug(ESTR ": Ran out of input data.\n"); - errno = EIO; - } else { - ntfs_log_debug(ESTR ": unknown error\n"); - errno = EIO; - } + if (r == -1) + ntfs_log_perror(ESTR); + else if (r < rl[i].length << vol->cluster_size_bits) { + ntfs_log_debug(ESTR ": Ran out of input data.\n"); + errno = EIO; + } else { + ntfs_log_debug(ESTR ": unknown error\n"); + errno = EIO; + } #undef ESTR - free(rl); - return 0; - } - total += r; - } - free(rl); - return total; + free(rl); + return 0; + } + total += r; + } + free(rl); + return total; } /* Already cleaned up code below, but still look for FIXME:... */ @@ -304,15 +308,16 @@ s64 ntfs_get_attribute_value(const ntfs_volume *vol, * Initialize the ntfs attribute @na with @ni, @type, @name, and @name_len. */ static void __ntfs_attr_init(ntfs_attr *na, ntfs_inode *ni, - const ATTR_TYPES type, ntfschar *name, const u32 name_len) { - na->rl = NULL; - na->ni = ni; - na->type = type; - na->name = name; - if (name) - na->name_len = name_len; - else - na->name_len = 0; + const ATTR_TYPES type, ntfschar *name, const u32 name_len) +{ + na->rl = NULL; + na->ni = ni; + na->type = type; + na->name = name; + if (name) + na->name_len = name_len; + else + na->name_len = 0; } /** @@ -331,36 +336,37 @@ static void __ntfs_attr_init(ntfs_attr *na, ntfs_inode *ni, * Final initialization for an ntfs attribute. */ void ntfs_attr_init(ntfs_attr *na, const BOOL non_resident, - const ATTR_FLAGS data_flags, - const BOOL encrypted, const BOOL sparse, - const s64 allocated_size, const s64 data_size, - const s64 initialized_size, const s64 compressed_size, - const u8 compression_unit) { - if (!NAttrInitialized(na)) { - na->data_flags = data_flags; - if (non_resident) - NAttrSetNonResident(na); - if (data_flags & ATTR_COMPRESSION_MASK) - NAttrSetCompressed(na); - if (encrypted) - NAttrSetEncrypted(na); - if (sparse) - NAttrSetSparse(na); - na->allocated_size = allocated_size; - na->data_size = data_size; - na->initialized_size = initialized_size; - if ((data_flags & ATTR_COMPRESSION_MASK) || sparse) { - ntfs_volume *vol = na->ni->vol; + const ATTR_FLAGS data_flags, + const BOOL encrypted, const BOOL sparse, + const s64 allocated_size, const s64 data_size, + const s64 initialized_size, const s64 compressed_size, + const u8 compression_unit) +{ + if (!NAttrInitialized(na)) { + na->data_flags = data_flags; + if (non_resident) + NAttrSetNonResident(na); + if (data_flags & ATTR_COMPRESSION_MASK) + NAttrSetCompressed(na); + if (encrypted) + NAttrSetEncrypted(na); + if (sparse) + NAttrSetSparse(na); + na->allocated_size = allocated_size; + na->data_size = data_size; + na->initialized_size = initialized_size; + if ((data_flags & ATTR_COMPRESSION_MASK) || sparse) { + ntfs_volume *vol = na->ni->vol; - na->compressed_size = compressed_size; - na->compression_block_clusters = 1 << compression_unit; - na->compression_block_size = 1 << (compression_unit + - vol->cluster_size_bits); - na->compression_block_size_bits = ffs( - na->compression_block_size) - 1; - } - NAttrSetInitialized(na); - } + na->compressed_size = compressed_size; + na->compression_block_clusters = 1 << compression_unit; + na->compression_block_size = 1 << (compression_unit + + vol->cluster_size_bits); + na->compression_block_size_bits = ffs( + na->compression_block_size) - 1; + } + NAttrSetInitialized(na); + } } /** @@ -379,125 +385,126 @@ void ntfs_attr_init(ntfs_attr *na, const BOOL non_resident, * both those cases @name_len is not used at all. */ ntfs_attr *ntfs_attr_open(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len) { - ntfs_attr_search_ctx *ctx; - ntfs_attr *na = NULL; - ntfschar *newname = NULL; - ATTR_RECORD *a; - BOOL cs; + ntfschar *name, u32 name_len) +{ + ntfs_attr_search_ctx *ctx; + ntfs_attr *na = NULL; + ntfschar *newname = NULL; + ATTR_RECORD *a; + BOOL cs; - ntfs_log_enter("Entering for inode %lld, attr 0x%x.\n", - (unsigned long long)ni->mft_no, type); + ntfs_log_enter("Entering for inode %lld, attr 0x%x.\n", + (unsigned long long)ni->mft_no, type); + + if (!ni || !ni->vol || !ni->mrec) { + errno = EINVAL; + goto out; + } + na = ntfs_calloc(sizeof(ntfs_attr)); + if (!na) + goto out; + if (name && name != AT_UNNAMED && name != NTFS_INDEX_I30) { + name = ntfs_ucsndup(name, name_len); + if (!name) + goto err_out; + newname = name; + } - if (!ni || !ni->vol || !ni->mrec) { - errno = EINVAL; - goto out; - } - na = ntfs_calloc(sizeof(ntfs_attr)); - if (!na) - goto out; - if (name && name != AT_UNNAMED && name != NTFS_INDEX_I30) { - name = ntfs_ucsndup(name, name_len); - if (!name) - goto err_out; - newname = name; - } + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + goto err_out; - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - goto err_out; + if (ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx)) + goto put_err_out; - if (ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx)) - goto put_err_out; + a = ctx->attr; + + if (!name) { + if (a->name_length) { + name = ntfs_ucsndup((ntfschar*)((u8*)a + le16_to_cpu( + a->name_offset)), a->name_length); + if (!name) + goto put_err_out; + newname = name; + name_len = a->name_length; + } else { + name = AT_UNNAMED; + name_len = 0; + } + } + + __ntfs_attr_init(na, ni, type, name, name_len); + + /* + * Wipe the flags in case they are not zero for an attribute list + * attribute. Windows does not complain about invalid flags and chkdsk + * does not detect or fix them so we need to cope with it, too. + */ + if (type == AT_ATTRIBUTE_LIST) + a->flags = 0; - a = ctx->attr; + if ((type == AT_DATA) && !a->initialized_size) { + /* + * Define/redefine the compression state if stream is + * empty, based on the compression mark on parent + * directory (for unnamed data streams) or on current + * inode (for named data streams). The compression mark + * may change any time, the compression state can only + * change when stream is wiped out. + */ + a->flags &= ~ATTR_COMPRESSION_MASK; + if (na->ni->flags & FILE_ATTR_COMPRESSED) + a->flags |= ATTR_IS_COMPRESSED; + } + + cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE); + + if (na->type == AT_DATA && na->name == AT_UNNAMED && + ((!(a->flags & ATTR_IS_SPARSE) != !NAttrSparse(na)) || + (!(a->flags & ATTR_IS_ENCRYPTED) != !NAttrEncrypted(na)))) { + errno = EIO; + ntfs_log_perror("Inode %lld has corrupt attribute flags " + "(0x%x <> 0x%x)",(unsigned long long)ni->mft_no, + a->flags, na->ni->flags); + goto put_err_out; + } - if (!name) { - if (a->name_length) { - name = ntfs_ucsndup((ntfschar*)((u8*)a + le16_to_cpu( - a->name_offset)), a->name_length); - if (!name) - goto put_err_out; - newname = name; - name_len = a->name_length; - } else { - name = AT_UNNAMED; - name_len = 0; - } - } - - __ntfs_attr_init(na, ni, type, name, name_len); - - /* - * Wipe the flags in case they are not zero for an attribute list - * attribute. Windows does not complain about invalid flags and chkdsk - * does not detect or fix them so we need to cope with it, too. - */ - if (type == AT_ATTRIBUTE_LIST) - a->flags = 0; - - if ((type == AT_DATA) && !a->initialized_size) { - /* - * Define/redefine the compression state if stream is - * empty, based on the compression mark on parent - * directory (for unnamed data streams) or on current - * inode (for named data streams). The compression mark - * may change any time, the compression state can only - * change when stream is wiped out. - */ - a->flags &= ~ATTR_COMPRESSION_MASK; - if (na->ni->flags & FILE_ATTR_COMPRESSED) - a->flags |= ATTR_IS_COMPRESSED; - } - - cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE); - - if (na->type == AT_DATA && na->name == AT_UNNAMED && - ((!(a->flags & ATTR_IS_SPARSE) != !NAttrSparse(na)) || - (!(a->flags & ATTR_IS_ENCRYPTED) != !NAttrEncrypted(na)))) { - errno = EIO; - ntfs_log_perror("Inode %lld has corrupt attribute flags " - "(0x%x <> 0x%x)",(unsigned long long)ni->mft_no, - a->flags, na->ni->flags); - goto put_err_out; - } - - if (a->non_resident) { - if ((a->flags & ATTR_COMPRESSION_MASK) - && !a->compression_unit) { - errno = EIO; - ntfs_log_perror("Compressed inode %lld attr 0x%x has " - "no compression unit", - (unsigned long long)ni->mft_no, type); - goto put_err_out; - } - ntfs_attr_init(na, TRUE, a->flags, - a->flags & ATTR_IS_ENCRYPTED, - a->flags & ATTR_IS_SPARSE, - sle64_to_cpu(a->allocated_size), - sle64_to_cpu(a->data_size), - sle64_to_cpu(a->initialized_size), - cs ? sle64_to_cpu(a->compressed_size) : 0, - cs ? a->compression_unit : 0); - } else { - s64 l = le32_to_cpu(a->value_length); - ntfs_attr_init(na, FALSE, a->flags, - a->flags & ATTR_IS_ENCRYPTED, - a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l, - cs ? (l + 7) & ~7 : 0, 0); - } - ntfs_attr_put_search_ctx(ctx); + if (a->non_resident) { + if ((a->flags & ATTR_COMPRESSION_MASK) + && !a->compression_unit) { + errno = EIO; + ntfs_log_perror("Compressed inode %lld attr 0x%x has " + "no compression unit", + (unsigned long long)ni->mft_no, type); + goto put_err_out; + } + ntfs_attr_init(na, TRUE, a->flags, + a->flags & ATTR_IS_ENCRYPTED, + a->flags & ATTR_IS_SPARSE, + sle64_to_cpu(a->allocated_size), + sle64_to_cpu(a->data_size), + sle64_to_cpu(a->initialized_size), + cs ? sle64_to_cpu(a->compressed_size) : 0, + cs ? a->compression_unit : 0); + } else { + s64 l = le32_to_cpu(a->value_length); + ntfs_attr_init(na, FALSE, a->flags, + a->flags & ATTR_IS_ENCRYPTED, + a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l, + cs ? (l + 7) & ~7 : 0, 0); + } + ntfs_attr_put_search_ctx(ctx); out: - ntfs_log_leave("\n"); - return na; + ntfs_log_leave("\n"); + return na; put_err_out: - ntfs_attr_put_search_ctx(ctx); + ntfs_attr_put_search_ctx(ctx); err_out: - free(newname); - free(na); - na = NULL; - goto out; + free(newname); + free(na); + na = NULL; + goto out; } /** @@ -507,16 +514,17 @@ err_out: * Release all memory associated with the ntfs attribute @na and then release * @na itself. */ -void ntfs_attr_close(ntfs_attr *na) { - if (!na) - return; - if (NAttrNonResident(na) && na->rl) - free(na->rl); - /* Don't release if using an internal constant. */ - if (na->name != AT_UNNAMED && na->name != NTFS_INDEX_I30 - && na->name != STREAM_SDS) - free(na->name); - free(na); +void ntfs_attr_close(ntfs_attr *na) +{ + if (!na) + return; + if (NAttrNonResident(na) && na->rl) + free(na->rl); + /* Don't release if using an internal constant. */ + if (na->name != AT_UNNAMED && na->name != NTFS_INDEX_I30 + && na->name != STREAM_SDS) + free(na->name); + free(na); } /** @@ -528,38 +536,39 @@ void ntfs_attr_close(ntfs_attr *na) { * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) { - LCN lcn; - ntfs_attr_search_ctx *ctx; +int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) +{ + LCN lcn; + ntfs_attr_search_ctx *ctx; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn 0x%llx.\n", - (unsigned long long)na->ni->mft_no, na->type, (long long)vcn); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn 0x%llx.\n", + (unsigned long long)na->ni->mft_no, na->type, (long long)vcn); - lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); - if (lcn >= 0 || lcn == LCN_HOLE || lcn == LCN_ENOENT) - return 0; + lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); + if (lcn >= 0 || lcn == LCN_HOLE || lcn == LCN_ENOENT) + return 0; - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; - /* Find the attribute in the mft record. */ - if (!ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - vcn, NULL, 0, ctx)) { - runlist_element *rl; + /* Find the attribute in the mft record. */ + if (!ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + vcn, NULL, 0, ctx)) { + runlist_element *rl; - /* Decode the runlist. */ - rl = ntfs_mapping_pairs_decompress(na->ni->vol, ctx->attr, - na->rl); - if (rl) { - na->rl = rl; - ntfs_attr_put_search_ctx(ctx); - return 0; - } - } - - ntfs_attr_put_search_ctx(ctx); - return -1; + /* Decode the runlist. */ + rl = ntfs_mapping_pairs_decompress(na->ni->vol, ctx->attr, + na->rl); + if (rl) { + na->rl = rl; + ntfs_attr_put_search_ctx(ctx); + return 0; + } + } + + ntfs_attr_put_search_ctx(ctx); + return -1; } /** @@ -574,96 +583,97 @@ int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) { * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_whole_runlist(ntfs_attr *na) { - VCN next_vcn, last_vcn, highest_vcn; - ntfs_attr_search_ctx *ctx; - ntfs_volume *vol = na->ni->vol; - ATTR_RECORD *a; - int ret = -1; +int ntfs_attr_map_whole_runlist(ntfs_attr *na) +{ + VCN next_vcn, last_vcn, highest_vcn; + ntfs_attr_search_ctx *ctx; + ntfs_volume *vol = na->ni->vol; + ATTR_RECORD *a; + int ret = -1; - ntfs_log_enter("Entering for inode %llu, attr 0x%x.\n", - (unsigned long long)na->ni->mft_no, na->type); + ntfs_log_enter("Entering for inode %llu, attr 0x%x.\n", + (unsigned long long)na->ni->mft_no, na->type); - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto out; + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + goto out; - /* Map all attribute extents one by one. */ - next_vcn = last_vcn = highest_vcn = 0; - a = NULL; - while (1) { - runlist_element *rl; + /* Map all attribute extents one by one. */ + next_vcn = last_vcn = highest_vcn = 0; + a = NULL; + while (1) { + runlist_element *rl; - int not_mapped = 0; - if (ntfs_rl_vcn_to_lcn(na->rl, next_vcn) == LCN_RL_NOT_MAPPED) - not_mapped = 1; + int not_mapped = 0; + if (ntfs_rl_vcn_to_lcn(na->rl, next_vcn) == LCN_RL_NOT_MAPPED) + not_mapped = 1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, next_vcn, NULL, 0, ctx)) - break; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, next_vcn, NULL, 0, ctx)) + break; - a = ctx->attr; + a = ctx->attr; - if (not_mapped) { - /* Decode the runlist. */ - rl = ntfs_mapping_pairs_decompress(na->ni->vol, - a, na->rl); - if (!rl) - goto err_out; - na->rl = rl; - } + if (not_mapped) { + /* Decode the runlist. */ + rl = ntfs_mapping_pairs_decompress(na->ni->vol, + a, na->rl); + if (!rl) + goto err_out; + na->rl = rl; + } - /* Are we in the first extent? */ - if (!next_vcn) { - if (a->lowest_vcn) { - errno = EIO; - ntfs_log_perror("First extent of inode %llu " - "attribute has non-zero lowest_vcn", - (unsigned long long)na->ni->mft_no); - goto err_out; - } - /* Get the last vcn in the attribute. */ - last_vcn = sle64_to_cpu(a->allocated_size) >> - vol->cluster_size_bits; - } + /* Are we in the first extent? */ + if (!next_vcn) { + if (a->lowest_vcn) { + errno = EIO; + ntfs_log_perror("First extent of inode %llu " + "attribute has non-zero lowest_vcn", + (unsigned long long)na->ni->mft_no); + goto err_out; + } + /* Get the last vcn in the attribute. */ + last_vcn = sle64_to_cpu(a->allocated_size) >> + vol->cluster_size_bits; + } - /* Get the lowest vcn for the next extent. */ - highest_vcn = sle64_to_cpu(a->highest_vcn); - next_vcn = highest_vcn + 1; + /* Get the lowest vcn for the next extent. */ + highest_vcn = sle64_to_cpu(a->highest_vcn); + next_vcn = highest_vcn + 1; - /* Only one extent or error, which we catch below. */ - if (next_vcn <= 0) { - errno = ENOENT; - break; - } + /* Only one extent or error, which we catch below. */ + if (next_vcn <= 0) { + errno = ENOENT; + break; + } - /* Avoid endless loops due to corruption. */ - if (next_vcn < sle64_to_cpu(a->lowest_vcn)) { - errno = EIO; - ntfs_log_perror("Inode %llu has corrupt attribute list", - (unsigned long long)na->ni->mft_no); - goto err_out; - } - } - if (!a) { - ntfs_log_perror("Couldn't find attribute for runlist mapping"); - goto err_out; - } - if (highest_vcn && highest_vcn != last_vcn - 1) { - errno = EIO; - ntfs_log_perror("Failed to load full runlist: inode: %llu " - "highest_vcn: 0x%llx last_vcn: 0x%llx", - (unsigned long long)na->ni->mft_no, - (long long)highest_vcn, (long long)last_vcn); - goto err_out; - } - if (errno == ENOENT) - ret = 0; -err_out: - ntfs_attr_put_search_ctx(ctx); + /* Avoid endless loops due to corruption. */ + if (next_vcn < sle64_to_cpu(a->lowest_vcn)) { + errno = EIO; + ntfs_log_perror("Inode %llu has corrupt attribute list", + (unsigned long long)na->ni->mft_no); + goto err_out; + } + } + if (!a) { + ntfs_log_perror("Couldn't find attribute for runlist mapping"); + goto err_out; + } + if (highest_vcn && highest_vcn != last_vcn - 1) { + errno = EIO; + ntfs_log_perror("Failed to load full runlist: inode: %llu " + "highest_vcn: 0x%llx last_vcn: 0x%llx", + (unsigned long long)na->ni->mft_no, + (long long)highest_vcn, (long long)last_vcn); + goto err_out; + } + if (errno == ENOENT) + ret = 0; +err_out: + ntfs_attr_put_search_ctx(ctx); out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } /** @@ -687,33 +697,34 @@ out: * -4 = LCN_EINVAL Input parameter error. * -5 = LCN_EIO Corrupt fs, disk i/o error, or not enough memory. */ -LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn) { - LCN lcn; - BOOL is_retry = FALSE; +LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn) +{ + LCN lcn; + BOOL is_retry = FALSE; - if (!na || !NAttrNonResident(na) || vcn < 0) - return (LCN)LCN_EINVAL; + if (!na || !NAttrNonResident(na) || vcn < 0) + return (LCN)LCN_EINVAL; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long - long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long + long)na->ni->mft_no, na->type); retry: - /* Convert vcn to lcn. If that fails map the runlist and retry once. */ - lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); - if (lcn >= 0) - return lcn; - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If the attempt to map the runlist failed, or we are getting - * LCN_RL_NOT_MAPPED despite having mapped the attribute extent - * successfully, something is really badly wrong... - */ - if (!is_retry || lcn == (LCN)LCN_RL_NOT_MAPPED) - return (LCN)LCN_EIO; - /* lcn contains the appropriate error code. */ - return lcn; + /* Convert vcn to lcn. If that fails map the runlist and retry once. */ + lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); + if (lcn >= 0) + return lcn; + if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { + is_retry = TRUE; + goto retry; + } + /* + * If the attempt to map the runlist failed, or we are getting + * LCN_RL_NOT_MAPPED despite having mapped the attribute extent + * successfully, something is really badly wrong... + */ + if (!is_retry || lcn == (LCN)LCN_RL_NOT_MAPPED) + return (LCN)LCN_EIO; + /* lcn contains the appropriate error code. */ + return lcn; } /** @@ -736,61 +747,62 @@ retry: * ENOMEM Not enough memory. * EIO I/O error or corrupt metadata. */ -runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn) { - runlist_element *rl; - BOOL is_retry = FALSE; +runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn) +{ + runlist_element *rl; + BOOL is_retry = FALSE; - if (!na || !NAttrNonResident(na) || vcn < 0) { - errno = EINVAL; - return NULL; - } + if (!na || !NAttrNonResident(na) || vcn < 0) { + errno = EINVAL; + return NULL; + } - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn %llx\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)vcn); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, vcn %llx\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)vcn); retry: - rl = na->rl; - if (!rl) - goto map_rl; - if (vcn < rl[0].vcn) - goto map_rl; - while (rl->length) { - if (vcn < rl[1].vcn) { - if (rl->lcn >= (LCN)LCN_HOLE) - return rl; - break; - } - rl++; - } - switch (rl->lcn) { - case (LCN)LCN_RL_NOT_MAPPED: - goto map_rl; - case (LCN)LCN_ENOENT: - errno = ENOENT; - break; - case (LCN)LCN_EINVAL: - errno = EINVAL; - break; - default: - errno = EIO; - break; - } - return NULL; + rl = na->rl; + if (!rl) + goto map_rl; + if (vcn < rl[0].vcn) + goto map_rl; + while (rl->length) { + if (vcn < rl[1].vcn) { + if (rl->lcn >= (LCN)LCN_HOLE) + return rl; + break; + } + rl++; + } + switch (rl->lcn) { + case (LCN)LCN_RL_NOT_MAPPED: + goto map_rl; + case (LCN)LCN_ENOENT: + errno = ENOENT; + break; + case (LCN)LCN_EINVAL: + errno = EINVAL; + break; + default: + errno = EIO; + break; + } + return NULL; map_rl: - /* The @vcn is in an unmapped region, map the runlist and retry. */ - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If we already retried or the mapping attempt failed something has - * gone badly wrong. EINVAL and ENOENT coming from a failed mapping - * attempt are equivalent to errors for us as they should not happen - * in our code paths. - */ - if (is_retry || errno == EINVAL || errno == ENOENT) - errno = EIO; - return NULL; + /* The @vcn is in an unmapped region, map the runlist and retry. */ + if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { + is_retry = TRUE; + goto retry; + } + /* + * If we already retried or the mapping attempt failed something has + * gone badly wrong. EINVAL and ENOENT coming from a failed mapping + * attempt are equivalent to errors for us as they should not happen + * in our code paths. + */ + if (is_retry || errno == EINVAL || errno == ENOENT) + errno = EIO; + return NULL; } @@ -798,244 +810,248 @@ map_rl: /** * ntfs_attr_pread_i - see description at ntfs_attr_pread() - */ + */ static s64 ntfs_attr_getfragments_i(ntfs_attr *na, const s64 pos, s64 count, u64 offset, - _ntfs_frag_append_t append_fragment, void *callback_data) { - u64 b = offset; - s64 br, to_read, ofs, total, total2, max_read, max_init; - ntfs_volume *vol; - runlist_element *rl; + _ntfs_frag_append_t append_fragment, void *callback_data) +{ + u64 b = offset; + s64 br, to_read, ofs, total, total2, max_read, max_init; + ntfs_volume *vol; + runlist_element *rl; // u16 efs_padding_length; - /* Sanity checking arguments is done in ntfs_attr_pread(). */ + /* Sanity checking arguments is done in ntfs_attr_pread(). */ + + if ((na->data_flags & ATTR_COMPRESSION_MASK) && NAttrNonResident(na)) + { + //return -1; // no compressed files + return -31; + /* + if ((na->data_flags & ATTR_COMPRESSION_MASK) + == ATTR_IS_COMPRESSED) + return ntfs_compressed_attr_pread(na, pos, count, b); + else { + // compression mode not supported + errno = EOPNOTSUPP; + return -1; + } + */ + } + /* + * Encrypted non-resident attributes are not supported. We return + * access denied, which is what Windows NT4 does, too. + * However, allow if mounted with efs_raw option + */ + vol = na->ni->vol; + if (!vol->efs_raw && NAttrEncrypted(na) && NAttrNonResident(na)) { + errno = EACCES; + //return -1; + return -32; + } + + if (!count) + return 0; + /* + * Truncate reads beyond end of attribute, + * but round to next 512 byte boundary for encrypted + * attributes with efs_raw mount option + */ + max_read = na->data_size; + max_init = na->initialized_size; + if (na->ni->vol->efs_raw + && (na->data_flags & ATTR_IS_ENCRYPTED) + && NAttrNonResident(na)) { + if (na->data_size != na->initialized_size) { + ntfs_log_error("uninitialized encrypted file not supported\n"); + errno = EINVAL; + //return -1; + return -33; + } + max_init = max_read = ((na->data_size + 511) & ~511) + 2; + } + if (pos + count > max_read) { + if (pos >= max_read) + return 0; + count = max_read - pos; + } + /* If it is a resident attribute, get the value from the mft record. */ + if (!NAttrNonResident(na)) + { + return -34; // No resident files + /* + ntfs_attr_search_ctx *ctx; + char *val; - if ((na->data_flags & ATTR_COMPRESSION_MASK) && NAttrNonResident(na)) { - //return -1; // no compressed files - return -31; - /* - if ((na->data_flags & ATTR_COMPRESSION_MASK) - == ATTR_IS_COMPRESSED) - return ntfs_compressed_attr_pread(na, pos, count, b); - else { - // compression mode not supported - errno = EOPNOTSUPP; - return -1; - } - */ - } - /* - * Encrypted non-resident attributes are not supported. We return - * access denied, which is what Windows NT4 does, too. - * However, allow if mounted with efs_raw option - */ - vol = na->ni->vol; - if (!vol->efs_raw && NAttrEncrypted(na) && NAttrNonResident(na)) { - errno = EACCES; - //return -1; - return -32; - } - - if (!count) - return 0; - /* - * Truncate reads beyond end of attribute, - * but round to next 512 byte boundary for encrypted - * attributes with efs_raw mount option - */ - max_read = na->data_size; - max_init = na->initialized_size; - if (na->ni->vol->efs_raw - && (na->data_flags & ATTR_IS_ENCRYPTED) - && NAttrNonResident(na)) { - if (na->data_size != na->initialized_size) { - ntfs_log_error("uninitialized encrypted file not supported\n"); - errno = EINVAL; - //return -1; - return -33; - } - max_init = max_read = ((na->data_size + 511) & ~511) + 2; - } - if (pos + count > max_read) { - if (pos >= max_read) - return 0; - count = max_read - pos; - } - /* If it is a resident attribute, get the value from the mft record. */ - if (!NAttrNonResident(na)) { - return -34; // No resident files - /* - ntfs_attr_search_ctx *ctx; - char *val; - - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx)) { - res_err_out: - ntfs_attr_put_search_ctx(ctx); - return -1; - } - val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); - if (val < (char*)ctx->attr || val + - le32_to_cpu(ctx->attr->value_length) > - (char*)ctx->mrec + vol->mft_record_size) { - errno = EIO; - ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); - goto res_err_out; - } - memcpy(b, val + pos, count); - ntfs_attr_put_search_ctx(ctx); - return count; - */ - } - total = total2 = 0; - /* Zero out reads beyond initialized size. */ - if (pos + count > max_init) { - if (pos >= max_init) { - //memset(b, 0, count); - return count; - } - total2 = pos + count - max_init; - count -= total2; - //memset((u8*)b + count, 0, total2); - } - /* - * for encrypted non-resident attributes with efs_raw set - * the last two bytes aren't read from disk but contain - * the number of padding bytes so original size can be - * restored - */ - if (na->ni->vol->efs_raw && - (na->data_flags & ATTR_IS_ENCRYPTED) && - ((pos + count) > max_init-2)) { - return -35; //No encrypted files - /* - efs_padding_length = 511 - ((na->data_size - 1) & 511); - if (pos+count == max_init) { - if (count == 1) { - *((u8*)b+count-1) = (u8)(efs_padding_length >> 8); - count--; - total2++; - } else { - *(u16*)((u8*)b+count-2) = cpu_to_le16(efs_padding_length); - count -= 2; - total2 +=2; - } - } else { - *((u8*)b+count-1) = (u8)(efs_padding_length & 0xff); - count--; - total2++; - } - */ - } - - /* Find the runlist element containing the vcn. */ - rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds read. - * However, we already truncated the read to the data_size, - * so getting this here is an error. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #1", __FUNCTION__); - } - //return -1; - return -36; - } - /* - * Gather the requested data into the linear destination buffer. Note, - * a partial final vcn is taken care of by the @count capping of read - * length. - */ - ofs = pos - (rl->vcn << vol->cluster_size_bits); - for (; count; rl++, ofs = 0) { - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #2", - __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = pos + total - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - if (rl->lcn != (LCN)LCN_HOLE) { - ntfs_log_perror("%s: Bad run (%lld)", - __FUNCTION__, - (long long)rl->lcn); - goto rl_err_out; - } - /* It is a hole, just zero the matching @b range. */ - to_read = min(count, (rl->length << - vol->cluster_size_bits) - ofs); - //memset(b, 0, to_read); - /* Update progress counters. */ - total += to_read; - count -= to_read; - b = b + to_read; - continue; - } - /* It is a real lcn, read it into @dst. */ - to_read = min(count, (rl->length << vol->cluster_size_bits) - - ofs); + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx)) { +res_err_out: + ntfs_attr_put_search_ctx(ctx); + return -1; + } + val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); + if (val < (char*)ctx->attr || val + + le32_to_cpu(ctx->attr->value_length) > + (char*)ctx->mrec + vol->mft_record_size) { + errno = EIO; + ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); + goto res_err_out; + } + memcpy(b, val + pos, count); + ntfs_attr_put_search_ctx(ctx); + return count; + */ + } + total = total2 = 0; + /* Zero out reads beyond initialized size. */ + if (pos + count > max_init) { + if (pos >= max_init) { + //memset(b, 0, count); + return count; + } + total2 = pos + count - max_init; + count -= total2; + //memset((u8*)b + count, 0, total2); + } + /* + * for encrypted non-resident attributes with efs_raw set + * the last two bytes aren't read from disk but contain + * the number of padding bytes so original size can be + * restored + */ + if (na->ni->vol->efs_raw && + (na->data_flags & ATTR_IS_ENCRYPTED) && + ((pos + count) > max_init-2)) + { + return -35; //No encrypted files + /* + efs_padding_length = 511 - ((na->data_size - 1) & 511); + if (pos+count == max_init) { + if (count == 1) { + *((u8*)b+count-1) = (u8)(efs_padding_length >> 8); + count--; + total2++; + } else { + *(u16*)((u8*)b+count-2) = cpu_to_le16(efs_padding_length); + count -= 2; + total2 +=2; + } + } else { + *((u8*)b+count-1) = (u8)(efs_padding_length & 0xff); + count--; + total2++; + } + */ + } + + /* Find the runlist element containing the vcn. */ + rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); + if (!rl) { + /* + * If the vcn is not present it is an out of bounds read. + * However, we already truncated the read to the data_size, + * so getting this here is an error. + */ + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #1", __FUNCTION__); + } + //return -1; + return -36; + } + /* + * Gather the requested data into the linear destination buffer. Note, + * a partial final vcn is taken care of by the @count capping of read + * length. + */ + ofs = pos - (rl->vcn << vol->cluster_size_bits); + for (; count; rl++, ofs = 0) { + if (rl->lcn == LCN_RL_NOT_MAPPED) { + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl) { + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #2", + __FUNCTION__); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = pos + total - (rl->vcn << vol->cluster_size_bits); + } + if (!rl->length) { + errno = EIO; + ntfs_log_perror("%s: Zero run length", __FUNCTION__); + goto rl_err_out; + } + if (rl->lcn < (LCN)0) { + if (rl->lcn != (LCN)LCN_HOLE) { + ntfs_log_perror("%s: Bad run (%lld)", + __FUNCTION__, + (long long)rl->lcn); + goto rl_err_out; + } + /* It is a hole, just zero the matching @b range. */ + to_read = min(count, (rl->length << + vol->cluster_size_bits) - ofs); + //memset(b, 0, to_read); + /* Update progress counters. */ + total += to_read; + count -= to_read; + b = b + to_read; + continue; + } + /* It is a real lcn, read it into @dst. */ + to_read = min(count, (rl->length << vol->cluster_size_bits) - + ofs); retry: - ntfs_log_trace("Reading %lld bytes from vcn %lld, lcn %lld, ofs" - " %lld.\n", (long long)to_read, (long long)rl->vcn, - (long long )rl->lcn, (long long)ofs); - /* - br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) + - ofs, to_read, b); - */ - br = to_read; - // convert to sectors unit - u32 off_sec = b >> 9; - u32 sector = ((rl->lcn << vol->cluster_size_bits) + ofs) >> 9; - u32 count_sec = to_read >> 9; - int ret; - ret = append_fragment(callback_data, off_sec, sector, count_sec); - if (ret) { - if (ret < 0) return ret; - return -50; - } - /* If everything ok, update progress counters and continue. */ - if (br > 0) { - total += br; - count -= br; - b = b + br; - } - if (br == to_read) - continue; - /* If the syscall was interrupted, try again. */ - if (br == (s64)-1 && errno == EINTR) - goto retry; - if (total) - return total; - if (!br) - errno = EIO; - ntfs_log_perror("%s: ntfs_pread failed", __FUNCTION__); - //return -1; - return -38; - } - /* Finally, return the number of bytes read. */ - return total + total2; + ntfs_log_trace("Reading %lld bytes from vcn %lld, lcn %lld, ofs" + " %lld.\n", (long long)to_read, (long long)rl->vcn, + (long long )rl->lcn, (long long)ofs); + /* + br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) + + ofs, to_read, b); + */ + br = to_read; + // convert to sectors unit + u32 off_sec = b >> 9; + u32 sector = ((rl->lcn << vol->cluster_size_bits) + ofs) >> 9; + u32 count_sec = to_read >> 9; + int ret; + ret = append_fragment(callback_data, off_sec, sector, count_sec); + if (ret) { + if (ret < 0) return ret; + return -50; + } + /* If everything ok, update progress counters and continue. */ + if (br > 0) { + total += br; + count -= br; + b = b + br; + } + if (br == to_read) + continue; + /* If the syscall was interrupted, try again. */ + if (br == (s64)-1 && errno == EINTR) + goto retry; + if (total) + return total; + if (!br) + errno = EIO; + ntfs_log_perror("%s: ntfs_pread failed", __FUNCTION__); + //return -1; + return -38; + } + /* Finally, return the number of bytes read. */ + return total + total2; rl_err_out: - if (total) - return total; - errno = EIO; - //return -1; - return -39; + if (total) + return total; + errno = EIO; + //return -1; + return -39; } @@ -1059,222 +1075,225 @@ rl_err_out: * arguments. */ s64 ntfs_attr_getfragments(ntfs_attr *na, const s64 pos, s64 count, u64 offset, - _ntfs_frag_append_t append_fragment, void *callback_data) { - s64 ret; + _ntfs_frag_append_t append_fragment, void *callback_data) +{ + s64 ret; - if (!na || !na->ni || !na->ni->vol || !callback_data || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s: na=%p b=%p pos=%lld count=%lld", - __FUNCTION__, na, callback_data, (long long)pos, - (long long)count); - //return -1; - return -21; - } + if (!na || !na->ni || !na->ni->vol || !callback_data || pos < 0 || count < 0) { + errno = EINVAL; + ntfs_log_perror("%s: na=%p b=%p pos=%lld count=%lld", + __FUNCTION__, na, callback_data, (long long)pos, + (long long)count); + //return -1; + return -21; + } - /* - ntfs_log_enter("Entering for inode %lld attr 0x%x pos %lld count " - "%lld\n", (unsigned long long)na->ni->mft_no, - na->type, (long long)pos, (long long)count); - */ + /* + ntfs_log_enter("Entering for inode %lld attr 0x%x pos %lld count " + "%lld\n", (unsigned long long)na->ni->mft_no, + na->type, (long long)pos, (long long)count); + */ - ret = ntfs_attr_getfragments_i(na, pos, count, offset, - append_fragment, callback_data); + ret = ntfs_attr_getfragments_i(na, pos, count, offset, + append_fragment, callback_data); - //ntfs_log_leave("\n"); - return ret; + //ntfs_log_leave("\n"); + return ret; } #if 0 -static int ntfs_attr_fill_zero(ntfs_attr *na, s64 pos, s64 count) { - char *buf; - s64 written, size, end = pos + count; - s64 ofsi; - const runlist_element *rli; - ntfs_volume *vol; - int ret = -1; +static int ntfs_attr_fill_zero(ntfs_attr *na, s64 pos, s64 count) +{ + char *buf; + s64 written, size, end = pos + count; + s64 ofsi; + const runlist_element *rli; + ntfs_volume *vol; + int ret = -1; - ntfs_log_trace("pos %lld, count %lld\n", (long long)pos, - (long long)count); - - if (!na || pos < 0 || count < 0) { - errno = EINVAL; - goto err_out; - } - - buf = ntfs_calloc(NTFS_BUF_SIZE); - if (!buf) - goto err_out; - - rli = na->rl; - ofsi = 0; - vol = na->ni->vol; - while (pos < end) { - while (rli->length && (ofsi + (rli->length << - vol->cluster_size_bits) <= pos)) { - ofsi += (rli->length << vol->cluster_size_bits); - rli++; - } - size = min(end - pos, NTFS_BUF_SIZE); - written = ntfs_rl_pwrite(vol, rli, ofsi, pos, size, buf); - if (written <= 0) { - ntfs_log_perror("Failed to zero space"); - goto err_free; - } - pos += written; - } - - ret = 0; -err_free: - free(buf); + ntfs_log_trace("pos %lld, count %lld\n", (long long)pos, + (long long)count); + + if (!na || pos < 0 || count < 0) { + errno = EINVAL; + goto err_out; + } + + buf = ntfs_calloc(NTFS_BUF_SIZE); + if (!buf) + goto err_out; + + rli = na->rl; + ofsi = 0; + vol = na->ni->vol; + while (pos < end) { + while (rli->length && (ofsi + (rli->length << + vol->cluster_size_bits) <= pos)) { + ofsi += (rli->length << vol->cluster_size_bits); + rli++; + } + size = min(end - pos, NTFS_BUF_SIZE); + written = ntfs_rl_pwrite(vol, rli, ofsi, pos, size, buf); + if (written <= 0) { + ntfs_log_perror("Failed to zero space"); + goto err_free; + } + pos += written; + } + + ret = 0; +err_free: + free(buf); err_out: - return ret; + return ret; } -static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs, - runlist_element **rl, VCN *update_from) { - s64 to_write; - s64 need; - ntfs_volume *vol = na->ni->vol; - int eo, ret = -1; - runlist *rlc; - LCN lcn_seek_from = -1; - VCN cur_vcn, from_vcn; +static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs, + runlist_element **rl, VCN *update_from) +{ + s64 to_write; + s64 need; + ntfs_volume *vol = na->ni->vol; + int eo, ret = -1; + runlist *rlc; + LCN lcn_seek_from = -1; + VCN cur_vcn, from_vcn; - to_write = min(count, ((*rl)->length << vol->cluster_size_bits) - *ofs); - - cur_vcn = (*rl)->vcn; - from_vcn = (*rl)->vcn + (*ofs >> vol->cluster_size_bits); - - ntfs_log_trace("count: %lld, cur_vcn: %lld, from: %lld, to: %lld, ofs: " - "%lld\n", (long long)count, (long long)cur_vcn, - (long long)from_vcn, (long long)to_write, (long long)*ofs); - - /* Map whole runlist to be able update mapping pairs later. */ - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - - /* Restore @*rl, it probably get lost during runlist mapping. */ - *rl = ntfs_attr_find_vcn(na, cur_vcn); - if (!*rl) { - ntfs_log_error("Failed to find run after mapping runlist. " - "Please report to %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - - /* Search backwards to find the best lcn to start seek from. */ - rlc = *rl; - while (rlc->vcn) { - rlc--; - if (rlc->lcn >= 0) { - /* - * avoid fragmenting a compressed file - * Windows does not do that, and that may - * not be desirable for files which can - * be updated - */ - if (na->data_flags & ATTR_COMPRESSION_MASK) - lcn_seek_from = rlc->lcn + rlc->length; - else - lcn_seek_from = rlc->lcn + (from_vcn - rlc->vcn); - break; - } - } - if (lcn_seek_from == -1) { - /* Backwards search failed, search forwards. */ - rlc = *rl; - while (rlc->length) { - rlc++; - if (rlc->lcn >= 0) { - lcn_seek_from = rlc->lcn - (rlc->vcn - from_vcn); - if (lcn_seek_from < -1) - lcn_seek_from = -1; - break; - } - } - } - - need = ((*ofs + to_write - 1) >> vol->cluster_size_bits) - + 1 + (*rl)->vcn - from_vcn; - if ((na->data_flags & ATTR_COMPRESSION_MASK) - && (need < na->compression_block_clusters)) { - /* - * for a compressed file, be sure to allocate the full hole. - * We may need space to decompress existing compressed data. - */ - rlc = ntfs_cluster_alloc(vol, (*rl)->vcn, (*rl)->length, - lcn_seek_from, DATA_ZONE); - } else - rlc = ntfs_cluster_alloc(vol, from_vcn, need, - lcn_seek_from, DATA_ZONE); - if (!rlc) - goto err_out; - - *rl = ntfs_runlists_merge(na->rl, rlc); - /* - * For a compressed attribute, we must be sure there is an - * available entry, so reserve it before it gets too late. - */ - if (*rl && (na->data_flags & ATTR_COMPRESSION_MASK)) - *rl = ntfs_rl_extend(*rl,1); - if (!*rl) { - eo = errno; - ntfs_log_perror("Failed to merge runlists"); - if (ntfs_cluster_free_from_rl(vol, rlc)) { - ntfs_log_perror("Failed to free hot clusters. " - "Please run chkdsk /f"); - } - errno = eo; - goto err_out; - } - na->rl = *rl; - if (*update_from == -1) - *update_from = from_vcn; - *rl = ntfs_attr_find_vcn(na, cur_vcn); - if (!*rl) { - /* - * It's definitely a BUG, if we failed to find @cur_vcn, because - * we missed it during instantiating of the hole. - */ - ntfs_log_error("Failed to find run after hole instantiation. " - "Please report to %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - /* If leaved part of the hole go to the next run. */ - if ((*rl)->lcn < 0) - (*rl)++; - /* Now LCN shoudn't be less than 0. */ - if ((*rl)->lcn < 0) { - ntfs_log_error("BUG! LCN is lesser than 0. " - "Please report to the %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - if (*ofs) { - /* Clear non-sparse region from @cur_vcn to @*ofs. */ - if (ntfs_attr_fill_zero(na, cur_vcn << vol->cluster_size_bits, - *ofs)) - goto err_out; - } - if ((*rl)->vcn < cur_vcn) { - /* - * Clusters that replaced hole are merged with - * previous run, so we need to update offset. - */ - *ofs += (cur_vcn - (*rl)->vcn) << vol->cluster_size_bits; - } - if ((*rl)->vcn > cur_vcn) { - /* - * We left part of the hole, so we need to update offset - */ - *ofs -= ((*rl)->vcn - cur_vcn) << vol->cluster_size_bits; - } - - ret = 0; + to_write = min(count, ((*rl)->length << vol->cluster_size_bits) - *ofs); + + cur_vcn = (*rl)->vcn; + from_vcn = (*rl)->vcn + (*ofs >> vol->cluster_size_bits); + + ntfs_log_trace("count: %lld, cur_vcn: %lld, from: %lld, to: %lld, ofs: " + "%lld\n", (long long)count, (long long)cur_vcn, + (long long)from_vcn, (long long)to_write, (long long)*ofs); + + /* Map whole runlist to be able update mapping pairs later. */ + if (ntfs_attr_map_whole_runlist(na)) + goto err_out; + + /* Restore @*rl, it probably get lost during runlist mapping. */ + *rl = ntfs_attr_find_vcn(na, cur_vcn); + if (!*rl) { + ntfs_log_error("Failed to find run after mapping runlist. " + "Please report to %s.\n", NTFS_DEV_LIST); + errno = EIO; + goto err_out; + } + + /* Search backwards to find the best lcn to start seek from. */ + rlc = *rl; + while (rlc->vcn) { + rlc--; + if (rlc->lcn >= 0) { + /* + * avoid fragmenting a compressed file + * Windows does not do that, and that may + * not be desirable for files which can + * be updated + */ + if (na->data_flags & ATTR_COMPRESSION_MASK) + lcn_seek_from = rlc->lcn + rlc->length; + else + lcn_seek_from = rlc->lcn + (from_vcn - rlc->vcn); + break; + } + } + if (lcn_seek_from == -1) { + /* Backwards search failed, search forwards. */ + rlc = *rl; + while (rlc->length) { + rlc++; + if (rlc->lcn >= 0) { + lcn_seek_from = rlc->lcn - (rlc->vcn - from_vcn); + if (lcn_seek_from < -1) + lcn_seek_from = -1; + break; + } + } + } + + need = ((*ofs + to_write - 1) >> vol->cluster_size_bits) + + 1 + (*rl)->vcn - from_vcn; + if ((na->data_flags & ATTR_COMPRESSION_MASK) + && (need < na->compression_block_clusters)) { + /* + * for a compressed file, be sure to allocate the full hole. + * We may need space to decompress existing compressed data. + */ + rlc = ntfs_cluster_alloc(vol, (*rl)->vcn, (*rl)->length, + lcn_seek_from, DATA_ZONE); + } else + rlc = ntfs_cluster_alloc(vol, from_vcn, need, + lcn_seek_from, DATA_ZONE); + if (!rlc) + goto err_out; + + *rl = ntfs_runlists_merge(na->rl, rlc); + /* + * For a compressed attribute, we must be sure there is an + * available entry, so reserve it before it gets too late. + */ + if (*rl && (na->data_flags & ATTR_COMPRESSION_MASK)) + *rl = ntfs_rl_extend(*rl,1); + if (!*rl) { + eo = errno; + ntfs_log_perror("Failed to merge runlists"); + if (ntfs_cluster_free_from_rl(vol, rlc)) { + ntfs_log_perror("Failed to free hot clusters. " + "Please run chkdsk /f"); + } + errno = eo; + goto err_out; + } + na->rl = *rl; + if (*update_from == -1) + *update_from = from_vcn; + *rl = ntfs_attr_find_vcn(na, cur_vcn); + if (!*rl) { + /* + * It's definitely a BUG, if we failed to find @cur_vcn, because + * we missed it during instantiating of the hole. + */ + ntfs_log_error("Failed to find run after hole instantiation. " + "Please report to %s.\n", NTFS_DEV_LIST); + errno = EIO; + goto err_out; + } + /* If leaved part of the hole go to the next run. */ + if ((*rl)->lcn < 0) + (*rl)++; + /* Now LCN shoudn't be less than 0. */ + if ((*rl)->lcn < 0) { + ntfs_log_error("BUG! LCN is lesser than 0. " + "Please report to the %s.\n", NTFS_DEV_LIST); + errno = EIO; + goto err_out; + } + if (*ofs) { + /* Clear non-sparse region from @cur_vcn to @*ofs. */ + if (ntfs_attr_fill_zero(na, cur_vcn << vol->cluster_size_bits, + *ofs)) + goto err_out; + } + if ((*rl)->vcn < cur_vcn) { + /* + * Clusters that replaced hole are merged with + * previous run, so we need to update offset. + */ + *ofs += (cur_vcn - (*rl)->vcn) << vol->cluster_size_bits; + } + if ((*rl)->vcn > cur_vcn) { + /* + * We left part of the hole, so we need to update offset + */ + *ofs -= ((*rl)->vcn - cur_vcn) << vol->cluster_size_bits; + } + + ret = 0; err_out: - return ret; + return ret; } static int stuff_hole(ntfs_attr *na, const s64 pos); @@ -1298,650 +1317,650 @@ static int stuff_hole(ntfs_attr *na, const s64 pos); * appropriately to the return code of ntfs_pwrite(), or to EINVAL in case of * invalid arguments. */ -s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, const void *b) { - s64 written, to_write, ofs, old_initialized_size, old_data_size; - s64 total = 0; - VCN update_from = -1; - ntfs_volume *vol; - s64 fullcount; - ntfs_attr_search_ctx *ctx = NULL; - runlist_element *rl; - s64 hole_end; - int eo; - int compressed_part; - struct { -unsigned int undo_initialized_size : - 1; -unsigned int undo_data_size : - 1; - } need_to = { 0, 0 }; - BOOL makingnonresident = FALSE; - BOOL wasnonresident = FALSE; - BOOL compressed; +s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, const void *b) +{ + s64 written, to_write, ofs, old_initialized_size, old_data_size; + s64 total = 0; + VCN update_from = -1; + ntfs_volume *vol; + s64 fullcount; + ntfs_attr_search_ctx *ctx = NULL; + runlist_element *rl; + s64 hole_end; + int eo; + int compressed_part; + struct { + unsigned int undo_initialized_size : 1; + unsigned int undo_data_size : 1; + } need_to = { 0, 0 }; + BOOL makingnonresident = FALSE; + BOOL wasnonresident = FALSE; + BOOL compressed; - ntfs_log_enter("Entering for inode %lld, attr 0x%x, pos 0x%llx, count " - "0x%llx.\n", (long long)na->ni->mft_no, na->type, - (long long)pos, (long long)count); + ntfs_log_enter("Entering for inode %lld, attr 0x%x, pos 0x%llx, count " + "0x%llx.\n", (long long)na->ni->mft_no, na->type, + (long long)pos, (long long)count); + + if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + goto errno_set; + } + vol = na->ni->vol; + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + /* + * Encrypted attributes are only supported in raw mode. We return + * access denied, which is what Windows NT4 does, too. + * Moreover a file cannot be both encrypted and compressed. + */ + if ((na->data_flags & ATTR_IS_ENCRYPTED) + && (compressed || !vol->efs_raw)) { + errno = EACCES; + goto errno_set; + } + /* + * Fill the gap, when writing beyond the end of a compressed + * file. This will make recursive calls + */ + if (compressed + && (na->type == AT_DATA) + && (pos > na->initialized_size) + && stuff_hole(na,pos)) + goto errno_set; + /* If this is a compressed attribute it needs special treatment. */ + wasnonresident = NAttrNonResident(na) != 0; + makingnonresident = wasnonresident /* yes : already changed */ + && !pos && (count == na->initialized_size); + /* + * Writing to compressed files is currently restricted + * to appending data. However we have to accept + * recursive write calls to make the attribute non resident. + * These are writing at position 0 up to initialized_size. + * Compression is also restricted to data streams. + * Only ATTR_IS_COMPRESSED compression mode is supported. + */ + if (compressed + && ((na->type != AT_DATA) + || ((na->data_flags & ATTR_COMPRESSION_MASK) + != ATTR_IS_COMPRESSED) + || ((pos != na->initialized_size) + && (pos || (count != na->initialized_size))))) { + // TODO: Implement writing compressed attributes! (AIA) + errno = EOPNOTSUPP; + goto errno_set; + } + + if (!count) + goto out; + /* for a compressed file, get prepared to reserve a full block */ + fullcount = count; + /* If the write reaches beyond the end, extend the attribute. */ + old_data_size = na->data_size; + if (pos + count > na->data_size) { + if (ntfs_attr_truncate(na, pos + count)) { + ntfs_log_perror("Failed to enlarge attribute"); + goto errno_set; + } + /* resizing may change the compression mode */ + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + need_to.undo_data_size = 1; + } + /* + * For compressed data, a single full block was allocated + * to deal with compression, possibly in a previous call. + * We are not able to process several blocks because + * some clusters are freed after compression and + * new allocations have to be done before proceeding, + * so truncate the requested count if needed (big buffers). + */ + if (compressed) { + fullcount = na->data_size - pos; + if (count > fullcount) + count = fullcount; + } + old_initialized_size = na->initialized_size; + /* If it is a resident attribute, write the data to the mft record. */ + if (!NAttrNonResident(na)) { + char *val; - if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto errno_set; - } - vol = na->ni->vol; - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - /* - * Encrypted attributes are only supported in raw mode. We return - * access denied, which is what Windows NT4 does, too. - * Moreover a file cannot be both encrypted and compressed. - */ - if ((na->data_flags & ATTR_IS_ENCRYPTED) - && (compressed || !vol->efs_raw)) { - errno = EACCES; - goto errno_set; - } - /* - * Fill the gap, when writing beyond the end of a compressed - * file. This will make recursive calls - */ - if (compressed - && (na->type == AT_DATA) - && (pos > na->initialized_size) - && stuff_hole(na,pos)) - goto errno_set; - /* If this is a compressed attribute it needs special treatment. */ - wasnonresident = NAttrNonResident(na) != 0; - makingnonresident = wasnonresident /* yes : already changed */ - && !pos && (count == na->initialized_size); - /* - * Writing to compressed files is currently restricted - * to appending data. However we have to accept - * recursive write calls to make the attribute non resident. - * These are writing at position 0 up to initialized_size. - * Compression is also restricted to data streams. - * Only ATTR_IS_COMPRESSED compression mode is supported. - */ - if (compressed - && ((na->type != AT_DATA) - || ((na->data_flags & ATTR_COMPRESSION_MASK) - != ATTR_IS_COMPRESSED) - || ((pos != na->initialized_size) - && (pos || (count != na->initialized_size))))) { - // TODO: Implement writing compressed attributes! (AIA) - errno = EOPNOTSUPP; - goto errno_set; - } + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + goto err_out; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx)) { + ntfs_log_perror("%s: lookup failed", __FUNCTION__); + goto err_out; + } + val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); + if (val < (char*)ctx->attr || val + + le32_to_cpu(ctx->attr->value_length) > + (char*)ctx->mrec + vol->mft_record_size) { + errno = EIO; + ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); + goto err_out; + } + memcpy(val + pos, b, count); + if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, + ctx->mrec)) { + /* + * NOTE: We are in a bad state at this moment. We have + * dirtied the mft record but we failed to commit it to + * disk. Since we have read the mft record ok before, + * it is unlikely to fail writing it, so is ok to just + * return error here... (AIA) + */ + ntfs_log_perror("%s: failed to write mft record", __FUNCTION__); + goto err_out; + } + ntfs_attr_put_search_ctx(ctx); + total = count; + goto out; + } + + /* Handle writes beyond initialized_size. */ + if (pos + count > na->initialized_size) { + if (ntfs_attr_map_whole_runlist(na)) + goto err_out; + /* + * For a compressed attribute, we must be sure there is an + * available entry, and, when reopening a compressed file, + * we may need to split a hole. So reserve the entries + * before it gets too late. + */ + if (compressed) { + na->rl = ntfs_rl_extend(na->rl,2); + if (!na->rl) + goto err_out; + } + /* Set initialized_size to @pos + @count. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + goto err_out; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx)) + goto err_out; + + /* If write starts beyond initialized_size, zero the gap. */ + if (pos > na->initialized_size) + if (ntfs_attr_fill_zero(na, na->initialized_size, + pos - na->initialized_size)) + goto err_out; + + ctx->attr->initialized_size = cpu_to_sle64(pos + count); + /* fix data_size for compressed files */ + if (compressed) + ctx->attr->data_size = ctx->attr->initialized_size; + if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, + ctx->mrec)) { + /* + * Undo the change in the in-memory copy and send it + * back for writing. + */ + ctx->attr->initialized_size = + cpu_to_sle64(old_initialized_size); + ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, + ctx->mrec); + goto err_out; + } + na->initialized_size = pos + count; + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; + /* + * NOTE: At this point the initialized_size in the mft record + * has been updated BUT there is random data on disk thus if + * we decide to abort, we MUST change the initialized_size + * again. + */ + need_to.undo_initialized_size = 1; + } + /* Find the runlist element containing the vcn. */ + rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); + if (!rl) { + /* + * If the vcn is not present it is an out of bounds write. + * However, we already extended the size of the attribute, + * so getting this here must be an error of some kind. + */ + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #3", __FUNCTION__); + } + goto err_out; + } + ofs = pos - (rl->vcn << vol->cluster_size_bits); + /* + * Determine if there is compressed data in the current + * compression block (when appending to an existing file). + * If so, decompression will be needed, and the full block + * must be allocated to be identified as uncompressed. + * This comes in two variants, depending on whether + * compression has saved at least one cluster. + * The compressed size can never be over full size by + * more than 485 (maximum for 15 compression blocks + * compressed to 4098 and the last 3640 bytes compressed + * to 3640 + 3640/8 = 4095, with 15*2 + 4095 - 3640 = 485) + * This is less than the smallest cluster, so the hole is + * is never beyond the cluster next to the position of + * the first uncompressed byte to write. + */ + compressed_part = 0; + if (compressed) { + if ((rl->lcn == (LCN)LCN_HOLE) + && wasnonresident) { + if (rl->length < na->compression_block_clusters) + compressed_part + = na->compression_block_clusters + - rl->length; + else { + compressed_part + = na->compression_block_clusters; + if (rl->length > na->compression_block_clusters) { + rl[2].lcn = rl[1].lcn; + rl[2].vcn = rl[1].vcn; + rl[2].length = rl[1].length; + rl[1].vcn -= compressed_part; + rl[1].lcn = LCN_HOLE; + rl[1].length = compressed_part; + rl[0].length -= compressed_part; + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } + } + /* normal hole filling will do later */ + } else + if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) { + s64 xofs; - if (!count) - goto out; - /* for a compressed file, get prepared to reserve a full block */ - fullcount = count; - /* If the write reaches beyond the end, extend the attribute. */ - old_data_size = na->data_size; - if (pos + count > na->data_size) { - if (ntfs_attr_truncate(na, pos + count)) { - ntfs_log_perror("Failed to enlarge attribute"); - goto errno_set; - } - /* resizing may change the compression mode */ - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - need_to.undo_data_size = 1; - } - /* - * For compressed data, a single full block was allocated - * to deal with compression, possibly in a previous call. - * We are not able to process several blocks because - * some clusters are freed after compression and - * new allocations have to be done before proceeding, - * so truncate the requested count if needed (big buffers). - */ - if (compressed) { - fullcount = na->data_size - pos; - if (count > fullcount) - count = fullcount; - } - old_initialized_size = na->initialized_size; - /* If it is a resident attribute, write the data to the mft record. */ - if (!NAttrNonResident(na)) { - char *val; + if (wasnonresident) + compressed_part = na->compression_block_clusters + - rl[1].length; + rl++; + xofs = 0; + if (ntfs_attr_fill_hole(na, + rl->length << vol->cluster_size_bits, + &xofs, &rl, &update_from)) + goto err_out; + /* the fist allocated cluster was not merged */ + if (!xofs) + rl--; + } + } + /* + * Scatter the data from the linear data buffer to the volume. Note, a + * partial final vcn is taken care of by the @count capping of write + * length. + */ + for (hole_end = 0; count; rl++, ofs = 0, hole_end = 0) { + if (rl->lcn == LCN_RL_NOT_MAPPED) { + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl) { + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN" + " #4", __FUNCTION__); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = pos + total - (rl->vcn << vol->cluster_size_bits); + } + if (!rl->length) { + errno = EIO; + ntfs_log_perror("%s: Zero run length", __FUNCTION__); + goto rl_err_out; + } + if (rl->lcn < (LCN)0) { + hole_end = rl->vcn + rl->length; - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto err_out; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx)) { - ntfs_log_perror("%s: lookup failed", __FUNCTION__); - goto err_out; - } - val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); - if (val < (char*)ctx->attr || val + - le32_to_cpu(ctx->attr->value_length) > - (char*)ctx->mrec + vol->mft_record_size) { - errno = EIO; - ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); - goto err_out; - } - memcpy(val + pos, b, count); - if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec)) { - /* - * NOTE: We are in a bad state at this moment. We have - * dirtied the mft record but we failed to commit it to - * disk. Since we have read the mft record ok before, - * it is unlikely to fail writing it, so is ok to just - * return error here... (AIA) - */ - ntfs_log_perror("%s: failed to write mft record", __FUNCTION__); - goto err_out; - } - ntfs_attr_put_search_ctx(ctx); - total = count; - goto out; - } + if (rl->lcn != (LCN)LCN_HOLE) { + errno = EIO; + ntfs_log_perror("%s: Unexpected LCN (%lld)", + __FUNCTION__, + (long long)rl->lcn); + goto rl_err_out; + } + if (ntfs_attr_fill_hole(na, fullcount, &ofs, &rl, + &update_from)) + goto err_out; + } + if (compressed) { + while (rl->length + && (ofs >= (rl->length << vol->cluster_size_bits))) { + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } + } - /* Handle writes beyond initialized_size. */ - if (pos + count > na->initialized_size) { - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - /* - * For a compressed attribute, we must be sure there is an - * available entry, and, when reopening a compressed file, - * we may need to split a hole. So reserve the entries - * before it gets too late. - */ - if (compressed) { - na->rl = ntfs_rl_extend(na->rl,2); - if (!na->rl) - goto err_out; - } - /* Set initialized_size to @pos + @count. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto err_out; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx)) - goto err_out; - - /* If write starts beyond initialized_size, zero the gap. */ - if (pos > na->initialized_size) - if (ntfs_attr_fill_zero(na, na->initialized_size, - pos - na->initialized_size)) - goto err_out; - - ctx->attr->initialized_size = cpu_to_sle64(pos + count); - /* fix data_size for compressed files */ - if (compressed) - ctx->attr->data_size = ctx->attr->initialized_size; - if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec)) { - /* - * Undo the change in the in-memory copy and send it - * back for writing. - */ - ctx->attr->initialized_size = - cpu_to_sle64(old_initialized_size); - ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec); - goto err_out; - } - na->initialized_size = pos + count; - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - /* - * NOTE: At this point the initialized_size in the mft record - * has been updated BUT there is random data on disk thus if - * we decide to abort, we MUST change the initialized_size - * again. - */ - need_to.undo_initialized_size = 1; - } - /* Find the runlist element containing the vcn. */ - rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds write. - * However, we already extended the size of the attribute, - * so getting this here must be an error of some kind. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #3", __FUNCTION__); - } - goto err_out; - } - ofs = pos - (rl->vcn << vol->cluster_size_bits); - /* - * Determine if there is compressed data in the current - * compression block (when appending to an existing file). - * If so, decompression will be needed, and the full block - * must be allocated to be identified as uncompressed. - * This comes in two variants, depending on whether - * compression has saved at least one cluster. - * The compressed size can never be over full size by - * more than 485 (maximum for 15 compression blocks - * compressed to 4098 and the last 3640 bytes compressed - * to 3640 + 3640/8 = 4095, with 15*2 + 4095 - 3640 = 485) - * This is less than the smallest cluster, so the hole is - * is never beyond the cluster next to the position of - * the first uncompressed byte to write. - */ - compressed_part = 0; - if (compressed) { - if ((rl->lcn == (LCN)LCN_HOLE) - && wasnonresident) { - if (rl->length < na->compression_block_clusters) - compressed_part - = na->compression_block_clusters - - rl->length; - else { - compressed_part - = na->compression_block_clusters; - if (rl->length > na->compression_block_clusters) { - rl[2].lcn = rl[1].lcn; - rl[2].vcn = rl[1].vcn; - rl[2].length = rl[1].length; - rl[1].vcn -= compressed_part; - rl[1].lcn = LCN_HOLE; - rl[1].length = compressed_part; - rl[0].length -= compressed_part; - ofs -= rl->length << vol->cluster_size_bits; - rl++; - } - } - /* normal hole filling will do later */ - } else - if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) { - s64 xofs; - - if (wasnonresident) - compressed_part = na->compression_block_clusters - - rl[1].length; - rl++; - xofs = 0; - if (ntfs_attr_fill_hole(na, - rl->length << vol->cluster_size_bits, - &xofs, &rl, &update_from)) - goto err_out; - /* the fist allocated cluster was not merged */ - if (!xofs) - rl--; - } - } - /* - * Scatter the data from the linear data buffer to the volume. Note, a - * partial final vcn is taken care of by the @count capping of write - * length. - */ - for (hole_end = 0; count; rl++, ofs = 0, hole_end = 0) { - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN" - " #4", __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = pos + total - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - hole_end = rl->vcn + rl->length; - - if (rl->lcn != (LCN)LCN_HOLE) { - errno = EIO; - ntfs_log_perror("%s: Unexpected LCN (%lld)", - __FUNCTION__, - (long long)rl->lcn); - goto rl_err_out; - } - if (ntfs_attr_fill_hole(na, fullcount, &ofs, &rl, - &update_from)) - goto err_out; - } - if (compressed) { - while (rl->length - && (ofs >= (rl->length << vol->cluster_size_bits))) { - ofs -= rl->length << vol->cluster_size_bits; - rl++; - } - } - - /* It is a real lcn, write it to the volume. */ - to_write = min(count, (rl->length << vol->cluster_size_bits) - ofs); + /* It is a real lcn, write it to the volume. */ + to_write = min(count, (rl->length << vol->cluster_size_bits) - ofs); retry: - ntfs_log_trace("Writing %lld bytes to vcn %lld, lcn %lld, ofs " - "%lld.\n", (long long)to_write, (long long)rl->vcn, - (long long)rl->lcn, (long long)ofs); - if (!NVolReadOnly(vol)) { - - s64 wpos = (rl->lcn << vol->cluster_size_bits) + ofs; - s64 wend = (rl->vcn << vol->cluster_size_bits) + ofs + to_write; - u32 bsize = vol->cluster_size; - /* Byte size needed to zero fill a cluster */ - s64 rounding = ((wend + bsize - 1) & ~(s64)(bsize - 1)) - wend; - /** - * Zero fill to cluster boundary if we're writing at the - * end of the attribute or into an ex-sparse cluster. - * This will cause the kernel not to seek and read disk - * blocks during write(2) to fill the end of the buffer - * which increases write speed by 2-10 fold typically. - * - * This is done even for compressed files, because - * data is generally first written uncompressed. - */ - if (rounding && ((wend == na->initialized_size) || - (wend < (hole_end << vol->cluster_size_bits)))) { - - char *cb; - - rounding += to_write; - - cb = ntfs_malloc(rounding); - if (!cb) - goto err_out; - - memcpy(cb, b, to_write); - memset(cb + to_write, 0, rounding - to_write); - - if (compressed) { - written = ntfs_compressed_pwrite(na, - rl, wpos, ofs, to_write, - rounding, b, compressed_part); - } else { - written = ntfs_pwrite(vol->dev, wpos, - rounding, cb); - if (written == rounding) - written = to_write; - } - - free(cb); - } else { - if (compressed) { - written = ntfs_compressed_pwrite(na, - rl, wpos, ofs, to_write, - to_write, b, compressed_part); - } else - written = ntfs_pwrite(vol->dev, wpos, - to_write, b); - } - } else - written = to_write; - /* If everything ok, update progress counters and continue. */ - if (written > 0) { - total += written; - count -= written; - fullcount -= written; - b = (const u8*)b + written; - } - if (written != to_write) { - /* Partial write cannot be dealt with, stop there */ - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (!written) - errno = EIO; - goto rl_err_out; - } - compressed_part = 0; - } + ntfs_log_trace("Writing %lld bytes to vcn %lld, lcn %lld, ofs " + "%lld.\n", (long long)to_write, (long long)rl->vcn, + (long long)rl->lcn, (long long)ofs); + if (!NVolReadOnly(vol)) { + + s64 wpos = (rl->lcn << vol->cluster_size_bits) + ofs; + s64 wend = (rl->vcn << vol->cluster_size_bits) + ofs + to_write; + u32 bsize = vol->cluster_size; + /* Byte size needed to zero fill a cluster */ + s64 rounding = ((wend + bsize - 1) & ~(s64)(bsize - 1)) - wend; + /** + * Zero fill to cluster boundary if we're writing at the + * end of the attribute or into an ex-sparse cluster. + * This will cause the kernel not to seek and read disk + * blocks during write(2) to fill the end of the buffer + * which increases write speed by 2-10 fold typically. + * + * This is done even for compressed files, because + * data is generally first written uncompressed. + */ + if (rounding && ((wend == na->initialized_size) || + (wend < (hole_end << vol->cluster_size_bits)))){ + + char *cb; + + rounding += to_write; + + cb = ntfs_malloc(rounding); + if (!cb) + goto err_out; + + memcpy(cb, b, to_write); + memset(cb + to_write, 0, rounding - to_write); + + if (compressed) { + written = ntfs_compressed_pwrite(na, + rl, wpos, ofs, to_write, + rounding, b, compressed_part); + } else { + written = ntfs_pwrite(vol->dev, wpos, + rounding, cb); + if (written == rounding) + written = to_write; + } + + free(cb); + } else { + if (compressed) { + written = ntfs_compressed_pwrite(na, + rl, wpos, ofs, to_write, + to_write, b, compressed_part); + } else + written = ntfs_pwrite(vol->dev, wpos, + to_write, b); + } + } else + written = to_write; + /* If everything ok, update progress counters and continue. */ + if (written > 0) { + total += written; + count -= written; + fullcount -= written; + b = (const u8*)b + written; + } + if (written != to_write) { + /* Partial write cannot be dealt with, stop there */ + /* If the syscall was interrupted, try again. */ + if (written == (s64)-1 && errno == EINTR) + goto retry; + if (!written) + errno = EIO; + goto rl_err_out; + } + compressed_part = 0; + } done: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if ((update_from != -1) - || (compressed && !makingnonresident)) - if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { - /* - * FIXME: trying to recover by goto rl_err_out; - * could cause driver hang by infinite looping. - */ - total = -1; - goto out; - } -out: - ntfs_log_leave("\n"); - return total; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if ((update_from != -1) + || (compressed && !makingnonresident)) + if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { + /* + * FIXME: trying to recover by goto rl_err_out; + * could cause driver hang by infinite looping. + */ + total = -1; + goto out; + } +out: + ntfs_log_leave("\n"); + return total; rl_err_out: - eo = errno; - if (total) { - if (need_to.undo_initialized_size) { - if (pos + total > na->initialized_size) - goto done; - /* - * TODO: Need to try to change initialized_size. If it - * succeeds goto done, otherwise goto err_out. (AIA) - */ - goto err_out; - } - goto done; - } - errno = eo; + eo = errno; + if (total) { + if (need_to.undo_initialized_size) { + if (pos + total > na->initialized_size) + goto done; + /* + * TODO: Need to try to change initialized_size. If it + * succeeds goto done, otherwise goto err_out. (AIA) + */ + goto err_out; + } + goto done; + } + errno = eo; err_out: - eo = errno; - if (need_to.undo_initialized_size) { - int err; + eo = errno; + if (need_to.undo_initialized_size) { + int err; - err = 0; - if (!ctx) { - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - err = 1; - } else - ntfs_attr_reinit_search_ctx(ctx); - if (!err) { - err = ntfs_attr_lookup(na->type, na->name, - na->name_len, 0, 0, NULL, 0, ctx); - if (!err) { - na->initialized_size = old_initialized_size; - ctx->attr->initialized_size = cpu_to_sle64( - old_initialized_size); - err = ntfs_mft_record_write(vol, - ctx->ntfs_ino->mft_no, - ctx->mrec); - } - } - if (err) { - /* - * FIXME: At this stage could try to recover by filling - * old_initialized_size -> new_initialized_size with - * data or at least zeroes. (AIA) - */ - ntfs_log_error("Eeek! Failed to recover from error. " - "Leaving metadata in inconsistent " - "state! Run chkdsk!\n"); - } - } - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if (update_from != -1) - ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); - /* Restore original data_size if needed. */ - if (need_to.undo_data_size && ntfs_attr_truncate(na, old_data_size)) - ntfs_log_perror("Failed to restore data_size"); - errno = eo; + err = 0; + if (!ctx) { + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + err = 1; + } else + ntfs_attr_reinit_search_ctx(ctx); + if (!err) { + err = ntfs_attr_lookup(na->type, na->name, + na->name_len, 0, 0, NULL, 0, ctx); + if (!err) { + na->initialized_size = old_initialized_size; + ctx->attr->initialized_size = cpu_to_sle64( + old_initialized_size); + err = ntfs_mft_record_write(vol, + ctx->ntfs_ino->mft_no, + ctx->mrec); + } + } + if (err) { + /* + * FIXME: At this stage could try to recover by filling + * old_initialized_size -> new_initialized_size with + * data or at least zeroes. (AIA) + */ + ntfs_log_error("Eeek! Failed to recover from error. " + "Leaving metadata in inconsistent " + "state! Run chkdsk!\n"); + } + } + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if (update_from != -1) + ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); + /* Restore original data_size if needed. */ + if (need_to.undo_data_size && ntfs_attr_truncate(na, old_data_size)) + ntfs_log_perror("Failed to restore data_size"); + errno = eo; errno_set: - total = -1; - goto out; + total = -1; + goto out; } -int ntfs_attr_pclose(ntfs_attr *na) { - s64 written, ofs; - BOOL ok = TRUE; - VCN update_from = -1; - ntfs_volume *vol; - ntfs_attr_search_ctx *ctx = NULL; - runlist_element *rl; - int eo; - s64 hole; - int compressed_part; - BOOL compressed; +int ntfs_attr_pclose(ntfs_attr *na) +{ + s64 written, ofs; + BOOL ok = TRUE; + VCN update_from = -1; + ntfs_volume *vol; + ntfs_attr_search_ctx *ctx = NULL; + runlist_element *rl; + int eo; + s64 hole; + int compressed_part; + BOOL compressed; - ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x.\n", - na->ni->mft_no, na->type); + ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x.\n", + na->ni->mft_no, na->type); + + if (!na || !na->ni || !na->ni->vol) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + goto errno_set; + } + vol = na->ni->vol; + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + /* + * Encrypted non-resident attributes are not supported. We return + * access denied, which is what Windows NT4 does, too. + */ + if (NAttrEncrypted(na) && NAttrNonResident(na)) { + errno = EACCES; + goto errno_set; + } + /* If this is not a compressed attribute get out */ + /* same if it is resident */ + if (!compressed || !NAttrNonResident(na)) + goto out; - if (!na || !na->ni || !na->ni->vol) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto errno_set; - } - vol = na->ni->vol; - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - /* - * Encrypted non-resident attributes are not supported. We return - * access denied, which is what Windows NT4 does, too. - */ - if (NAttrEncrypted(na) && NAttrNonResident(na)) { - errno = EACCES; - goto errno_set; - } - /* If this is not a compressed attribute get out */ - /* same if it is resident */ - if (!compressed || !NAttrNonResident(na)) - goto out; + /* + * For a compressed attribute, we must be sure there is an + * available entry, so reserve it before it gets too late. + */ + if (ntfs_attr_map_whole_runlist(na)) + goto err_out; + na->rl = ntfs_rl_extend(na->rl,1); + if (!na->rl) + goto err_out; + /* Find the runlist element containing the terminal vcn. */ + rl = ntfs_attr_find_vcn(na, (na->initialized_size - 1) >> vol->cluster_size_bits); + if (!rl) { + /* + * If the vcn is not present it is an out of bounds write. + * However, we have already written the last byte uncompressed, + * so getting this here must be an error of some kind. + */ + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN #5", __FUNCTION__); + } + goto err_out; + } + /* + * Scatter the data from the linear data buffer to the volume. Note, a + * partial final vcn is taken care of by the @count capping of write + * length. + */ + compressed_part = 0; + if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) + compressed_part + = na->compression_block_clusters - rl[1].length; + else + if (rl->lcn == (LCN)LCN_HOLE) { + if (rl->length < na->compression_block_clusters) + compressed_part + = na->compression_block_clusters + - rl->length; + else + compressed_part + = na->compression_block_clusters; + } + /* done, if the last block set was compressed */ + if (compressed_part) + goto out; - /* - * For a compressed attribute, we must be sure there is an - * available entry, so reserve it before it gets too late. - */ - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - na->rl = ntfs_rl_extend(na->rl,1); - if (!na->rl) - goto err_out; - /* Find the runlist element containing the terminal vcn. */ - rl = ntfs_attr_find_vcn(na, (na->initialized_size - 1) >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds write. - * However, we have already written the last byte uncompressed, - * so getting this here must be an error of some kind. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #5", __FUNCTION__); - } - goto err_out; - } - /* - * Scatter the data from the linear data buffer to the volume. Note, a - * partial final vcn is taken care of by the @count capping of write - * length. - */ - compressed_part = 0; - if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) - compressed_part - = na->compression_block_clusters - rl[1].length; - else - if (rl->lcn == (LCN)LCN_HOLE) { - if (rl->length < na->compression_block_clusters) - compressed_part - = na->compression_block_clusters - - rl->length; - else - compressed_part - = na->compression_block_clusters; - } - /* done, if the last block set was compressed */ - if (compressed_part) - goto out; + ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); - ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); - - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN" - " #6", __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - hole = rl->vcn + rl->length; - if (rl->lcn != (LCN)LCN_HOLE) { - errno = EIO; - ntfs_log_perror("%s: Unexpected LCN (%lld)", - __FUNCTION__, - (long long)rl->lcn); - goto rl_err_out; - } - - if (ntfs_attr_fill_hole(na, (s64)0, &ofs, &rl, &update_from)) - goto err_out; - } - while (rl->length - && (ofs >= (rl->length << vol->cluster_size_bits))) { - ofs -= rl->length << vol->cluster_size_bits; - rl++; - } + if (rl->lcn == LCN_RL_NOT_MAPPED) { + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl) { + if (errno == ENOENT) { + errno = EIO; + ntfs_log_perror("%s: Failed to find VCN" + " #6", __FUNCTION__); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); + } + if (!rl->length) { + errno = EIO; + ntfs_log_perror("%s: Zero run length", __FUNCTION__); + goto rl_err_out; + } + if (rl->lcn < (LCN)0) { + hole = rl->vcn + rl->length; + if (rl->lcn != (LCN)LCN_HOLE) { + errno = EIO; + ntfs_log_perror("%s: Unexpected LCN (%lld)", + __FUNCTION__, + (long long)rl->lcn); + goto rl_err_out; + } + + if (ntfs_attr_fill_hole(na, (s64)0, &ofs, &rl, &update_from)) + goto err_out; + } + while (rl->length + && (ofs >= (rl->length << vol->cluster_size_bits))) { + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } retry: - if (!NVolReadOnly(vol)) { - - written = ntfs_compressed_close(na, rl, ofs); - /* If everything ok, update progress counters and continue. */ - if (!written) - goto done; - } - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (!written) - errno = EIO; - goto rl_err_out; + if (!NVolReadOnly(vol)) { + + written = ntfs_compressed_close(na, rl, ofs); + /* If everything ok, update progress counters and continue. */ + if (!written) + goto done; + } + /* If the syscall was interrupted, try again. */ + if (written == (s64)-1 && errno == EINTR) + goto retry; + if (!written) + errno = EIO; + goto rl_err_out; done: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { - /* - * FIXME: trying to recover by goto rl_err_out; - * could cause driver hang by infinite looping. - */ - ok = FALSE; - goto out; - } -out: - ntfs_log_leave("\n"); - return (!ok); + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { + /* + * FIXME: trying to recover by goto rl_err_out; + * could cause driver hang by infinite looping. + */ + ok = FALSE; + goto out; + } +out: + ntfs_log_leave("\n"); + return (!ok); rl_err_out: - /* - * need not restore old sizes, only compressed_size - * can have changed. It has been set according to - * the current runlist while updating the mapping pairs, - * and must be kept consistent with the runlists. - */ + /* + * need not restore old sizes, only compressed_size + * can have changed. It has been set according to + * the current runlist while updating the mapping pairs, + * and must be kept consistent with the runlists. + */ err_out: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); - errno = eo; + eo = errno; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); + errno = eo; errno_set: - ok = FALSE; - goto out; + ok = FALSE; + goto out; } /** @@ -1974,27 +1993,28 @@ errno_set: * errors can be repaired. */ s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, const s64 bk_cnt, - const u32 bk_size, void *dst) { - s64 br; - u8 *end; + const u32 bk_size, void *dst) +{ + s64 br; + u8 *end; - ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)pos); - if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } - br = ntfs_attr_pread(na, pos, bk_cnt * bk_size, dst); - if (br <= 0) - return br; - br /= bk_size; - for (end = (u8*)dst + br * bk_size; (u8*)dst < end; dst = (u8*)dst + - bk_size) - ntfs_mst_post_read_fixup((NTFS_RECORD*)dst, bk_size); - /* Finally, return the number of blocks read. */ - return br; + ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)pos); + if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } + br = ntfs_attr_pread(na, pos, bk_cnt * bk_size, dst); + if (br <= 0) + return br; + br /= bk_size; + for (end = (u8*)dst + br * bk_size; (u8*)dst < end; dst = (u8*)dst + + bk_size) + ntfs_mst_post_read_fixup((NTFS_RECORD*)dst, bk_size); + /* Finally, return the number of blocks read. */ + return br; } /** @@ -2028,47 +2048,48 @@ s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, const s64 bk_cnt, * achieved. */ s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, - const u32 bk_size, void *src) { - s64 written, i; + const u32 bk_size, void *src) +{ + s64 written, i; - ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)pos); - if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { - errno = EINVAL; - return -1; - } - if (!bk_cnt) - return 0; - /* Prepare data for writing. */ - for (i = 0; i < bk_cnt; ++i) { - int err; + ntfs_log_trace("Entering for inode 0x%llx, attr type 0x%x, pos 0x%llx.\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)pos); + if (bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE) { + errno = EINVAL; + return -1; + } + if (!bk_cnt) + return 0; + /* Prepare data for writing. */ + for (i = 0; i < bk_cnt; ++i) { + int err; - err = ntfs_mst_pre_write_fixup((NTFS_RECORD*) - ((u8*)src + i * bk_size), bk_size); - if (err < 0) { - /* Abort write at this position. */ - ntfs_log_perror("%s #1", __FUNCTION__); - if (!i) - return err; - bk_cnt = i; - break; - } - } - /* Write the prepared data. */ - written = ntfs_attr_pwrite(na, pos, bk_cnt * bk_size, src); - if (written <= 0) { - ntfs_log_perror("%s: written=%lld", __FUNCTION__, - (long long)written); - } - /* Quickly deprotect the data again. */ - for (i = 0; i < bk_cnt; ++i) - ntfs_mst_post_write_fixup((NTFS_RECORD*)((u8*)src + i * - bk_size)); - if (written <= 0) - return written; - /* Finally, return the number of complete blocks written. */ - return written / bk_size; + err = ntfs_mst_pre_write_fixup((NTFS_RECORD*) + ((u8*)src + i * bk_size), bk_size); + if (err < 0) { + /* Abort write at this position. */ + ntfs_log_perror("%s #1", __FUNCTION__); + if (!i) + return err; + bk_cnt = i; + break; + } + } + /* Write the prepared data. */ + written = ntfs_attr_pwrite(na, pos, bk_cnt * bk_size, src); + if (written <= 0) { + ntfs_log_perror("%s: written=%lld", __FUNCTION__, + (long long)written); + } + /* Quickly deprotect the data again. */ + for (i = 0; i < bk_cnt; ++i) + ntfs_mst_post_write_fixup((NTFS_RECORD*)((u8*)src + i * + bk_size)); + if (written <= 0) + return written; + /* Finally, return the number of complete blocks written. */ + return written / bk_size; } /** @@ -2142,161 +2163,164 @@ s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, * non-resident as this most likely will result in a crash! */ static int ntfs_attr_find(const ATTR_TYPES type, const ntfschar *name, - const u32 name_len, const IGNORE_CASE_BOOL ic, - const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx) { - ATTR_RECORD *a; - ntfs_volume *vol; - ntfschar *upcase; - u32 upcase_len; + const u32 name_len, const IGNORE_CASE_BOOL ic, + const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx) +{ + ATTR_RECORD *a; + ntfs_volume *vol; + ntfschar *upcase; + u32 upcase_len; - ntfs_log_trace("attribute type 0x%x.\n", type); + ntfs_log_trace("attribute type 0x%x.\n", type); - if (ctx->ntfs_ino) { - vol = ctx->ntfs_ino->vol; - upcase = vol->upcase; - upcase_len = vol->upcase_len; - } else { - if (name && name != AT_UNNAMED) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } - vol = NULL; - upcase = NULL; - upcase_len = 0; - } - /* - * Iterate over attributes in mft record starting at @ctx->attr, or the - * attribute following that, if @ctx->is_first is TRUE. - */ - if (ctx->is_first) { - a = ctx->attr; - ctx->is_first = FALSE; - } else - a = (ATTR_RECORD*)((char*)ctx->attr + - le32_to_cpu(ctx->attr->length)); - for (;; a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length))) { - if (p2n(a) < p2n(ctx->mrec) || (char*)a > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_allocated)) - break; - ctx->attr = a; - if (((type != AT_UNUSED) && (le32_to_cpu(a->type) > - le32_to_cpu(type))) || - (a->type == AT_END)) { - errno = ENOENT; - return -1; - } - if (!a->length) - break; - /* If this is an enumeration return this attribute. */ - if (type == AT_UNUSED) - return 0; - if (a->type != type) - continue; - /* - * If @name is AT_UNNAMED we want an unnamed attribute. - * If @name is present, compare the two names. - * Otherwise, match any attribute. - */ - if (name == AT_UNNAMED) { - /* The search failed if the found attribute is named. */ - if (a->name_length) { - errno = ENOENT; - return -1; - } - } else if (name && !ntfs_names_are_equal(name, name_len, - (ntfschar*)((char*)a + le16_to_cpu(a->name_offset)), - a->name_length, ic, upcase, upcase_len)) { - register int rc; + if (ctx->ntfs_ino) { + vol = ctx->ntfs_ino->vol; + upcase = vol->upcase; + upcase_len = vol->upcase_len; + } else { + if (name && name != AT_UNNAMED) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } + vol = NULL; + upcase = NULL; + upcase_len = 0; + } + /* + * Iterate over attributes in mft record starting at @ctx->attr, or the + * attribute following that, if @ctx->is_first is TRUE. + */ + if (ctx->is_first) { + a = ctx->attr; + ctx->is_first = FALSE; + } else + a = (ATTR_RECORD*)((char*)ctx->attr + + le32_to_cpu(ctx->attr->length)); + for (;; a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length))) { + if (p2n(a) < p2n(ctx->mrec) || (char*)a > (char*)ctx->mrec + + le32_to_cpu(ctx->mrec->bytes_allocated)) + break; + ctx->attr = a; + if (((type != AT_UNUSED) && (le32_to_cpu(a->type) > + le32_to_cpu(type))) || + (a->type == AT_END)) { + errno = ENOENT; + return -1; + } + if (!a->length) + break; + /* If this is an enumeration return this attribute. */ + if (type == AT_UNUSED) + return 0; + if (a->type != type) + continue; + /* + * If @name is AT_UNNAMED we want an unnamed attribute. + * If @name is present, compare the two names. + * Otherwise, match any attribute. + */ + if (name == AT_UNNAMED) { + /* The search failed if the found attribute is named. */ + if (a->name_length) { + errno = ENOENT; + return -1; + } + } else if (name && !ntfs_names_are_equal(name, name_len, + (ntfschar*)((char*)a + le16_to_cpu(a->name_offset)), + a->name_length, ic, upcase, upcase_len)) { + register int rc; - rc = ntfs_names_collate(name, name_len, - (ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, 1, IGNORE_CASE, - upcase, upcase_len); - /* - * If @name collates before a->name, there is no - * matching attribute. - */ - if (rc == -1) { - errno = ENOENT; - return -1; - } - /* If the strings are not equal, continue search. */ - if (rc) - continue; - rc = ntfs_names_collate(name, name_len, - (ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, 1, CASE_SENSITIVE, - upcase, upcase_len); - if (rc == -1) { - errno = ENOENT; - return -1; - } - if (rc) - continue; - } - /* - * The names match or @name not present and attribute is - * unnamed. If no @val specified, we have found the attribute - * and are done. - */ - if (!val) - return 0; - /* @val is present; compare values. */ - else { - register int rc; + rc = ntfs_names_collate(name, name_len, + (ntfschar*)((char*)a + + le16_to_cpu(a->name_offset)), + a->name_length, 1, IGNORE_CASE, + upcase, upcase_len); + /* + * If @name collates before a->name, there is no + * matching attribute. + */ + if (rc == -1) { + errno = ENOENT; + return -1; + } + /* If the strings are not equal, continue search. */ + if (rc) + continue; + rc = ntfs_names_collate(name, name_len, + (ntfschar*)((char*)a + + le16_to_cpu(a->name_offset)), + a->name_length, 1, CASE_SENSITIVE, + upcase, upcase_len); + if (rc == -1) { + errno = ENOENT; + return -1; + } + if (rc) + continue; + } + /* + * The names match or @name not present and attribute is + * unnamed. If no @val specified, we have found the attribute + * and are done. + */ + if (!val) + return 0; + /* @val is present; compare values. */ + else { + register int rc; - rc = memcmp(val, (char*)a +le16_to_cpu(a->value_offset), - min(val_len, - le32_to_cpu(a->value_length))); - /* - * If @val collates before the current attribute's - * value, there is no matching attribute. - */ - if (!rc) { - register u32 avl; - avl = le32_to_cpu(a->value_length); - if (val_len == avl) - return 0; - if (val_len < avl) { - errno = ENOENT; - return -1; - } - } else if (rc < 0) { - errno = ENOENT; - return -1; - } - } - } - errno = EIO; - ntfs_log_perror("%s: Corrupt inode (%lld)", __FUNCTION__, - ctx->ntfs_ino ? (long long)ctx->ntfs_ino->mft_no : -1); - return -1; + rc = memcmp(val, (char*)a +le16_to_cpu(a->value_offset), + min(val_len, + le32_to_cpu(a->value_length))); + /* + * If @val collates before the current attribute's + * value, there is no matching attribute. + */ + if (!rc) { + register u32 avl; + avl = le32_to_cpu(a->value_length); + if (val_len == avl) + return 0; + if (val_len < avl) { + errno = ENOENT; + return -1; + } + } else if (rc < 0) { + errno = ENOENT; + return -1; + } + } + } + errno = EIO; + ntfs_log_perror("%s: Corrupt inode (%lld)", __FUNCTION__, + ctx->ntfs_ino ? (long long)ctx->ntfs_ino->mft_no : -1); + return -1; } -void ntfs_attr_name_free(char **name) { - if (*name) { - free(*name); - *name = NULL; - } +void ntfs_attr_name_free(char **name) +{ + if (*name) { + free(*name); + *name = NULL; + } } -char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) { - char *name = NULL; - int name_len; +char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) +{ + char *name = NULL; + int name_len; - name_len = ntfs_ucstombs(uname, uname_len, &name, 0); - if (name_len < 0) { - ntfs_log_perror("ntfs_ucstombs"); - return NULL; + name_len = ntfs_ucstombs(uname, uname_len, &name, 0); + if (name_len < 0) { + ntfs_log_perror("ntfs_ucstombs"); + return NULL; - } else if (name_len > 0) - return name; + } else if (name_len > 0) + return name; - ntfs_attr_name_free(&name); - return NULL; + ntfs_attr_name_free(&name); + return NULL; } /** @@ -2370,342 +2394,343 @@ char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) { * ENOMEM Not enough memory to allocate necessary buffers. */ static int ntfs_external_attr_find(ATTR_TYPES type, const ntfschar *name, - const u32 name_len, const IGNORE_CASE_BOOL ic, - const VCN lowest_vcn, const u8 *val, const u32 val_len, - ntfs_attr_search_ctx *ctx) { - ntfs_inode *base_ni, *ni; - ntfs_volume *vol; - ATTR_LIST_ENTRY *al_entry, *next_al_entry; - u8 *al_start, *al_end; - ATTR_RECORD *a; - ntfschar *al_name; - u32 al_name_len; - BOOL is_first_search = FALSE; + const u32 name_len, const IGNORE_CASE_BOOL ic, + const VCN lowest_vcn, const u8 *val, const u32 val_len, + ntfs_attr_search_ctx *ctx) +{ + ntfs_inode *base_ni, *ni; + ntfs_volume *vol; + ATTR_LIST_ENTRY *al_entry, *next_al_entry; + u8 *al_start, *al_end; + ATTR_RECORD *a; + ntfschar *al_name; + u32 al_name_len; + BOOL is_first_search = FALSE; - ni = ctx->ntfs_ino; - base_ni = ctx->base_ntfs_ino; - ntfs_log_trace("Entering for inode %lld, attribute type 0x%x.\n", - (unsigned long long)ni->mft_no, type); - if (!base_ni) { - /* First call happens with the base mft record. */ - base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino; - ctx->base_mrec = ctx->mrec; - } - if (ni == base_ni) - ctx->base_attr = ctx->attr; - if (type == AT_END) - goto not_found; - vol = base_ni->vol; - al_start = base_ni->attr_list; - al_end = al_start + base_ni->attr_list_size; - if (!ctx->al_entry) { - ctx->al_entry = (ATTR_LIST_ENTRY*)al_start; - is_first_search = TRUE; - } - /* - * Iterate over entries in attribute list starting at @ctx->al_entry, - * or the entry following that, if @ctx->is_first is TRUE. - */ - if (ctx->is_first) { - al_entry = ctx->al_entry; - ctx->is_first = FALSE; - /* - * If an enumeration and the first attribute is higher than - * the attribute list itself, need to return the attribute list - * attribute. - */ - if ((type == AT_UNUSED) && is_first_search && - le32_to_cpu(al_entry->type) > - le32_to_cpu(AT_ATTRIBUTE_LIST)) - goto find_attr_list_attr; - } else { - al_entry = (ATTR_LIST_ENTRY*)((char*)ctx->al_entry + - le16_to_cpu(ctx->al_entry->length)); - /* - * If this is an enumeration and the attribute list attribute - * is the next one in the enumeration sequence, just return the - * attribute list attribute from the base mft record as it is - * not listed in the attribute list itself. - */ - if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) < - le32_to_cpu(AT_ATTRIBUTE_LIST) && - le32_to_cpu(al_entry->type) > - le32_to_cpu(AT_ATTRIBUTE_LIST)) { - int rc; + ni = ctx->ntfs_ino; + base_ni = ctx->base_ntfs_ino; + ntfs_log_trace("Entering for inode %lld, attribute type 0x%x.\n", + (unsigned long long)ni->mft_no, type); + if (!base_ni) { + /* First call happens with the base mft record. */ + base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino; + ctx->base_mrec = ctx->mrec; + } + if (ni == base_ni) + ctx->base_attr = ctx->attr; + if (type == AT_END) + goto not_found; + vol = base_ni->vol; + al_start = base_ni->attr_list; + al_end = al_start + base_ni->attr_list_size; + if (!ctx->al_entry) { + ctx->al_entry = (ATTR_LIST_ENTRY*)al_start; + is_first_search = TRUE; + } + /* + * Iterate over entries in attribute list starting at @ctx->al_entry, + * or the entry following that, if @ctx->is_first is TRUE. + */ + if (ctx->is_first) { + al_entry = ctx->al_entry; + ctx->is_first = FALSE; + /* + * If an enumeration and the first attribute is higher than + * the attribute list itself, need to return the attribute list + * attribute. + */ + if ((type == AT_UNUSED) && is_first_search && + le32_to_cpu(al_entry->type) > + le32_to_cpu(AT_ATTRIBUTE_LIST)) + goto find_attr_list_attr; + } else { + al_entry = (ATTR_LIST_ENTRY*)((char*)ctx->al_entry + + le16_to_cpu(ctx->al_entry->length)); + /* + * If this is an enumeration and the attribute list attribute + * is the next one in the enumeration sequence, just return the + * attribute list attribute from the base mft record as it is + * not listed in the attribute list itself. + */ + if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) < + le32_to_cpu(AT_ATTRIBUTE_LIST) && + le32_to_cpu(al_entry->type) > + le32_to_cpu(AT_ATTRIBUTE_LIST)) { + int rc; find_attr_list_attr: - /* Check for bogus calls. */ - if (name || name_len || val || val_len || lowest_vcn) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } + /* Check for bogus calls. */ + if (name || name_len || val || val_len || lowest_vcn) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } - /* We want the base record. */ - ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - ctx->is_first = TRUE; - /* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); + /* We want the base record. */ + ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + ctx->is_first = TRUE; + /* Sanity checks are performed elsewhere. */ + ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); - /* Find the attribute list attribute. */ - rc = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0, - IGNORE_CASE, NULL, 0, ctx); + /* Find the attribute list attribute. */ + rc = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0, + IGNORE_CASE, NULL, 0, ctx); - /* - * Setup the search context so the correct - * attribute is returned next time round. - */ - ctx->al_entry = al_entry; - ctx->is_first = TRUE; + /* + * Setup the search context so the correct + * attribute is returned next time round. + */ + ctx->al_entry = al_entry; + ctx->is_first = TRUE; - /* Got it. Done. */ - if (!rc) - return 0; + /* Got it. Done. */ + if (!rc) + return 0; - /* Error! If other than not found return it. */ - if (errno != ENOENT) - return rc; + /* Error! If other than not found return it. */ + if (errno != ENOENT) + return rc; - /* Not found?!? Absurd! */ - errno = EIO; - ntfs_log_error("Attribute list wasn't found"); - return -1; - } - } - for (;; al_entry = next_al_entry) { - /* Out of bounds check. */ - if ((u8*)al_entry < base_ni->attr_list || - (u8*)al_entry > al_end) - break; /* Inode is corrupt. */ - ctx->al_entry = al_entry; - /* Catch the end of the attribute list. */ - if ((u8*)al_entry == al_end) - goto not_found; - if (!al_entry->length) - break; - if ((u8*)al_entry + 6 > al_end || (u8*)al_entry + - le16_to_cpu(al_entry->length) > al_end) - break; - next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry + - le16_to_cpu(al_entry->length)); - if (type != AT_UNUSED) { - if (le32_to_cpu(al_entry->type) > le32_to_cpu(type)) - goto not_found; - if (type != al_entry->type) - continue; - } - al_name_len = al_entry->name_length; - al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset); - /* - * If !@type we want the attribute represented by this - * attribute list entry. - */ - if (type == AT_UNUSED) - goto is_enumeration; - /* - * If @name is AT_UNNAMED we want an unnamed attribute. - * If @name is present, compare the two names. - * Otherwise, match any attribute. - */ - if (name == AT_UNNAMED) { - if (al_name_len) - goto not_found; - } else if (name && !ntfs_names_are_equal(al_name, al_name_len, - name, name_len, ic, vol->upcase, - vol->upcase_len)) { - register int rc; + /* Not found?!? Absurd! */ + errno = EIO; + ntfs_log_error("Attribute list wasn't found"); + return -1; + } + } + for (;; al_entry = next_al_entry) { + /* Out of bounds check. */ + if ((u8*)al_entry < base_ni->attr_list || + (u8*)al_entry > al_end) + break; /* Inode is corrupt. */ + ctx->al_entry = al_entry; + /* Catch the end of the attribute list. */ + if ((u8*)al_entry == al_end) + goto not_found; + if (!al_entry->length) + break; + if ((u8*)al_entry + 6 > al_end || (u8*)al_entry + + le16_to_cpu(al_entry->length) > al_end) + break; + next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry + + le16_to_cpu(al_entry->length)); + if (type != AT_UNUSED) { + if (le32_to_cpu(al_entry->type) > le32_to_cpu(type)) + goto not_found; + if (type != al_entry->type) + continue; + } + al_name_len = al_entry->name_length; + al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset); + /* + * If !@type we want the attribute represented by this + * attribute list entry. + */ + if (type == AT_UNUSED) + goto is_enumeration; + /* + * If @name is AT_UNNAMED we want an unnamed attribute. + * If @name is present, compare the two names. + * Otherwise, match any attribute. + */ + if (name == AT_UNNAMED) { + if (al_name_len) + goto not_found; + } else if (name && !ntfs_names_are_equal(al_name, al_name_len, + name, name_len, ic, vol->upcase, + vol->upcase_len)) { + register int rc; - rc = ntfs_names_collate(name, name_len, al_name, - al_name_len, 1, IGNORE_CASE, - vol->upcase, vol->upcase_len); - /* - * If @name collates before al_name, there is no - * matching attribute. - */ - if (rc == -1) - goto not_found; - /* If the strings are not equal, continue search. */ - if (rc) - continue; - /* - * FIXME: Reverse engineering showed 0, IGNORE_CASE but - * that is inconsistent with ntfs_attr_find(). The - * subsequent rc checks were also different. Perhaps I - * made a mistake in one of the two. Need to recheck - * which is correct or at least see what is going - * on... (AIA) - */ - rc = ntfs_names_collate(name, name_len, al_name, - al_name_len, 1, CASE_SENSITIVE, - vol->upcase, vol->upcase_len); - if (rc == -1) - goto not_found; - if (rc) - continue; - } - /* - * The names match or @name not present and attribute is - * unnamed. Now check @lowest_vcn. Continue search if the - * next attribute list entry still fits @lowest_vcn. Otherwise - * we have reached the right one or the search has failed. - */ - if (lowest_vcn && (u8*)next_al_entry >= al_start && - (u8*)next_al_entry + 6 < al_end && - (u8*)next_al_entry + le16_to_cpu( - next_al_entry->length) <= al_end && - sle64_to_cpu(next_al_entry->lowest_vcn) <= - lowest_vcn && - next_al_entry->type == al_entry->type && - next_al_entry->name_length == al_name_len && - ntfs_names_are_equal((ntfschar*)((char*) - next_al_entry + - next_al_entry->name_offset), - next_al_entry->name_length, - al_name, al_name_len, CASE_SENSITIVE, - vol->upcase, vol->upcase_len)) - continue; + rc = ntfs_names_collate(name, name_len, al_name, + al_name_len, 1, IGNORE_CASE, + vol->upcase, vol->upcase_len); + /* + * If @name collates before al_name, there is no + * matching attribute. + */ + if (rc == -1) + goto not_found; + /* If the strings are not equal, continue search. */ + if (rc) + continue; + /* + * FIXME: Reverse engineering showed 0, IGNORE_CASE but + * that is inconsistent with ntfs_attr_find(). The + * subsequent rc checks were also different. Perhaps I + * made a mistake in one of the two. Need to recheck + * which is correct or at least see what is going + * on... (AIA) + */ + rc = ntfs_names_collate(name, name_len, al_name, + al_name_len, 1, CASE_SENSITIVE, + vol->upcase, vol->upcase_len); + if (rc == -1) + goto not_found; + if (rc) + continue; + } + /* + * The names match or @name not present and attribute is + * unnamed. Now check @lowest_vcn. Continue search if the + * next attribute list entry still fits @lowest_vcn. Otherwise + * we have reached the right one or the search has failed. + */ + if (lowest_vcn && (u8*)next_al_entry >= al_start && + (u8*)next_al_entry + 6 < al_end && + (u8*)next_al_entry + le16_to_cpu( + next_al_entry->length) <= al_end && + sle64_to_cpu(next_al_entry->lowest_vcn) <= + lowest_vcn && + next_al_entry->type == al_entry->type && + next_al_entry->name_length == al_name_len && + ntfs_names_are_equal((ntfschar*)((char*) + next_al_entry + + next_al_entry->name_offset), + next_al_entry->name_length, + al_name, al_name_len, CASE_SENSITIVE, + vol->upcase, vol->upcase_len)) + continue; is_enumeration: - if (MREF_LE(al_entry->mft_reference) == ni->mft_no) { - if (MSEQNO_LE(al_entry->mft_reference) != - le16_to_cpu( - ni->mrec->sequence_number)) { - ntfs_log_error("Found stale mft reference in " - "attribute list!\n"); - break; - } - } else { /* Mft references do not match. */ - /* Do we want the base record back? */ - if (MREF_LE(al_entry->mft_reference) == - base_ni->mft_no) { - ni = ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - } else { - /* We want an extent record. */ - ni = ntfs_extent_inode_open(base_ni, - al_entry->mft_reference); - if (!ni) - break; - ctx->ntfs_ino = ni; - ctx->mrec = ni->mrec; - } - } - a = ctx->attr = (ATTR_RECORD*)((char*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - /* - * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the - * mft record containing the attribute represented by the - * current al_entry. - * - * We could call into ntfs_attr_find() to find the right - * attribute in this mft record but this would be less - * efficient and not quite accurate as ntfs_attr_find() ignores - * the attribute instance numbers for example which become - * important when one plays with attribute lists. Also, because - * a proper match has been found in the attribute list entry - * above, the comparison can now be optimized. So it is worth - * re-implementing a simplified ntfs_attr_find() here. - * - * Use a manual loop so we can still use break and continue - * with the same meanings as above. - */ + if (MREF_LE(al_entry->mft_reference) == ni->mft_no) { + if (MSEQNO_LE(al_entry->mft_reference) != + le16_to_cpu( + ni->mrec->sequence_number)) { + ntfs_log_error("Found stale mft reference in " + "attribute list!\n"); + break; + } + } else { /* Mft references do not match. */ + /* Do we want the base record back? */ + if (MREF_LE(al_entry->mft_reference) == + base_ni->mft_no) { + ni = ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + } else { + /* We want an extent record. */ + ni = ntfs_extent_inode_open(base_ni, + al_entry->mft_reference); + if (!ni) + break; + ctx->ntfs_ino = ni; + ctx->mrec = ni->mrec; + } + } + a = ctx->attr = (ATTR_RECORD*)((char*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); + /* + * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the + * mft record containing the attribute represented by the + * current al_entry. + * + * We could call into ntfs_attr_find() to find the right + * attribute in this mft record but this would be less + * efficient and not quite accurate as ntfs_attr_find() ignores + * the attribute instance numbers for example which become + * important when one plays with attribute lists. Also, because + * a proper match has been found in the attribute list entry + * above, the comparison can now be optimized. So it is worth + * re-implementing a simplified ntfs_attr_find() here. + * + * Use a manual loop so we can still use break and continue + * with the same meanings as above. + */ do_next_attr_loop: - if ((char*)a < (char*)ctx->mrec || (char*)a > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_allocated)) - break; - if (a->type == AT_END) - continue; - if (!a->length) - break; - if (al_entry->instance != a->instance) - goto do_next_attr; - /* - * If the type and/or the name are/is mismatched between the - * attribute list entry and the attribute record, there is - * corruption so we break and return error EIO. - */ - if (al_entry->type != a->type) - break; - if (!ntfs_names_are_equal((ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, al_name, - al_name_len, CASE_SENSITIVE, - vol->upcase, vol->upcase_len)) - break; - ctx->attr = a; - /* - * If no @val specified or @val specified and it matches, we - * have found it! Also, if !@type, it is an enumeration, so we - * want the current attribute. - */ - if ((type == AT_UNUSED) || !val || (!a->non_resident && - le32_to_cpu(a->value_length) == val_len && - !memcmp((char*)a + le16_to_cpu(a->value_offset), - val, val_len))) { - return 0; - } + if ((char*)a < (char*)ctx->mrec || (char*)a > (char*)ctx->mrec + + le32_to_cpu(ctx->mrec->bytes_allocated)) + break; + if (a->type == AT_END) + continue; + if (!a->length) + break; + if (al_entry->instance != a->instance) + goto do_next_attr; + /* + * If the type and/or the name are/is mismatched between the + * attribute list entry and the attribute record, there is + * corruption so we break and return error EIO. + */ + if (al_entry->type != a->type) + break; + if (!ntfs_names_are_equal((ntfschar*)((char*)a + + le16_to_cpu(a->name_offset)), + a->name_length, al_name, + al_name_len, CASE_SENSITIVE, + vol->upcase, vol->upcase_len)) + break; + ctx->attr = a; + /* + * If no @val specified or @val specified and it matches, we + * have found it! Also, if !@type, it is an enumeration, so we + * want the current attribute. + */ + if ((type == AT_UNUSED) || !val || (!a->non_resident && + le32_to_cpu(a->value_length) == val_len && + !memcmp((char*)a + le16_to_cpu(a->value_offset), + val, val_len))) { + return 0; + } do_next_attr: - /* Proceed to the next attribute in the current mft record. */ - a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length)); - goto do_next_attr_loop; - } - if (ni != base_ni) { - ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - ctx->attr = ctx->base_attr; - } - errno = EIO; - ntfs_log_perror("Inode is corrupt (%lld)", (long long)base_ni->mft_no); - return -1; + /* Proceed to the next attribute in the current mft record. */ + a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length)); + goto do_next_attr_loop; + } + if (ni != base_ni) { + ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + ctx->attr = ctx->base_attr; + } + errno = EIO; + ntfs_log_perror("Inode is corrupt (%lld)", (long long)base_ni->mft_no); + return -1; not_found: - /* - * If we were looking for AT_END or we were enumerating and reached the - * end, we reset the search context @ctx and use ntfs_attr_find() to - * seek to the end of the base mft record. - */ - if (type == AT_UNUSED || type == AT_END) { - ntfs_attr_reinit_search_ctx(ctx); - return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len, - ctx); - } - /* - * The attribute wasn't found. Before we return, we want to ensure - * @ctx->mrec and @ctx->attr indicate the position at which the - * attribute should be inserted in the base mft record. Since we also - * want to preserve @ctx->al_entry we cannot reinitialize the search - * context using ntfs_attr_reinit_search_ctx() as this would set - * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see - * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve - * @ctx->al_entry as the remaining fields (base_*) are identical to - * their non base_ counterparts and we cannot set @ctx->base_attr - * correctly yet as we do not know what @ctx->attr will be set to by - * the call to ntfs_attr_find() below. - */ - ctx->mrec = ctx->base_mrec; - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - ctx->is_first = TRUE; - ctx->ntfs_ino = ctx->base_ntfs_ino; - ctx->base_ntfs_ino = NULL; - ctx->base_mrec = NULL; - ctx->base_attr = NULL; - /* - * In case there are multiple matches in the base mft record, need to - * keep enumerating until we get an attribute not found response (or - * another error), otherwise we would keep returning the same attribute - * over and over again and all programs using us for enumeration would - * lock up in a tight loop. - */ - { - int ret; + /* + * If we were looking for AT_END or we were enumerating and reached the + * end, we reset the search context @ctx and use ntfs_attr_find() to + * seek to the end of the base mft record. + */ + if (type == AT_UNUSED || type == AT_END) { + ntfs_attr_reinit_search_ctx(ctx); + return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len, + ctx); + } + /* + * The attribute wasn't found. Before we return, we want to ensure + * @ctx->mrec and @ctx->attr indicate the position at which the + * attribute should be inserted in the base mft record. Since we also + * want to preserve @ctx->al_entry we cannot reinitialize the search + * context using ntfs_attr_reinit_search_ctx() as this would set + * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see + * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve + * @ctx->al_entry as the remaining fields (base_*) are identical to + * their non base_ counterparts and we cannot set @ctx->base_attr + * correctly yet as we do not know what @ctx->attr will be set to by + * the call to ntfs_attr_find() below. + */ + ctx->mrec = ctx->base_mrec; + ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); + ctx->is_first = TRUE; + ctx->ntfs_ino = ctx->base_ntfs_ino; + ctx->base_ntfs_ino = NULL; + ctx->base_mrec = NULL; + ctx->base_attr = NULL; + /* + * In case there are multiple matches in the base mft record, need to + * keep enumerating until we get an attribute not found response (or + * another error), otherwise we would keep returning the same attribute + * over and over again and all programs using us for enumeration would + * lock up in a tight loop. + */ + { + int ret; - do { - ret = ntfs_attr_find(type, name, name_len, ic, val, - val_len, ctx); - } while (!ret); - return ret; - } + do { + ret = ntfs_attr_find(type, name, name_len, ic, val, + val_len, ctx); + } while (!ret); + return ret; + } } /** @@ -2776,35 +2801,36 @@ not_found: * ENOMEM Not enough memory to allocate necessary buffers. */ int ntfs_attr_lookup(const ATTR_TYPES type, const ntfschar *name, - const u32 name_len, const IGNORE_CASE_BOOL ic, - const VCN lowest_vcn, const u8 *val, const u32 val_len, - ntfs_attr_search_ctx *ctx) { - ntfs_volume *vol; - ntfs_inode *base_ni; - int ret = -1; + const u32 name_len, const IGNORE_CASE_BOOL ic, + const VCN lowest_vcn, const u8 *val, const u32 val_len, + ntfs_attr_search_ctx *ctx) +{ + ntfs_volume *vol; + ntfs_inode *base_ni; + int ret = -1; - ntfs_log_enter("Entering for attribute type 0x%x\n", type); - - if (!ctx || !ctx->mrec || !ctx->attr || (name && name != AT_UNNAMED && - (!ctx->ntfs_ino || !(vol = ctx->ntfs_ino->vol) || - !vol->upcase || !vol->upcase_len))) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto out; - } - - if (ctx->base_ntfs_ino) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; - if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST) - ret = ntfs_attr_find(type, name, name_len, ic, val, val_len, ctx); - else - ret = ntfs_external_attr_find(type, name, name_len, ic, - lowest_vcn, val, val_len, ctx); + ntfs_log_enter("Entering for attribute type 0x%x\n", type); + + if (!ctx || !ctx->mrec || !ctx->attr || (name && name != AT_UNNAMED && + (!ctx->ntfs_ino || !(vol = ctx->ntfs_ino->vol) || + !vol->upcase || !vol->upcase_len))) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + goto out; + } + + if (ctx->base_ntfs_ino) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; + if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST) + ret = ntfs_attr_find(type, name, name_len, ic, val, val_len, ctx); + else + ret = ntfs_external_attr_find(type, name, name_len, ic, + lowest_vcn, val, val_len, ctx); out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } /** @@ -2824,16 +2850,17 @@ out: * ENOMEM Not enough memory to allocate necessary buffers. * ENOSPC No attribute was found after 'type', only AT_END. */ -int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) { - if (ntfs_attr_lookup(type, NULL, 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (errno != ENOENT) - return -1; - if (ctx->attr->type == AT_END) { - errno = ENOSPC; - return -1; - } - } - return 0; +int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) +{ + if (ntfs_attr_lookup(type, NULL, 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (errno != ENOENT) + return -1; + if (ctx->attr->type == AT_END) { + errno = ENOSPC; + return -1; + } + } + return 0; } /** @@ -2845,18 +2872,19 @@ int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) { * Initialize the attribute search context @ctx with @ni and @mrec. */ static void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx, - ntfs_inode *ni, MFT_RECORD *mrec) { - if (!mrec) - mrec = ni->mrec; - ctx->mrec = mrec; - /* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset)); - ctx->is_first = TRUE; - ctx->ntfs_ino = ni; - ctx->al_entry = NULL; - ctx->base_ntfs_ino = NULL; - ctx->base_mrec = NULL; - ctx->base_attr = NULL; + ntfs_inode *ni, MFT_RECORD *mrec) +{ + if (!mrec) + mrec = ni->mrec; + ctx->mrec = mrec; + /* Sanity checks are performed elsewhere. */ + ctx->attr = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset)); + ctx->is_first = TRUE; + ctx->ntfs_ino = ni; + ctx->al_entry = NULL; + ctx->base_ntfs_ino = NULL; + ctx->base_mrec = NULL; + ctx->base_attr = NULL; } /** @@ -2868,22 +2896,23 @@ static void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx, * This is used when a search for a new attribute is being started to reset * the search context to the beginning. */ -void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) { - if (!ctx->base_ntfs_ino) { - /* No attribute list. */ - ctx->is_first = TRUE; - /* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - /* - * This needs resetting due to ntfs_external_attr_find() which - * can leave it set despite having zeroed ctx->base_ntfs_ino. - */ - ctx->al_entry = NULL; - return; - } /* Attribute list. */ - ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec); - return; +void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) +{ + if (!ctx->base_ntfs_ino) { + /* No attribute list. */ + ctx->is_first = TRUE; + /* Sanity checks are performed elsewhere. */ + ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); + /* + * This needs resetting due to ntfs_external_attr_find() which + * can leave it set despite having zeroed ctx->base_ntfs_ino. + */ + ctx->al_entry = NULL; + return; + } /* Attribute list. */ + ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec); + return; } /** @@ -2900,18 +2929,19 @@ void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) { * be NULL and @mrec to be set. Do NOT do this unless you understand the * implications!!! For example it is no longer safe to call ntfs_attr_lookup(). */ -ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) { - ntfs_attr_search_ctx *ctx; +ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) +{ + ntfs_attr_search_ctx *ctx; - if (!ni && !mrec) { - errno = EINVAL; - ntfs_log_perror("NULL arguments"); - return NULL; - } - ctx = ntfs_malloc(sizeof(ntfs_attr_search_ctx)); - if (ctx) - ntfs_attr_init_search_ctx(ctx, ni, mrec); - return ctx; + if (!ni && !mrec) { + errno = EINVAL; + ntfs_log_perror("NULL arguments"); + return NULL; + } + ctx = ntfs_malloc(sizeof(ntfs_attr_search_ctx)); + if (ctx) + ntfs_attr_init_search_ctx(ctx, ni, mrec); + return ctx; } /** @@ -2920,9 +2950,10 @@ ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) * * Release the attribute search context @ctx. */ -void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) { - // NOTE: save errno if it could change and function stays void! - free(ctx); +void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) +{ + // NOTE: save errno if it could change and function stays void! + free(ctx); } /** @@ -2940,28 +2971,29 @@ void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) { * EINVAL - Invalid parameters (e.g. @vol is not valid). */ ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, - const ATTR_TYPES type) { - ATTR_DEF *ad; + const ATTR_TYPES type) +{ + ATTR_DEF *ad; - if (!vol || !vol->attrdef || !type) { - errno = EINVAL; - ntfs_log_perror("%s: type=%d", __FUNCTION__, type); - return NULL; - } - for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef < - vol->attrdef_len && ad->type; ++ad) { - /* We haven't found it yet, carry on searching. */ - if (le32_to_cpu(ad->type) < le32_to_cpu(type)) - continue; - /* We found the attribute; return it. */ - if (ad->type == type) - return ad; - /* We have gone too far already. No point in continuing. */ - break; - } - errno = ENOENT; - ntfs_log_perror("%s: type=%d", __FUNCTION__, type); - return NULL; + if (!vol || !vol->attrdef || !type) { + errno = EINVAL; + ntfs_log_perror("%s: type=%d", __FUNCTION__, type); + return NULL; + } + for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef < + vol->attrdef_len && ad->type; ++ad) { + /* We haven't found it yet, carry on searching. */ + if (le32_to_cpu(ad->type) < le32_to_cpu(type)) + continue; + /* We found the attribute; return it. */ + if (ad->type == type) + return ad; + /* We have gone too far already. No point in continuing. */ + break; + } + errno = ENOENT; + ntfs_log_perror("%s: type=%d", __FUNCTION__, type); + return NULL; } /** @@ -2980,43 +3012,44 @@ ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, * EINVAL - Invalid parameters (e.g. @size is < 0 or @vol is not valid). */ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type, - const s64 size) { - ATTR_DEF *ad; - s64 min_size, max_size; + const s64 size) +{ + ATTR_DEF *ad; + s64 min_size, max_size; - if (size < 0) { - errno = EINVAL; - ntfs_log_perror("%s: size=%lld", __FUNCTION__, - (long long)size); - return -1; - } + if (size < 0) { + errno = EINVAL; + ntfs_log_perror("%s: size=%lld", __FUNCTION__, + (long long)size); + return -1; + } - /* - * $ATTRIBUTE_LIST shouldn't be greater than 0x40000, otherwise - * Windows would crash. This is not listed in the AttrDef. - */ - if (type == AT_ATTRIBUTE_LIST && size > 0x40000) { - errno = ERANGE; - ntfs_log_perror("Too large attrlist (%lld)", (long long)size); - return -1; - } + /* + * $ATTRIBUTE_LIST shouldn't be greater than 0x40000, otherwise + * Windows would crash. This is not listed in the AttrDef. + */ + if (type == AT_ATTRIBUTE_LIST && size > 0x40000) { + errno = ERANGE; + ntfs_log_perror("Too large attrlist (%lld)", (long long)size); + return -1; + } - ad = ntfs_attr_find_in_attrdef(vol, type); - if (!ad) - return -1; - - min_size = sle64_to_cpu(ad->min_size); - max_size = sle64_to_cpu(ad->max_size); - - if ((min_size && (size < min_size)) || - ((max_size > 0) && (size > max_size))) { - errno = ERANGE; - ntfs_log_perror("Attr type %d size check failed (min,size,max=" - "%lld,%lld,%lld)", type, (long long)min_size, - (long long)size, (long long)max_size); - return -1; - } - return 0; + ad = ntfs_attr_find_in_attrdef(vol, type); + if (!ad) + return -1; + + min_size = sle64_to_cpu(ad->min_size); + max_size = sle64_to_cpu(ad->max_size); + + if ((min_size && (size < min_size)) || + ((max_size > 0) && (size > max_size))) { + errno = ERANGE; + ntfs_log_perror("Attr type %d size check failed (min,size,max=" + "%lld,%lld,%lld)", type, (long long)min_size, + (long long)size, (long long)max_size); + return -1; + } + return 0; } /** @@ -3034,20 +3067,21 @@ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type, * ENOENT - The attribute @type is not specified in $AttrDef. * EINVAL - Invalid parameters (e.g. @vol is not valid). */ -int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type) { - ATTR_DEF *ad; +int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type) +{ + ATTR_DEF *ad; - /* Find the attribute definition record in $AttrDef. */ - ad = ntfs_attr_find_in_attrdef(vol, type); - if (!ad) - return -1; - /* Check the flags and return the result. */ - if (ad->flags & ATTR_DEF_RESIDENT) { - errno = EPERM; - ntfs_log_trace("Attribute can't be non-resident\n"); - return -1; - } - return 0; + /* Find the attribute definition record in $AttrDef. */ + ad = ntfs_attr_find_in_attrdef(vol, type); + if (!ad) + return -1; + /* Check the flags and return the result. */ + if (ad->flags & ATTR_DEF_RESIDENT) { + errno = EPERM; + ntfs_log_trace("Attribute can't be non-resident\n"); + return -1; + } + return 0; } /** @@ -3072,17 +3106,18 @@ int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type) * check for this here as we don't know which inode's $Bitmap is being * asked about so the caller needs to special case this. */ -int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) { - if (!vol || !vol->attrdef || !type) { - errno = EINVAL; - return -1; - } - if (type != AT_INDEX_ALLOCATION) - return 0; - - ntfs_log_trace("Attribute can't be resident\n"); - errno = EPERM; - return -1; +int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) +{ + if (!vol || !vol->attrdef || !type) { + errno = EINVAL; + return -1; + } + if (type != AT_INDEX_ALLOCATION) + return 0; + + ntfs_log_trace("Attribute can't be resident\n"); + errno = EPERM; + return -1; } /** @@ -3099,43 +3134,44 @@ int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) { * caller has to make space before calling this. * EINVAL - Input parameters were faulty. */ -int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) { - u32 biu; +int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) +{ + u32 biu; - ntfs_log_trace("Entering for pos 0x%d, size %u.\n", - (int)(pos - (u8*)m), (unsigned) size); + ntfs_log_trace("Entering for pos 0x%d, size %u.\n", + (int)(pos - (u8*)m), (unsigned) size); - /* Make size 8-byte alignment. */ - size = (size + 7) & ~7; + /* Make size 8-byte alignment. */ + size = (size + 7) & ~7; - /* Rigorous consistency checks. */ - if (!m || !pos || pos < (u8*)m) { - errno = EINVAL; - ntfs_log_perror("%s: pos=%p m=%p", __FUNCTION__, pos, m); - return -1; - } - /* The -8 is for the attribute terminator. */ - if (pos - (u8*)m > (int)le32_to_cpu(m->bytes_in_use) - 8) { - errno = EINVAL; - return -1; - } - /* Nothing to do. */ - if (!size) - return 0; + /* Rigorous consistency checks. */ + if (!m || !pos || pos < (u8*)m) { + errno = EINVAL; + ntfs_log_perror("%s: pos=%p m=%p", __FUNCTION__, pos, m); + return -1; + } + /* The -8 is for the attribute terminator. */ + if (pos - (u8*)m > (int)le32_to_cpu(m->bytes_in_use) - 8) { + errno = EINVAL; + return -1; + } + /* Nothing to do. */ + if (!size) + return 0; - biu = le32_to_cpu(m->bytes_in_use); - /* Do we have enough space? */ - if (biu + size > le32_to_cpu(m->bytes_allocated) || - pos + size > (u8*)m + le32_to_cpu(m->bytes_allocated)) { - errno = ENOSPC; - ntfs_log_trace("No enough space in the MFT record\n"); - return -1; - } - /* Move everything after pos to pos + size. */ - memmove(pos + size, pos, biu - (pos - (u8*)m)); - /* Update mft record. */ - m->bytes_in_use = cpu_to_le32(biu + size); - return 0; + biu = le32_to_cpu(m->bytes_in_use); + /* Do we have enough space? */ + if (biu + size > le32_to_cpu(m->bytes_allocated) || + pos + size > (u8*)m + le32_to_cpu(m->bytes_allocated)) { + errno = ENOSPC; + ntfs_log_trace("No enough space in the MFT record\n"); + return -1; + } + /* Move everything after pos to pos + size. */ + memmove(pos + size, pos, biu - (pos - (u8*)m)); + /* Update mft record. */ + m->bytes_in_use = cpu_to_le32(biu + size); + return 0; } /** @@ -3156,113 +3192,114 @@ int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) { * EIO - I/O error occurred or damaged filesystem. */ int ntfs_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, u8 *val, u32 size, - ATTR_FLAGS data_flags) { - ntfs_attr_search_ctx *ctx; - u32 length; - ATTR_RECORD *a; - MFT_RECORD *m; - int err, offset; - ntfs_inode *base_ni; + ntfschar *name, u8 name_len, u8 *val, u32 size, + ATTR_FLAGS data_flags) +{ + ntfs_attr_search_ctx *ctx; + u32 length; + ATTR_RECORD *a; + MFT_RECORD *m; + int err, offset; + ntfs_inode *base_ni; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n", - (long long) ni->mft_no, (unsigned) type, (unsigned) data_flags); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n", + (long long) ni->mft_no, (unsigned) type, (unsigned) data_flags); - if (!ni || (!name && name_len)) { - errno = EINVAL; - return -1; - } + if (!ni || (!name && name_len)) { + errno = EINVAL; + return -1; + } - if (ntfs_attr_can_be_resident(ni->vol, type)) { - if (errno == EPERM) - ntfs_log_trace("Attribute can't be resident.\n"); - else - ntfs_log_trace("ntfs_attr_can_be_resident failed.\n"); - return -1; - } + if (ntfs_attr_can_be_resident(ni->vol, type)) { + if (errno == EPERM) + ntfs_log_trace("Attribute can't be resident.\n"); + else + ntfs_log_trace("ntfs_attr_can_be_resident failed.\n"); + return -1; + } - /* Locate place where record should be. */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; - /* - * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for - * attribute in @ni->mrec, not any extent inode in case if @ni is base - * file record. - */ - if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size, - ctx)) { - err = EEXIST; - ntfs_log_trace("Attribute already present.\n"); - goto put_err_out; - } - if (errno != ENOENT) { - err = EIO; - goto put_err_out; - } - a = ctx->attr; - m = ctx->mrec; + /* Locate place where record should be. */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return -1; + /* + * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for + * attribute in @ni->mrec, not any extent inode in case if @ni is base + * file record. + */ + if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size, + ctx)) { + err = EEXIST; + ntfs_log_trace("Attribute already present.\n"); + goto put_err_out; + } + if (errno != ENOENT) { + err = EIO; + goto put_err_out; + } + a = ctx->attr; + m = ctx->mrec; - /* Make room for attribute. */ - length = offsetof(ATTR_RECORD, resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + - ((size + 7) & ~7); - if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { - err = errno; - ntfs_log_trace("Failed to make room for attribute.\n"); - goto put_err_out; - } + /* Make room for attribute. */ + length = offsetof(ATTR_RECORD, resident_end) + + ((name_len * sizeof(ntfschar) + 7) & ~7) + + ((size + 7) & ~7); + if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { + err = errno; + ntfs_log_trace("Failed to make room for attribute.\n"); + goto put_err_out; + } - /* Setup record fields. */ - offset = ((u8*)a - (u8*)m); - a->type = type; - a->length = cpu_to_le32(length); - a->non_resident = 0; - a->name_length = name_len; - a->name_offset = (name_len - ? cpu_to_le16(offsetof(ATTR_RECORD, resident_end)) - : const_cpu_to_le16(0)); - a->flags = data_flags; - a->instance = m->next_attr_instance; - a->value_length = cpu_to_le32(size); - a->value_offset = cpu_to_le16(length - ((size + 7) & ~7)); - if (val) - memcpy((u8*)a + le16_to_cpu(a->value_offset), val, size); - else - memset((u8*)a + le16_to_cpu(a->value_offset), 0, size); - if (type == AT_FILE_NAME) - a->resident_flags = RESIDENT_ATTR_IS_INDEXED; - else - a->resident_flags = 0; - if (name_len) - memcpy((u8*)a + le16_to_cpu(a->name_offset), - name, sizeof(ntfschar) * name_len); - m->next_attr_instance = - cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); - if (ni->nr_extents == -1) - base_ni = ni->base_ni; - else - base_ni = ni; - if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { - if (ntfs_attrlist_entry_add(ni, a)) { - err = errno; - ntfs_attr_record_resize(m, a, 0); - ntfs_log_trace("Failed add attribute entry to " - "ATTRIBUTE_LIST.\n"); - goto put_err_out; - } - } - if (type == AT_DATA && name == AT_UNNAMED) { - ni->data_size = size; - ni->allocated_size = (size + 7) & ~7; - } - ntfs_inode_mark_dirty(ni); - ntfs_attr_put_search_ctx(ctx); - return offset; + /* Setup record fields. */ + offset = ((u8*)a - (u8*)m); + a->type = type; + a->length = cpu_to_le32(length); + a->non_resident = 0; + a->name_length = name_len; + a->name_offset = (name_len + ? cpu_to_le16(offsetof(ATTR_RECORD, resident_end)) + : const_cpu_to_le16(0)); + a->flags = data_flags; + a->instance = m->next_attr_instance; + a->value_length = cpu_to_le32(size); + a->value_offset = cpu_to_le16(length - ((size + 7) & ~7)); + if (val) + memcpy((u8*)a + le16_to_cpu(a->value_offset), val, size); + else + memset((u8*)a + le16_to_cpu(a->value_offset), 0, size); + if (type == AT_FILE_NAME) + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + else + a->resident_flags = 0; + if (name_len) + memcpy((u8*)a + le16_to_cpu(a->name_offset), + name, sizeof(ntfschar) * name_len); + m->next_attr_instance = + cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); + if (ni->nr_extents == -1) + base_ni = ni->base_ni; + else + base_ni = ni; + if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { + if (ntfs_attrlist_entry_add(ni, a)) { + err = errno; + ntfs_attr_record_resize(m, a, 0); + ntfs_log_trace("Failed add attribute entry to " + "ATTRIBUTE_LIST.\n"); + goto put_err_out; + } + } + if (type == AT_DATA && name == AT_UNNAMED) { + ni->data_size = size; + ni->allocated_size = (size + 7) & ~7; + } + ntfs_inode_mark_dirty(ni); + ntfs_attr_put_search_ctx(ctx); + return offset; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } /** @@ -3284,129 +3321,130 @@ put_err_out: * EIO - I/O error occurred or damaged filesystem. */ int ntfs_non_resident_attr_record_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size, - ATTR_FLAGS flags) { - ntfs_attr_search_ctx *ctx; - u32 length; - ATTR_RECORD *a; - MFT_RECORD *m; - ntfs_inode *base_ni; - int err, offset; + ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size, + ATTR_FLAGS flags) +{ + ntfs_attr_search_ctx *ctx; + u32 length; + ATTR_RECORD *a; + MFT_RECORD *m; + ntfs_inode *base_ni; + int err, offset; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, " - "dataruns_size %d, flags 0x%x.\n", - (long long) ni->mft_no, (unsigned) type, - (long long) lowest_vcn, dataruns_size, (unsigned) flags); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, " + "dataruns_size %d, flags 0x%x.\n", + (long long) ni->mft_no, (unsigned) type, + (long long) lowest_vcn, dataruns_size, (unsigned) flags); - if (!ni || dataruns_size <= 0 || (!name && name_len)) { - errno = EINVAL; - return -1; - } + if (!ni || dataruns_size <= 0 || (!name && name_len)) { + errno = EINVAL; + return -1; + } - if (ntfs_attr_can_be_non_resident(ni->vol, type)) { - if (errno == EPERM) - ntfs_log_perror("Attribute can't be non resident"); - else - ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); - return -1; - } + if (ntfs_attr_can_be_non_resident(ni->vol, type)) { + if (errno == EPERM) + ntfs_log_perror("Attribute can't be non resident"); + else + ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); + return -1; + } - /* Locate place where record should be. */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; - /* - * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for - * attribute in @ni->mrec, not any extent inode in case if @ni is base - * file record. - */ - if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, - ctx)) { - err = EEXIST; - ntfs_log_perror("Attribute 0x%x already present", type); - goto put_err_out; - } - if (errno != ENOENT) { - ntfs_log_perror("ntfs_attr_find failed"); - err = EIO; - goto put_err_out; - } - a = ctx->attr; - m = ctx->mrec; + /* Locate place where record should be. */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return -1; + /* + * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for + * attribute in @ni->mrec, not any extent inode in case if @ni is base + * file record. + */ + if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, + ctx)) { + err = EEXIST; + ntfs_log_perror("Attribute 0x%x already present", type); + goto put_err_out; + } + if (errno != ENOENT) { + ntfs_log_perror("ntfs_attr_find failed"); + err = EIO; + goto put_err_out; + } + a = ctx->attr; + m = ctx->mrec; - /* Make room for attribute. */ - dataruns_size = (dataruns_size + 7) & ~7; - length = offsetof(ATTR_RECORD, compressed_size) + ((sizeof(ntfschar) * - name_len + 7) & ~7) + dataruns_size + - ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? - sizeof(a->compressed_size) : 0); - if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { - err = errno; - ntfs_log_perror("Failed to make room for attribute"); - goto put_err_out; - } + /* Make room for attribute. */ + dataruns_size = (dataruns_size + 7) & ~7; + length = offsetof(ATTR_RECORD, compressed_size) + ((sizeof(ntfschar) * + name_len + 7) & ~7) + dataruns_size + + ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? + sizeof(a->compressed_size) : 0); + if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { + err = errno; + ntfs_log_perror("Failed to make room for attribute"); + goto put_err_out; + } - /* Setup record fields. */ - a->type = type; - a->length = cpu_to_le32(length); - a->non_resident = 1; - a->name_length = name_len; - a->name_offset = cpu_to_le16(offsetof(ATTR_RECORD, compressed_size) + - ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? - sizeof(a->compressed_size) : 0)); - a->flags = flags; - a->instance = m->next_attr_instance; - a->lowest_vcn = cpu_to_sle64(lowest_vcn); - a->mapping_pairs_offset = cpu_to_le16(length - dataruns_size); - a->compression_unit = (flags & ATTR_IS_COMPRESSED) - ? STANDARD_COMPRESSION_UNIT : 0; - /* If @lowest_vcn == 0, than setup empty attribute. */ - if (!lowest_vcn) { - a->highest_vcn = cpu_to_sle64(-1); - a->allocated_size = 0; - a->data_size = 0; - a->initialized_size = 0; - /* Set empty mapping pairs. */ - *((u8*)a + le16_to_cpu(a->mapping_pairs_offset)) = 0; - } - if (name_len) - memcpy((u8*)a + le16_to_cpu(a->name_offset), - name, sizeof(ntfschar) * name_len); - m->next_attr_instance = - cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); - if (ni->nr_extents == -1) - base_ni = ni->base_ni; - else - base_ni = ni; - if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { - if (ntfs_attrlist_entry_add(ni, a)) { - err = errno; - ntfs_log_perror("Failed add attr entry to attrlist"); - ntfs_attr_record_resize(m, a, 0); - goto put_err_out; - } - } - ntfs_inode_mark_dirty(ni); - /* - * Locate offset from start of the MFT record where new attribute is - * placed. We need relookup it, because record maybe moved during - * update of attribute list. - */ - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, - lowest_vcn, NULL, 0, ctx)) { - ntfs_log_perror("%s: attribute lookup failed", __FUNCTION__); - ntfs_attr_put_search_ctx(ctx); - return -1; + /* Setup record fields. */ + a->type = type; + a->length = cpu_to_le32(length); + a->non_resident = 1; + a->name_length = name_len; + a->name_offset = cpu_to_le16(offsetof(ATTR_RECORD, compressed_size) + + ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? + sizeof(a->compressed_size) : 0)); + a->flags = flags; + a->instance = m->next_attr_instance; + a->lowest_vcn = cpu_to_sle64(lowest_vcn); + a->mapping_pairs_offset = cpu_to_le16(length - dataruns_size); + a->compression_unit = (flags & ATTR_IS_COMPRESSED) + ? STANDARD_COMPRESSION_UNIT : 0; + /* If @lowest_vcn == 0, than setup empty attribute. */ + if (!lowest_vcn) { + a->highest_vcn = cpu_to_sle64(-1); + a->allocated_size = 0; + a->data_size = 0; + a->initialized_size = 0; + /* Set empty mapping pairs. */ + *((u8*)a + le16_to_cpu(a->mapping_pairs_offset)) = 0; + } + if (name_len) + memcpy((u8*)a + le16_to_cpu(a->name_offset), + name, sizeof(ntfschar) * name_len); + m->next_attr_instance = + cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); + if (ni->nr_extents == -1) + base_ni = ni->base_ni; + else + base_ni = ni; + if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { + if (ntfs_attrlist_entry_add(ni, a)) { + err = errno; + ntfs_log_perror("Failed add attr entry to attrlist"); + ntfs_attr_record_resize(m, a, 0); + goto put_err_out; + } + } + ntfs_inode_mark_dirty(ni); + /* + * Locate offset from start of the MFT record where new attribute is + * placed. We need relookup it, because record maybe moved during + * update of attribute list. + */ + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, + lowest_vcn, NULL, 0, ctx)) { + ntfs_log_perror("%s: attribute lookup failed", __FUNCTION__); + ntfs_attr_put_search_ctx(ctx); + return -1; - } - offset = (u8*)ctx->attr - (u8*)ctx->mrec; - ntfs_attr_put_search_ctx(ctx); - return offset; + } + offset = (u8*)ctx->attr - (u8*)ctx->mrec; + ntfs_attr_put_search_ctx(ctx); + return offset; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } /** @@ -3421,122 +3459,123 @@ put_err_out: * EINVAL - Invalid arguments passed to function. * EIO - I/O error occurred or damaged filesystem. */ -int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) { - ntfs_inode *base_ni, *ni; - ATTR_TYPES type; - int err; +int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) +{ + ntfs_inode *base_ni, *ni; + ATTR_TYPES type; + int err; - if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr) { - errno = EINVAL; - return -1; - } + if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr) { + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", - (long long) ctx->ntfs_ino->mft_no, - (unsigned) le32_to_cpu(ctx->attr->type)); - type = ctx->attr->type; - ni = ctx->ntfs_ino; - if (ctx->base_ntfs_ino) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", + (long long) ctx->ntfs_ino->mft_no, + (unsigned) le32_to_cpu(ctx->attr->type)); + type = ctx->attr->type; + ni = ctx->ntfs_ino; + if (ctx->base_ntfs_ino) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; - /* Remove attribute itself. */ - if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) { - ntfs_log_trace("Couldn't remove attribute record. Bug or damaged MFT " - "record.\n"); - if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) - if (ntfs_attrlist_entry_add(ni, ctx->attr)) - ntfs_log_trace("Rollback failed. Leaving inconstant " - "metadata.\n"); - err = EIO; - return -1; - } - ntfs_inode_mark_dirty(ni); + /* Remove attribute itself. */ + if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) { + ntfs_log_trace("Couldn't remove attribute record. Bug or damaged MFT " + "record.\n"); + if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) + if (ntfs_attrlist_entry_add(ni, ctx->attr)) + ntfs_log_trace("Rollback failed. Leaving inconstant " + "metadata.\n"); + err = EIO; + return -1; + } + ntfs_inode_mark_dirty(ni); - /* - * Remove record from $ATTRIBUTE_LIST if present and we don't want - * delete $ATTRIBUTE_LIST itself. - */ - if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) { - if (ntfs_attrlist_entry_rm(ctx)) { - ntfs_log_trace("Couldn't delete record from " - "$ATTRIBUTE_LIST.\n"); - return -1; - } - } + /* + * Remove record from $ATTRIBUTE_LIST if present and we don't want + * delete $ATTRIBUTE_LIST itself. + */ + if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) { + if (ntfs_attrlist_entry_rm(ctx)) { + ntfs_log_trace("Couldn't delete record from " + "$ATTRIBUTE_LIST.\n"); + return -1; + } + } - /* Post $ATTRIBUTE_LIST delete setup. */ - if (type == AT_ATTRIBUTE_LIST) { - if (NInoAttrList(base_ni) && base_ni->attr_list) - free(base_ni->attr_list); - base_ni->attr_list = NULL; - NInoClearAttrList(base_ni); - NInoAttrListClearDirty(base_ni); - } + /* Post $ATTRIBUTE_LIST delete setup. */ + if (type == AT_ATTRIBUTE_LIST) { + if (NInoAttrList(base_ni) && base_ni->attr_list) + free(base_ni->attr_list); + base_ni->attr_list = NULL; + NInoClearAttrList(base_ni); + NInoAttrListClearDirty(base_ni); + } - /* Free MFT record, if it doesn't contain attributes. */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) - - le16_to_cpu(ctx->mrec->attrs_offset) == 8) { - if (ntfs_mft_record_free(ni->vol, ni)) { - // FIXME: We need rollback here. - ntfs_log_trace("Couldn't free MFT record.\n"); - errno = EIO; - return -1; - } - /* Remove done if we freed base inode. */ - if (ni == base_ni) - return 0; - } + /* Free MFT record, if it doesn't contain attributes. */ + if (le32_to_cpu(ctx->mrec->bytes_in_use) - + le16_to_cpu(ctx->mrec->attrs_offset) == 8) { + if (ntfs_mft_record_free(ni->vol, ni)) { + // FIXME: We need rollback here. + ntfs_log_trace("Couldn't free MFT record.\n"); + errno = EIO; + return -1; + } + /* Remove done if we freed base inode. */ + if (ni == base_ni) + return 0; + } - if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni)) - return 0; + if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni)) + return 0; - /* Remove attribute list if we don't need it any more. */ - if (!ntfs_attrlist_need(base_ni)) { - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - /* - * FIXME: Should we succeed here? Definitely something - * goes wrong because NInoAttrList(base_ni) returned - * that we have got attribute list. - */ - ntfs_log_trace("Couldn't find attribute list. Succeed " - "anyway.\n"); - return 0; - } - /* Deallocate clusters. */ - if (ctx->attr->non_resident) { - runlist *al_rl; + /* Remove attribute list if we don't need it any more. */ + if (!ntfs_attrlist_need(base_ni)) { + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + /* + * FIXME: Should we succeed here? Definitely something + * goes wrong because NInoAttrList(base_ni) returned + * that we have got attribute list. + */ + ntfs_log_trace("Couldn't find attribute list. Succeed " + "anyway.\n"); + return 0; + } + /* Deallocate clusters. */ + if (ctx->attr->non_resident) { + runlist *al_rl; - al_rl = ntfs_mapping_pairs_decompress(base_ni->vol, - ctx->attr, NULL); - if (!al_rl) { - ntfs_log_trace("Couldn't decompress attribute list " - "runlist. Succeed anyway.\n"); - return 0; - } - if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl)) { - ntfs_log_trace("Leaking clusters! Run chkdsk. " - "Couldn't free clusters from " - "attribute list runlist.\n"); - } - free(al_rl); - } - /* Remove attribute record itself. */ - if (ntfs_attr_record_rm(ctx)) { - /* - * FIXME: Should we succeed here? BTW, chkdsk doesn't - * complain if it find MFT record with attribute list, - * but without extents. - */ - ntfs_log_trace("Couldn't remove attribute list. Succeed " - "anyway.\n"); - return 0; - } - } - return 0; + al_rl = ntfs_mapping_pairs_decompress(base_ni->vol, + ctx->attr, NULL); + if (!al_rl) { + ntfs_log_trace("Couldn't decompress attribute list " + "runlist. Succeed anyway.\n"); + return 0; + } + if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl)) { + ntfs_log_trace("Leaking clusters! Run chkdsk. " + "Couldn't free clusters from " + "attribute list runlist.\n"); + } + free(al_rl); + } + /* Remove attribute record itself. */ + if (ntfs_attr_record_rm(ctx)) { + /* + * FIXME: Should we succeed here? BTW, chkdsk doesn't + * complain if it find MFT record with attribute list, + * but without extents. + */ + ntfs_log_trace("Couldn't remove attribute list. Succeed " + "anyway.\n"); + return 0; + } + } + return 0; } /** @@ -3566,191 +3605,192 @@ int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) { * On success return 0. On error return -1 with errno set to the error code. */ int ntfs_attr_add(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, u8 *val, s64 size) { - u32 attr_rec_size; - int err, i, offset; - BOOL is_resident; - BOOL can_be_non_resident = FALSE; - ntfs_inode *attr_ni; - ntfs_attr *na; - ATTR_FLAGS data_flags; + ntfschar *name, u8 name_len, u8 *val, s64 size) +{ + u32 attr_rec_size; + int err, i, offset; + BOOL is_resident; + BOOL can_be_non_resident = FALSE; + ntfs_inode *attr_ni; + ntfs_attr *na; + ATTR_FLAGS data_flags; - if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST) { - errno = EINVAL; - ntfs_log_perror("%s: ni=%p size=%lld", __FUNCTION__, ni, - (long long)size); - return -1; - } + if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST) { + errno = EINVAL; + ntfs_log_perror("%s: ni=%p size=%lld", __FUNCTION__, ni, + (long long)size); + return -1; + } - ntfs_log_trace("Entering for inode %lld, attr %x, size %lld.\n", - (long long)ni->mft_no, type, (long long)size); + ntfs_log_trace("Entering for inode %lld, attr %x, size %lld.\n", + (long long)ni->mft_no, type, (long long)size); - if (ni->nr_extents == -1) - ni = ni->base_ni; + if (ni->nr_extents == -1) + ni = ni->base_ni; - /* Check the attribute type and the size. */ - if (ntfs_attr_size_bounds_check(ni->vol, type, size)) { - if (errno == ENOENT) - errno = EIO; - return -1; - } + /* Check the attribute type and the size. */ + if (ntfs_attr_size_bounds_check(ni->vol, type, size)) { + if (errno == ENOENT) + errno = EIO; + return -1; + } - /* Sanity checks for always resident attributes. */ - if (ntfs_attr_can_be_non_resident(ni->vol, type)) { - if (errno != EPERM) { - err = errno; - ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); - goto err_out; - } - /* @val is mandatory. */ - if (!val) { - errno = EINVAL; - ntfs_log_perror("val is mandatory for always resident " - "attributes"); - return -1; - } - if (size > ni->vol->mft_record_size) { - errno = ERANGE; - ntfs_log_perror("Attribute is too big"); - return -1; - } - } else - can_be_non_resident = TRUE; + /* Sanity checks for always resident attributes. */ + if (ntfs_attr_can_be_non_resident(ni->vol, type)) { + if (errno != EPERM) { + err = errno; + ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); + goto err_out; + } + /* @val is mandatory. */ + if (!val) { + errno = EINVAL; + ntfs_log_perror("val is mandatory for always resident " + "attributes"); + return -1; + } + if (size > ni->vol->mft_record_size) { + errno = ERANGE; + ntfs_log_perror("Attribute is too big"); + return -1; + } + } else + can_be_non_resident = TRUE; - /* - * Determine resident or not will be new attribute. We add 8 to size in - * non resident case for mapping pairs. - */ - if (!ntfs_attr_can_be_resident(ni->vol, type)) { - is_resident = TRUE; - } else { - if (errno != EPERM) { - err = errno; - ntfs_log_perror("ntfs_attr_can_be_resident failed"); - goto err_out; - } - is_resident = FALSE; - } - /* Calculate attribute record size. */ - if (is_resident) - attr_rec_size = offsetof(ATTR_RECORD, resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + - ((size + 7) & ~7); - else - attr_rec_size = offsetof(ATTR_RECORD, non_resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + 8; + /* + * Determine resident or not will be new attribute. We add 8 to size in + * non resident case for mapping pairs. + */ + if (!ntfs_attr_can_be_resident(ni->vol, type)) { + is_resident = TRUE; + } else { + if (errno != EPERM) { + err = errno; + ntfs_log_perror("ntfs_attr_can_be_resident failed"); + goto err_out; + } + is_resident = FALSE; + } + /* Calculate attribute record size. */ + if (is_resident) + attr_rec_size = offsetof(ATTR_RECORD, resident_end) + + ((name_len * sizeof(ntfschar) + 7) & ~7) + + ((size + 7) & ~7); + else + attr_rec_size = offsetof(ATTR_RECORD, non_resident_end) + + ((name_len * sizeof(ntfschar) + 7) & ~7) + 8; - /* - * If we have enough free space for the new attribute in the base MFT - * record, then add attribute to it. - */ - if (le32_to_cpu(ni->mrec->bytes_allocated) - - le32_to_cpu(ni->mrec->bytes_in_use) >= attr_rec_size) { - attr_ni = ni; - goto add_attr_record; - } + /* + * If we have enough free space for the new attribute in the base MFT + * record, then add attribute to it. + */ + if (le32_to_cpu(ni->mrec->bytes_allocated) - + le32_to_cpu(ni->mrec->bytes_in_use) >= attr_rec_size) { + attr_ni = ni; + goto add_attr_record; + } - /* Try to add to extent inodes. */ - if (ntfs_inode_attach_all_extents(ni)) { - err = errno; - ntfs_log_perror("Failed to attach all extents to inode"); - goto err_out; - } - for (i = 0; i < ni->nr_extents; i++) { - attr_ni = ni->extent_nis[i]; - if (le32_to_cpu(attr_ni->mrec->bytes_allocated) - - le32_to_cpu(attr_ni->mrec->bytes_in_use) >= - attr_rec_size) - goto add_attr_record; - } + /* Try to add to extent inodes. */ + if (ntfs_inode_attach_all_extents(ni)) { + err = errno; + ntfs_log_perror("Failed to attach all extents to inode"); + goto err_out; + } + for (i = 0; i < ni->nr_extents; i++) { + attr_ni = ni->extent_nis[i]; + if (le32_to_cpu(attr_ni->mrec->bytes_allocated) - + le32_to_cpu(attr_ni->mrec->bytes_in_use) >= + attr_rec_size) + goto add_attr_record; + } - /* There is no extent that contain enough space for new attribute. */ - if (!NInoAttrList(ni)) { - /* Add attribute list not present, add it and retry. */ - if (ntfs_inode_add_attrlist(ni)) { - err = errno; - ntfs_log_perror("Failed to add attribute list"); - goto err_out; - } - return ntfs_attr_add(ni, type, name, name_len, val, size); - } - /* Allocate new extent. */ - attr_ni = ntfs_mft_record_alloc(ni->vol, ni); - if (!attr_ni) { - err = errno; - ntfs_log_perror("Failed to allocate extent record"); - goto err_out; - } + /* There is no extent that contain enough space for new attribute. */ + if (!NInoAttrList(ni)) { + /* Add attribute list not present, add it and retry. */ + if (ntfs_inode_add_attrlist(ni)) { + err = errno; + ntfs_log_perror("Failed to add attribute list"); + goto err_out; + } + return ntfs_attr_add(ni, type, name, name_len, val, size); + } + /* Allocate new extent. */ + attr_ni = ntfs_mft_record_alloc(ni->vol, ni); + if (!attr_ni) { + err = errno; + ntfs_log_perror("Failed to allocate extent record"); + goto err_out; + } add_attr_record: - if ((ni->flags & FILE_ATTR_COMPRESSED) - && ((type == AT_DATA) - || ((type == AT_INDEX_ROOT) && (name == NTFS_INDEX_I30)))) - data_flags = ATTR_IS_COMPRESSED; - else - data_flags = const_cpu_to_le16(0); - if (is_resident) { - /* Add resident attribute. */ - offset = ntfs_resident_attr_record_add(attr_ni, type, name, - name_len, val, size, data_flags); - if (offset < 0) { - if (errno == ENOSPC && can_be_non_resident) - goto add_non_resident; - err = errno; - ntfs_log_perror("Failed to add resident attribute"); - goto free_err_out; - } - return 0; - } + if ((ni->flags & FILE_ATTR_COMPRESSED) + && ((type == AT_DATA) + || ((type == AT_INDEX_ROOT) && (name == NTFS_INDEX_I30)))) + data_flags = ATTR_IS_COMPRESSED; + else + data_flags = const_cpu_to_le16(0); + if (is_resident) { + /* Add resident attribute. */ + offset = ntfs_resident_attr_record_add(attr_ni, type, name, + name_len, val, size, data_flags); + if (offset < 0) { + if (errno == ENOSPC && can_be_non_resident) + goto add_non_resident; + err = errno; + ntfs_log_perror("Failed to add resident attribute"); + goto free_err_out; + } + return 0; + } add_non_resident: - /* Add non resident attribute. */ - offset = ntfs_non_resident_attr_record_add(attr_ni, type, name, - name_len, 0, 8, data_flags); - if (offset < 0) { - err = errno; - ntfs_log_perror("Failed to add non resident attribute"); - goto free_err_out; - } + /* Add non resident attribute. */ + offset = ntfs_non_resident_attr_record_add(attr_ni, type, name, + name_len, 0, 8, data_flags); + if (offset < 0) { + err = errno; + ntfs_log_perror("Failed to add non resident attribute"); + goto free_err_out; + } - /* If @size == 0, we are done. */ - if (!size) - return 0; + /* If @size == 0, we are done. */ + if (!size) + return 0; - /* Open new attribute and resize it. */ - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - err = errno; - ntfs_log_perror("Failed to open just added attribute"); - goto rm_attr_err_out; - } - /* Resize and set attribute value. */ - if (ntfs_attr_truncate(na, size) || - (val && (ntfs_attr_pwrite(na, 0, size, val) != size))) { - err = errno; - ntfs_log_perror("Failed to initialize just added attribute"); - if (ntfs_attr_rm(na)) - ntfs_log_perror("Failed to remove just added attribute"); - ntfs_attr_close(na); - goto err_out; - } - ntfs_attr_close(na); - return 0; + /* Open new attribute and resize it. */ + na = ntfs_attr_open(ni, type, name, name_len); + if (!na) { + err = errno; + ntfs_log_perror("Failed to open just added attribute"); + goto rm_attr_err_out; + } + /* Resize and set attribute value. */ + if (ntfs_attr_truncate(na, size) || + (val && (ntfs_attr_pwrite(na, 0, size, val) != size))) { + err = errno; + ntfs_log_perror("Failed to initialize just added attribute"); + if (ntfs_attr_rm(na)) + ntfs_log_perror("Failed to remove just added attribute"); + ntfs_attr_close(na); + goto err_out; + } + ntfs_attr_close(na); + return 0; rm_attr_err_out: - /* Remove just added attribute. */ - if (ntfs_attr_record_resize(attr_ni->mrec, - (ATTR_RECORD*)((u8*)attr_ni->mrec + offset), 0)) - ntfs_log_perror("Failed to remove just added attribute #2"); + /* Remove just added attribute. */ + if (ntfs_attr_record_resize(attr_ni->mrec, + (ATTR_RECORD*)((u8*)attr_ni->mrec + offset), 0)) + ntfs_log_perror("Failed to remove just added attribute #2"); free_err_out: - /* Free MFT record, if it doesn't contain attributes. */ - if (le32_to_cpu(attr_ni->mrec->bytes_in_use) - - le16_to_cpu(attr_ni->mrec->attrs_offset) == 8) - if (ntfs_mft_record_free(attr_ni->vol, attr_ni)) - ntfs_log_perror("Failed to free MFT record"); + /* Free MFT record, if it doesn't contain attributes. */ + if (le32_to_cpu(attr_ni->mrec->bytes_in_use) - + le16_to_cpu(attr_ni->mrec->attrs_offset) == 8) + if (ntfs_mft_record_free(attr_ni->vol, attr_ni)) + ntfs_log_perror("Failed to free MFT record"); err_out: - errno = err; - return -1; + errno = err; + return -1; } /* @@ -3758,25 +3798,26 @@ err_out: */ int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask) { - ntfs_attr_search_ctx *ctx; - int res; + ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask) +{ + ntfs_attr_search_ctx *ctx; + int res; - res = -1; - /* Search for designated attribute */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (ctx) { - if (!ntfs_attr_lookup(type, name, name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - /* do the requested change (all small endian le16) */ - ctx->attr->flags = (ctx->attr->flags & ~mask) - | (flags & mask); - NInoSetDirty(ni); - res = 0; - } - ntfs_attr_put_search_ctx(ctx); - } - return (res); + res = -1; + /* Search for designated attribute */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (ctx) { + if (!ntfs_attr_lookup(type, name, name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + /* do the requested change (all small endian le16) */ + ctx->attr->flags = (ctx->attr->flags & ~mask) + | (flags & mask); + NInoSetDirty(ni); + res = 0; + } + ntfs_attr_put_search_ctx(ctx); + } + return (res); } @@ -3789,51 +3830,52 @@ int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_attr_rm(ntfs_attr *na) { - ntfs_attr_search_ctx *ctx; - int ret = 0; +int ntfs_attr_rm(ntfs_attr *na) +{ + ntfs_attr_search_ctx *ctx; + int ret = 0; - if (!na) { - ntfs_log_trace("Invalid arguments passed.\n"); - errno = EINVAL; - return -1; - } + if (!na) { + ntfs_log_trace("Invalid arguments passed.\n"); + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", - (long long) na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", + (long long) na->ni->mft_no, na->type); - /* Free cluster allocation. */ - if (NAttrNonResident(na)) { - if (ntfs_attr_map_whole_runlist(na)) - return -1; - if (ntfs_cluster_free(na->ni->vol, na, 0, -1) < 0) { - ntfs_log_trace("Failed to free cluster allocation. Leaving " - "inconstant metadata.\n"); - ret = -1; - } - } + /* Free cluster allocation. */ + if (NAttrNonResident(na)) { + if (ntfs_attr_map_whole_runlist(na)) + return -1; + if (ntfs_cluster_free(na->ni->vol, na, 0, -1) < 0) { + ntfs_log_trace("Failed to free cluster allocation. Leaving " + "inconstant metadata.\n"); + ret = -1; + } + } - /* Search for attribute extents and remove them all. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (ntfs_attr_record_rm(ctx)) { - ntfs_log_trace("Failed to remove attribute extent. Leaving " - "inconstant metadata.\n"); - ret = -1; - } - ntfs_attr_reinit_search_ctx(ctx); - } - ntfs_attr_put_search_ctx(ctx); - if (errno != ENOENT) { - ntfs_log_trace("Attribute lookup failed. Probably leaving inconstant " - "metadata.\n"); - ret = -1; - } + /* Search for attribute extents and remove them all. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; + while (!ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (ntfs_attr_record_rm(ctx)) { + ntfs_log_trace("Failed to remove attribute extent. Leaving " + "inconstant metadata.\n"); + ret = -1; + } + ntfs_attr_reinit_search_ctx(ctx); + } + ntfs_attr_put_search_ctx(ctx); + if (errno != ENOENT) { + ntfs_log_trace("Attribute lookup failed. Probably leaving inconstant " + "metadata.\n"); + ret = -1; + } - return ret; + return ret; } /** @@ -3853,53 +3895,54 @@ int ntfs_attr_rm(ntfs_attr *na) { * Warning: If you make a record smaller without having copied all the data you * are interested in the data may be overwritten! */ -int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) { - u32 old_size, alloc_size, attr_size; +int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) +{ + u32 old_size, alloc_size, attr_size; + + old_size = le32_to_cpu(m->bytes_in_use); + alloc_size = le32_to_cpu(m->bytes_allocated); + attr_size = le32_to_cpu(a->length); + + ntfs_log_trace("Sizes: old=%u alloc=%u attr=%u new=%u\n", + (unsigned)old_size, (unsigned)alloc_size, + (unsigned)attr_size, (unsigned)new_size); - old_size = le32_to_cpu(m->bytes_in_use); - alloc_size = le32_to_cpu(m->bytes_allocated); - attr_size = le32_to_cpu(a->length); + /* Align to 8 bytes, just in case the caller hasn't. */ + new_size = (new_size + 7) & ~7; + + /* If the actual attribute length has changed, move things around. */ + if (new_size != attr_size) { + + u32 new_muse = old_size - attr_size + new_size; + + /* Not enough space in this mft record. */ + if (new_muse > alloc_size) { + errno = ENOSPC; + ntfs_log_trace("Not enough space in the MFT record " + "(%u > %u)\n", new_muse, alloc_size); + return -1; + } - ntfs_log_trace("Sizes: old=%u alloc=%u attr=%u new=%u\n", - (unsigned)old_size, (unsigned)alloc_size, - (unsigned)attr_size, (unsigned)new_size); - - /* Align to 8 bytes, just in case the caller hasn't. */ - new_size = (new_size + 7) & ~7; - - /* If the actual attribute length has changed, move things around. */ - if (new_size != attr_size) { - - u32 new_muse = old_size - attr_size + new_size; - - /* Not enough space in this mft record. */ - if (new_muse > alloc_size) { - errno = ENOSPC; - ntfs_log_trace("Not enough space in the MFT record " - "(%u > %u)\n", new_muse, alloc_size); - return -1; - } - - if (a->type == AT_INDEX_ROOT && new_size > attr_size && - new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) { - errno = ENOSPC; - ntfs_log_trace("Too big INDEX_ROOT (%u > %u)\n", - new_muse, alloc_size); - return STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; - } - - /* Move attributes following @a to their new location. */ - memmove((u8 *)a + new_size, (u8 *)a + attr_size, - old_size - ((u8 *)a - (u8 *)m) - attr_size); - - /* Adjust @m to reflect the change in used space. */ - m->bytes_in_use = cpu_to_le32(new_muse); - - /* Adjust @a to reflect the new size. */ - if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length)) - a->length = cpu_to_le32(new_size); - } - return 0; + if (a->type == AT_INDEX_ROOT && new_size > attr_size && + new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) { + errno = ENOSPC; + ntfs_log_trace("Too big INDEX_ROOT (%u > %u)\n", + new_muse, alloc_size); + return STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; + } + + /* Move attributes following @a to their new location. */ + memmove((u8 *)a + new_size, (u8 *)a + attr_size, + old_size - ((u8 *)a - (u8 *)m) - attr_size); + + /* Adjust @m to reflect the change in used space. */ + m->bytes_in_use = cpu_to_le32(new_muse); + + /* Adjust @a to reflect the new size. */ + if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length)) + a->length = cpu_to_le32(new_size); + } + return 0; } /** @@ -3917,26 +3960,27 @@ int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) { * Note that on error no modifications have been performed whatsoever. */ int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, - const u32 new_size) { - int ret; + const u32 new_size) +{ + int ret; + + ntfs_log_trace("Entering for new size %u.\n", (unsigned)new_size); - ntfs_log_trace("Entering for new size %u.\n", (unsigned)new_size); - - /* Resize the resident part of the attribute record. */ - if ((ret = ntfs_attr_record_resize(m, a, (le16_to_cpu(a->value_offset) + - new_size + 7) & ~7)) < 0) - return ret; - /* - * If we made the attribute value bigger, clear the area between the - * old size and @new_size. - */ - if (new_size > le32_to_cpu(a->value_length)) - memset((u8*)a + le16_to_cpu(a->value_offset) + - le32_to_cpu(a->value_length), 0, new_size - - le32_to_cpu(a->value_length)); - /* Finally update the length of the attribute value. */ - a->value_length = cpu_to_le32(new_size); - return 0; + /* Resize the resident part of the attribute record. */ + if ((ret = ntfs_attr_record_resize(m, a, (le16_to_cpu(a->value_offset) + + new_size + 7) & ~7)) < 0) + return ret; + /* + * If we made the attribute value bigger, clear the area between the + * old size and @new_size. + */ + if (new_size > le32_to_cpu(a->value_length)) + memset((u8*)a + le16_to_cpu(a->value_offset) + + le32_to_cpu(a->value_length), 0, new_size - + le32_to_cpu(a->value_length)); + /* Finally update the length of the attribute value. */ + a->value_length = cpu_to_le32(new_size); + return 0; } /** @@ -3949,85 +3993,86 @@ int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni) { - ntfs_attr_search_ctx *nctx; - ATTR_RECORD *a; - int err; +int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni) +{ + ntfs_attr_search_ctx *nctx; + ATTR_RECORD *a; + int err; - if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) { - ntfs_log_trace("Invalid arguments passed.\n"); - errno = EINVAL; - return -1; - } + if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) { + ntfs_log_trace("Invalid arguments passed.\n"); + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no " - "0x%llx, ni->mft_no 0x%llx.\n", - (unsigned) le32_to_cpu(ctx->attr->type), - (long long) ctx->ntfs_ino->mft_no, - (long long) ni->mft_no); + ntfs_log_trace("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no " + "0x%llx, ni->mft_no 0x%llx.\n", + (unsigned) le32_to_cpu(ctx->attr->type), + (long long) ctx->ntfs_ino->mft_no, + (long long) ni->mft_no); - if (ctx->ntfs_ino == ni) - return 0; + if (ctx->ntfs_ino == ni) + return 0; - if (!ctx->al_entry) { - ntfs_log_trace("Inode should contain attribute list to use this " - "function.\n"); - errno = EINVAL; - return -1; - } + if (!ctx->al_entry) { + ntfs_log_trace("Inode should contain attribute list to use this " + "function.\n"); + errno = EINVAL; + return -1; + } - /* Find place in MFT record where attribute will be moved. */ - a = ctx->attr; - nctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!nctx) - return -1; + /* Find place in MFT record where attribute will be moved. */ + a = ctx->attr; + nctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!nctx) + return -1; - /* - * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for - * attribute in @ni->mrec, not any extent inode in case if @ni is base - * file record. - */ - if (!ntfs_attr_find(a->type, (ntfschar*)((u8*)a + le16_to_cpu( - a->name_offset)), a->name_length, CASE_SENSITIVE, NULL, - 0, nctx)) { - ntfs_log_trace("Attribute of such type, with same name already " - "present in this MFT record.\n"); - err = EEXIST; - goto put_err_out; - } - if (errno != ENOENT) { - err = errno; - ntfs_log_debug("Attribute lookup failed.\n"); - goto put_err_out; - } + /* + * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for + * attribute in @ni->mrec, not any extent inode in case if @ni is base + * file record. + */ + if (!ntfs_attr_find(a->type, (ntfschar*)((u8*)a + le16_to_cpu( + a->name_offset)), a->name_length, CASE_SENSITIVE, NULL, + 0, nctx)) { + ntfs_log_trace("Attribute of such type, with same name already " + "present in this MFT record.\n"); + err = EEXIST; + goto put_err_out; + } + if (errno != ENOENT) { + err = errno; + ntfs_log_debug("Attribute lookup failed.\n"); + goto put_err_out; + } - /* Make space and move attribute. */ - if (ntfs_make_room_for_attr(ni->mrec, (u8*) nctx->attr, - le32_to_cpu(a->length))) { - err = errno; - ntfs_log_trace("Couldn't make space for attribute.\n"); - goto put_err_out; - } - memcpy(nctx->attr, a, le32_to_cpu(a->length)); - nctx->attr->instance = nctx->mrec->next_attr_instance; - nctx->mrec->next_attr_instance = cpu_to_le16( - (le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff); - ntfs_attr_record_resize(ctx->mrec, a, 0); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_inode_mark_dirty(ni); + /* Make space and move attribute. */ + if (ntfs_make_room_for_attr(ni->mrec, (u8*) nctx->attr, + le32_to_cpu(a->length))) { + err = errno; + ntfs_log_trace("Couldn't make space for attribute.\n"); + goto put_err_out; + } + memcpy(nctx->attr, a, le32_to_cpu(a->length)); + nctx->attr->instance = nctx->mrec->next_attr_instance; + nctx->mrec->next_attr_instance = cpu_to_le16( + (le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff); + ntfs_attr_record_resize(ctx->mrec, a, 0); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_inode_mark_dirty(ni); - /* Update attribute list. */ - ctx->al_entry->mft_reference = - MK_LE_MREF(ni->mft_no, le16_to_cpu(ni->mrec->sequence_number)); - ctx->al_entry->instance = nctx->attr->instance; - ntfs_attrlist_mark_dirty(ni); + /* Update attribute list. */ + ctx->al_entry->mft_reference = + MK_LE_MREF(ni->mft_no, le16_to_cpu(ni->mrec->sequence_number)); + ctx->al_entry->instance = nctx->attr->instance; + ntfs_attrlist_mark_dirty(ni); - ntfs_attr_put_search_ctx(nctx); - return 0; + ntfs_attr_put_search_ctx(nctx); + return 0; put_err_out: - ntfs_attr_put_search_ctx(nctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(nctx); + errno = err; + return -1; } /** @@ -4043,76 +4088,77 @@ put_err_out: * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) { - ntfs_inode *base_ni, *ni; - MFT_RECORD *m; - int i; +int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) +{ + ntfs_inode *base_ni, *ni; + MFT_RECORD *m; + int i; - if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0) { - errno = EINVAL; - ntfs_log_perror("%s: ctx=%p ctx->attr=%p extra=%d", __FUNCTION__, - ctx, ctx ? ctx->attr : NULL, extra); - return -1; - } + if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0) { + errno = EINVAL; + ntfs_log_perror("%s: ctx=%p ctx->attr=%p extra=%d", __FUNCTION__, + ctx, ctx ? ctx->attr : NULL, extra); + return -1; + } - ntfs_log_trace("Entering for attr 0x%x, inode %llu\n", - (unsigned) le32_to_cpu(ctx->attr->type), - (unsigned long long)ctx->ntfs_ino->mft_no); + ntfs_log_trace("Entering for attr 0x%x, inode %llu\n", + (unsigned) le32_to_cpu(ctx->attr->type), + (unsigned long long)ctx->ntfs_ino->mft_no); - if (ctx->ntfs_ino->nr_extents == -1) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; + if (ctx->ntfs_ino->nr_extents == -1) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; - if (!NInoAttrList(base_ni)) { - errno = EINVAL; - ntfs_log_perror("Inode %llu has no attrlist", - (unsigned long long)base_ni->mft_no); - return -1; - } + if (!NInoAttrList(base_ni)) { + errno = EINVAL; + ntfs_log_perror("Inode %llu has no attrlist", + (unsigned long long)base_ni->mft_no); + return -1; + } - if (ntfs_inode_attach_all_extents(ctx->ntfs_ino)) { - ntfs_log_perror("Couldn't attach extents, inode=%llu", - (unsigned long long)base_ni->mft_no); - return -1; - } + if (ntfs_inode_attach_all_extents(ctx->ntfs_ino)) { + ntfs_log_perror("Couldn't attach extents, inode=%llu", + (unsigned long long)base_ni->mft_no); + return -1; + } - /* Walk through all extents and try to move attribute to them. */ - for (i = 0; i < base_ni->nr_extents; i++) { - ni = base_ni->extent_nis[i]; - m = ni->mrec; + /* Walk through all extents and try to move attribute to them. */ + for (i = 0; i < base_ni->nr_extents; i++) { + ni = base_ni->extent_nis[i]; + m = ni->mrec; - if (ctx->ntfs_ino->mft_no == ni->mft_no) - continue; + if (ctx->ntfs_ino->mft_no == ni->mft_no) + continue; - if (le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) < - le32_to_cpu(ctx->attr->length) + extra) - continue; + if (le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use) < + le32_to_cpu(ctx->attr->length) + extra) + continue; - /* - * ntfs_attr_record_move_to can fail if extent with other lowest - * VCN already present in inode we trying move record to. So, - * do not return error. - */ - if (!ntfs_attr_record_move_to(ctx, ni)) - return 0; - } + /* + * ntfs_attr_record_move_to can fail if extent with other lowest + * VCN already present in inode we trying move record to. So, + * do not return error. + */ + if (!ntfs_attr_record_move_to(ctx, ni)) + return 0; + } - /* - * Failed to move attribute to one of the current extents, so allocate - * new extent and move attribute to it. - */ - ni = ntfs_mft_record_alloc(base_ni->vol, base_ni); - if (!ni) { - ntfs_log_perror("Couldn't allocate MFT record"); - return -1; - } - if (ntfs_attr_record_move_to(ctx, ni)) { - ntfs_log_perror("Couldn't move attribute to MFT record"); - return -1; - } - return 0; + /* + * Failed to move attribute to one of the current extents, so allocate + * new extent and move attribute to it. + */ + ni = ntfs_mft_record_alloc(base_ni->vol, base_ni); + if (!ni) { + ntfs_log_perror("Couldn't allocate MFT record"); + return -1; + } + if (ntfs_attr_record_move_to(ctx, ni)) { + ntfs_log_perror("Couldn't move attribute to MFT record"); + return -1; + } + return 0; } /** @@ -4135,167 +4181,168 @@ int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) { * function and it is likely there will be further changes made. */ int ntfs_attr_make_non_resident(ntfs_attr *na, - ntfs_attr_search_ctx *ctx) { - s64 new_allocated_size, bw; - ntfs_volume *vol = na->ni->vol; - ATTR_REC *a = ctx->attr; - runlist *rl; - int mp_size, mp_ofs, name_ofs, arec_size, err; + ntfs_attr_search_ctx *ctx) +{ + s64 new_allocated_size, bw; + ntfs_volume *vol = na->ni->vol; + ATTR_REC *a = ctx->attr; + runlist *rl; + int mp_size, mp_ofs, name_ofs, arec_size, err; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long - long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long + long)na->ni->mft_no, na->type); - /* Some preliminary sanity checking. */ - if (NAttrNonResident(na)) { - ntfs_log_trace("Eeek! Trying to make non-resident attribute " - "non-resident. Aborting...\n"); - errno = EINVAL; - return -1; - } + /* Some preliminary sanity checking. */ + if (NAttrNonResident(na)) { + ntfs_log_trace("Eeek! Trying to make non-resident attribute " + "non-resident. Aborting...\n"); + errno = EINVAL; + return -1; + } - /* Check that the attribute is allowed to be non-resident. */ - if (ntfs_attr_can_be_non_resident(vol, na->type)) - return -1; + /* Check that the attribute is allowed to be non-resident. */ + if (ntfs_attr_can_be_non_resident(vol, na->type)) + return -1; - new_allocated_size = (le32_to_cpu(a->value_length) + vol->cluster_size - - 1) & ~(vol->cluster_size - 1); + new_allocated_size = (le32_to_cpu(a->value_length) + vol->cluster_size + - 1) & ~(vol->cluster_size - 1); - if (new_allocated_size > 0) { - /* Start by allocating clusters to hold the attribute value. */ - rl = ntfs_cluster_alloc(vol, 0, new_allocated_size >> - vol->cluster_size_bits, -1, DATA_ZONE); - if (!rl) - return -1; - } else - rl = NULL; - /* - * Setup the in-memory attribute structure to be non-resident so that - * we can use ntfs_attr_pwrite(). - */ - NAttrSetNonResident(na); - na->rl = rl; - na->allocated_size = new_allocated_size; - na->data_size = na->initialized_size = le32_to_cpu(a->value_length); - /* - * FIXME: For now just clear all of these as we don't support them when - * writing. - */ - NAttrClearSparse(na); - NAttrClearEncrypted(na); - if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { - /* set compression writing parameters */ - na->compression_block_size - = 1 << (STANDARD_COMPRESSION_UNIT + vol->cluster_size_bits); - na->compression_block_clusters = 1 << STANDARD_COMPRESSION_UNIT; - } + if (new_allocated_size > 0) { + /* Start by allocating clusters to hold the attribute value. */ + rl = ntfs_cluster_alloc(vol, 0, new_allocated_size >> + vol->cluster_size_bits, -1, DATA_ZONE); + if (!rl) + return -1; + } else + rl = NULL; + /* + * Setup the in-memory attribute structure to be non-resident so that + * we can use ntfs_attr_pwrite(). + */ + NAttrSetNonResident(na); + na->rl = rl; + na->allocated_size = new_allocated_size; + na->data_size = na->initialized_size = le32_to_cpu(a->value_length); + /* + * FIXME: For now just clear all of these as we don't support them when + * writing. + */ + NAttrClearSparse(na); + NAttrClearEncrypted(na); + if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { + /* set compression writing parameters */ + na->compression_block_size + = 1 << (STANDARD_COMPRESSION_UNIT + vol->cluster_size_bits); + na->compression_block_clusters = 1 << STANDARD_COMPRESSION_UNIT; + } - if (rl) { - /* Now copy the attribute value to the allocated cluster(s). */ - bw = ntfs_attr_pwrite(na, 0, le32_to_cpu(a->value_length), - (u8*)a + le16_to_cpu(a->value_offset)); - if (bw != le32_to_cpu(a->value_length)) { - err = errno; - ntfs_log_debug("Eeek! Failed to write out attribute value " - "(bw = %lli, errno = %i). " - "Aborting...\n", (long long)bw, err); - if (bw >= 0) - err = EIO; - goto cluster_free_err_out; - } - } - /* Determine the size of the mapping pairs array. */ - mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, INT_MAX); - if (mp_size < 0) { - err = errno; - ntfs_log_debug("Eeek! Failed to get size for mapping pairs array. " - "Aborting...\n"); - goto cluster_free_err_out; - } - /* Calculate new offsets for the name and the mapping pairs array. */ - if (na->ni->flags & FILE_ATTR_COMPRESSED) - name_ofs = (sizeof(ATTR_REC) + 7) & ~7; - else - name_ofs = (sizeof(ATTR_REC) - sizeof(a->compressed_size) + 7) & ~7; - mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; - /* - * Determine the size of the resident part of the non-resident - * attribute record. (Not compressed thus no compressed_size element - * present.) - */ - arec_size = (mp_ofs + mp_size + 7) & ~7; + if (rl) { + /* Now copy the attribute value to the allocated cluster(s). */ + bw = ntfs_attr_pwrite(na, 0, le32_to_cpu(a->value_length), + (u8*)a + le16_to_cpu(a->value_offset)); + if (bw != le32_to_cpu(a->value_length)) { + err = errno; + ntfs_log_debug("Eeek! Failed to write out attribute value " + "(bw = %lli, errno = %i). " + "Aborting...\n", (long long)bw, err); + if (bw >= 0) + err = EIO; + goto cluster_free_err_out; + } + } + /* Determine the size of the mapping pairs array. */ + mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, INT_MAX); + if (mp_size < 0) { + err = errno; + ntfs_log_debug("Eeek! Failed to get size for mapping pairs array. " + "Aborting...\n"); + goto cluster_free_err_out; + } + /* Calculate new offsets for the name and the mapping pairs array. */ + if (na->ni->flags & FILE_ATTR_COMPRESSED) + name_ofs = (sizeof(ATTR_REC) + 7) & ~7; + else + name_ofs = (sizeof(ATTR_REC) - sizeof(a->compressed_size) + 7) & ~7; + mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; + /* + * Determine the size of the resident part of the non-resident + * attribute record. (Not compressed thus no compressed_size element + * present.) + */ + arec_size = (mp_ofs + mp_size + 7) & ~7; - /* Resize the resident part of the attribute record. */ - if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { - err = errno; - goto cluster_free_err_out; - } + /* Resize the resident part of the attribute record. */ + if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { + err = errno; + goto cluster_free_err_out; + } - /* - * Convert the resident part of the attribute record to describe a - * non-resident attribute. - */ - a->non_resident = 1; + /* + * Convert the resident part of the attribute record to describe a + * non-resident attribute. + */ + a->non_resident = 1; - /* Move the attribute name if it exists and update the offset. */ - if (a->name_length) - memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - a->name_offset = cpu_to_le16(name_ofs); + /* Move the attribute name if it exists and update the offset. */ + if (a->name_length) + memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); + a->name_offset = cpu_to_le16(name_ofs); - /* Setup the fields specific to non-resident attributes. */ - a->lowest_vcn = cpu_to_sle64(0); - a->highest_vcn = cpu_to_sle64((new_allocated_size - 1) >> - vol->cluster_size_bits); + /* Setup the fields specific to non-resident attributes. */ + a->lowest_vcn = cpu_to_sle64(0); + a->highest_vcn = cpu_to_sle64((new_allocated_size - 1) >> + vol->cluster_size_bits); - a->mapping_pairs_offset = cpu_to_le16(mp_ofs); + a->mapping_pairs_offset = cpu_to_le16(mp_ofs); - /* - * Update the flags to match the in-memory ones. - * However cannot change the compression state if we had - * a fuse_file_info open with a mark for release. - * The decisions about compression can only be made when - * creating/recreating the stream, not when making non resident. - */ - a->flags &= ~(ATTR_IS_SPARSE | ATTR_IS_ENCRYPTED); - if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { - /* support only ATTR_IS_COMPRESSED compression mode */ - a->compression_unit = STANDARD_COMPRESSION_UNIT; - a->compressed_size = const_cpu_to_le64(0); - } else { - a->compression_unit = 0; - a->flags &= ~ATTR_COMPRESSION_MASK; - na->data_flags = a->flags; - } + /* + * Update the flags to match the in-memory ones. + * However cannot change the compression state if we had + * a fuse_file_info open with a mark for release. + * The decisions about compression can only be made when + * creating/recreating the stream, not when making non resident. + */ + a->flags &= ~(ATTR_IS_SPARSE | ATTR_IS_ENCRYPTED); + if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { + /* support only ATTR_IS_COMPRESSED compression mode */ + a->compression_unit = STANDARD_COMPRESSION_UNIT; + a->compressed_size = const_cpu_to_le64(0); + } else { + a->compression_unit = 0; + a->flags &= ~ATTR_COMPRESSION_MASK; + na->data_flags = a->flags; + } - memset(&a->reserved1, 0, sizeof(a->reserved1)); + memset(&a->reserved1, 0, sizeof(a->reserved1)); - a->allocated_size = cpu_to_sle64(new_allocated_size); - a->data_size = a->initialized_size = cpu_to_sle64(na->data_size); + a->allocated_size = cpu_to_sle64(new_allocated_size); + a->data_size = a->initialized_size = cpu_to_sle64(na->data_size); - /* Generate the mapping pairs array in the attribute record. */ - if (ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs, arec_size - mp_ofs, - rl, 0, NULL) < 0) { - // FIXME: Eeek! We need rollback! (AIA) - ntfs_log_trace("Eeek! Failed to build mapping pairs. Leaving " - "corrupt attribute record on disk. In memory " - "runlist is still intact! Error code is %i. " - "FIXME: Need to rollback instead!\n", errno); - return -1; - } + /* Generate the mapping pairs array in the attribute record. */ + if (ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs, arec_size - mp_ofs, + rl, 0, NULL) < 0) { + // FIXME: Eeek! We need rollback! (AIA) + ntfs_log_trace("Eeek! Failed to build mapping pairs. Leaving " + "corrupt attribute record on disk. In memory " + "runlist is still intact! Error code is %i. " + "FIXME: Need to rollback instead!\n", errno); + return -1; + } - /* Done! */ - return 0; + /* Done! */ + return 0; cluster_free_err_out: - if (rl && ntfs_cluster_free(vol, na, 0, -1) < 0) - ntfs_log_trace("Eeek! Failed to release allocated clusters in error " - "code path. Leaving inconsistent metadata...\n"); - NAttrClearNonResident(na); - na->allocated_size = na->data_size; - na->rl = NULL; - free(rl); - errno = err; - return -1; + if (rl && ntfs_cluster_free(vol, na, 0, -1) < 0) + ntfs_log_trace("Eeek! Failed to release allocated clusters in error " + "code path. Leaving inconsistent metadata...\n"); + NAttrClearNonResident(na); + na->allocated_size = na->data_size; + na->rl = NULL; + free(rl); + errno = err; + return -1; } @@ -4308,7 +4355,7 @@ static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize); * * Change the size of a resident, open ntfs attribute @na to @newsize bytes. * - * On success return 0 + * On success return 0 * On error return values are: * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT * STATUS_ERROR - otherwise @@ -4317,216 +4364,218 @@ static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize); * ERANGE - @newsize is not valid for the attribute type of @na. * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. */ -static int ntfs_resident_attr_resize_i(ntfs_attr *na, const s64 newsize) { - ntfs_attr_search_ctx *ctx; - ntfs_volume *vol; - ntfs_inode *ni; - int err, ret = STATUS_ERROR; +static int ntfs_resident_attr_resize_i(ntfs_attr *na, const s64 newsize) +{ + ntfs_attr_search_ctx *ctx; + ntfs_volume *vol; + ntfs_inode *ni; + int err, ret = STATUS_ERROR; - ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)newsize); + ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)newsize); - /* Get the attribute record that needs modification. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, 0, NULL, 0, - ctx)) { - err = errno; - ntfs_log_perror("ntfs_attr_lookup failed"); - goto put_err_out; - } - vol = na->ni->vol; - /* - * Check the attribute type and the corresponding minimum and maximum - * sizes against @newsize and fail if @newsize is out of bounds. - */ - if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { - err = errno; - if (err == ENOENT) - err = EIO; - ntfs_log_perror("%s: bounds check failed", __FUNCTION__); - goto put_err_out; - } - /* - * If @newsize is bigger than the mft record we need to make the - * attribute non-resident if the attribute type supports it. If it is - * smaller we can go ahead and attempt the resize. - */ - if (newsize < vol->mft_record_size) { - /* Perform the resize of the attribute record. */ - if (!(ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, - newsize))) { - /* Update attribute size everywhere. */ - na->data_size = na->initialized_size = newsize; - na->allocated_size = (newsize + 7) & ~7; - if ((na->data_flags & ATTR_COMPRESSION_MASK) - || NAttrSparse(na)) - na->compressed_size = na->allocated_size; - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - na->ni->allocated_size = na->allocated_size; - NInoFileNameSetDirty(na->ni); - } - goto resize_done; - } - /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */ - if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { - err = errno; - goto put_err_out; - } - } - /* There is not enough space in the mft record to perform the resize. */ + /* Get the attribute record that needs modification. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, 0, NULL, 0, + ctx)) { + err = errno; + ntfs_log_perror("ntfs_attr_lookup failed"); + goto put_err_out; + } + vol = na->ni->vol; + /* + * Check the attribute type and the corresponding minimum and maximum + * sizes against @newsize and fail if @newsize is out of bounds. + */ + if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { + err = errno; + if (err == ENOENT) + err = EIO; + ntfs_log_perror("%s: bounds check failed", __FUNCTION__); + goto put_err_out; + } + /* + * If @newsize is bigger than the mft record we need to make the + * attribute non-resident if the attribute type supports it. If it is + * smaller we can go ahead and attempt the resize. + */ + if (newsize < vol->mft_record_size) { + /* Perform the resize of the attribute record. */ + if (!(ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, + newsize))) { + /* Update attribute size everywhere. */ + na->data_size = na->initialized_size = newsize; + na->allocated_size = (newsize + 7) & ~7; + if ((na->data_flags & ATTR_COMPRESSION_MASK) + || NAttrSparse(na)) + na->compressed_size = na->allocated_size; + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + na->ni->data_size = na->data_size; + na->ni->allocated_size = na->allocated_size; + NInoFileNameSetDirty(na->ni); + } + goto resize_done; + } + /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */ + if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { + err = errno; + goto put_err_out; + } + } + /* There is not enough space in the mft record to perform the resize. */ - /* Make the attribute non-resident if possible. */ - if (!ntfs_attr_make_non_resident(na, ctx)) { - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - /* Resize non-resident attribute */ - return ntfs_attr_truncate(na, newsize); - } else if (errno != ENOSPC && errno != EPERM) { - err = errno; - ntfs_log_perror("Failed to make attribute non-resident"); - goto put_err_out; - } + /* Make the attribute non-resident if possible. */ + if (!ntfs_attr_make_non_resident(na, ctx)) { + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + /* Resize non-resident attribute */ + return ntfs_attr_truncate(na, newsize); + } else if (errno != ENOSPC && errno != EPERM) { + err = errno; + ntfs_log_perror("Failed to make attribute non-resident"); + goto put_err_out; + } - /* Try to make other attributes non-resident and retry each time. */ - ntfs_attr_init_search_ctx(ctx, NULL, na->ni->mrec); - while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) { - ntfs_attr *tna; - ATTR_RECORD *a; + /* Try to make other attributes non-resident and retry each time. */ + ntfs_attr_init_search_ctx(ctx, NULL, na->ni->mrec); + while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) { + ntfs_attr *tna; + ATTR_RECORD *a; - a = ctx->attr; - if (a->non_resident) - continue; + a = ctx->attr; + if (a->non_resident) + continue; - /* - * Check out whether convert is reasonable. Assume that mapping - * pairs will take 8 bytes. - */ - if (le32_to_cpu(a->length) <= offsetof(ATTR_RECORD, - compressed_size) + ((a->name_length * - sizeof(ntfschar) + 7) & ~7) + 8) - continue; + /* + * Check out whether convert is reasonable. Assume that mapping + * pairs will take 8 bytes. + */ + if (le32_to_cpu(a->length) <= offsetof(ATTR_RECORD, + compressed_size) + ((a->name_length * + sizeof(ntfschar) + 7) & ~7) + 8) + continue; - tna = ntfs_attr_open(na->ni, a->type, (ntfschar*)((u8*)a + - le16_to_cpu(a->name_offset)), a->name_length); - if (!tna) { - err = errno; - ntfs_log_perror("Couldn't open attribute"); - goto put_err_out; - } - if (ntfs_attr_make_non_resident(tna, ctx)) { - ntfs_attr_close(tna); - continue; - } - ntfs_inode_mark_dirty(tna->ni); - ntfs_attr_close(tna); - ntfs_attr_put_search_ctx(ctx); - return ntfs_resident_attr_resize(na, newsize); - } - /* Check whether error occurred. */ - if (errno != ENOENT) { - err = errno; - ntfs_log_perror("%s: Attribute lookup failed 1", __FUNCTION__); - goto put_err_out; - } + tna = ntfs_attr_open(na->ni, a->type, (ntfschar*)((u8*)a + + le16_to_cpu(a->name_offset)), a->name_length); + if (!tna) { + err = errno; + ntfs_log_perror("Couldn't open attribute"); + goto put_err_out; + } + if (ntfs_attr_make_non_resident(tna, ctx)) { + ntfs_attr_close(tna); + continue; + } + ntfs_inode_mark_dirty(tna->ni); + ntfs_attr_close(tna); + ntfs_attr_put_search_ctx(ctx); + return ntfs_resident_attr_resize(na, newsize); + } + /* Check whether error occurred. */ + if (errno != ENOENT) { + err = errno; + ntfs_log_perror("%s: Attribute lookup failed 1", __FUNCTION__); + goto put_err_out; + } + + /* + * The standard information and attribute list attributes can't be + * moved out from the base MFT record, so try to move out others. + */ + if (na->type==AT_STANDARD_INFORMATION || na->type==AT_ATTRIBUTE_LIST) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_free_space(na->ni, offsetof(ATTR_RECORD, + non_resident_end) + 8)) { + ntfs_log_perror("Could not free space in MFT record"); + return -1; + } + return ntfs_resident_attr_resize(na, newsize); + } - /* - * The standard information and attribute list attributes can't be - * moved out from the base MFT record, so try to move out others. - */ - if (na->type==AT_STANDARD_INFORMATION || na->type==AT_ATTRIBUTE_LIST) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_free_space(na->ni, offsetof(ATTR_RECORD, - non_resident_end) + 8)) { - ntfs_log_perror("Could not free space in MFT record"); - return -1; - } - return ntfs_resident_attr_resize(na, newsize); - } + /* + * Move the attribute to a new mft record, creating an attribute list + * attribute or modifying it if it is already present. + */ - /* - * Move the attribute to a new mft record, creating an attribute list - * attribute or modifying it if it is already present. - */ + /* Point search context back to attribute which we need resize. */ + ntfs_attr_init_search_ctx(ctx, na->ni, NULL); + if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + ntfs_log_perror("%s: Attribute lookup failed 2", __FUNCTION__); + err = errno; + goto put_err_out; + } - /* Point search context back to attribute which we need resize. */ - ntfs_attr_init_search_ctx(ctx, na->ni, NULL); - if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - ntfs_log_perror("%s: Attribute lookup failed 2", __FUNCTION__); - err = errno; - goto put_err_out; - } + /* + * Check whether attribute is already single in this MFT record. + * 8 added for the attribute terminator. + */ + if (le32_to_cpu(ctx->mrec->bytes_in_use) == + le16_to_cpu(ctx->mrec->attrs_offset) + + le32_to_cpu(ctx->attr->length) + 8) { + err = ENOSPC; + ntfs_log_trace("MFT record is filled with one attribute\n"); + ret = STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; + goto put_err_out; + } - /* - * Check whether attribute is already single in this MFT record. - * 8 added for the attribute terminator. - */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) == - le16_to_cpu(ctx->mrec->attrs_offset) + - le32_to_cpu(ctx->attr->length) + 8) { - err = ENOSPC; - ntfs_log_trace("MFT record is filled with one attribute\n"); - ret = STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT; - goto put_err_out; - } + /* Add attribute list if not present. */ + if (na->ni->nr_extents == -1) + ni = na->ni->base_ni; + else + ni = na->ni; + if (!NInoAttrList(ni)) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_add_attrlist(ni)) + return -1; + return ntfs_resident_attr_resize(na, newsize); + } + /* Allocate new mft record. */ + ni = ntfs_mft_record_alloc(vol, ni); + if (!ni) { + err = errno; + ntfs_log_perror("Couldn't allocate new MFT record"); + goto put_err_out; + } + /* Move attribute to it. */ + if (ntfs_attr_record_move_to(ctx, ni)) { + err = errno; + ntfs_log_perror("Couldn't move attribute to new MFT record"); + goto put_err_out; + } + /* Update ntfs attribute. */ + if (na->ni->nr_extents == -1) + na->ni = ni; - /* Add attribute list if not present. */ - if (na->ni->nr_extents == -1) - ni = na->ni->base_ni; - else - ni = na->ni; - if (!NInoAttrList(ni)) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_add_attrlist(ni)) - return -1; - return ntfs_resident_attr_resize(na, newsize); - } - /* Allocate new mft record. */ - ni = ntfs_mft_record_alloc(vol, ni); - if (!ni) { - err = errno; - ntfs_log_perror("Couldn't allocate new MFT record"); - goto put_err_out; - } - /* Move attribute to it. */ - if (ntfs_attr_record_move_to(ctx, ni)) { - err = errno; - ntfs_log_perror("Couldn't move attribute to new MFT record"); - goto put_err_out; - } - /* Update ntfs attribute. */ - if (na->ni->nr_extents == -1) - na->ni = ni; - - ntfs_attr_put_search_ctx(ctx); - /* Try to perform resize once again. */ - return ntfs_resident_attr_resize(na, newsize); + ntfs_attr_put_search_ctx(ctx); + /* Try to perform resize once again. */ + return ntfs_resident_attr_resize(na, newsize); resize_done: - /* - * Set the inode (and its base inode if it exists) dirty so it is - * written out later. - */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - return 0; + /* + * Set the inode (and its base inode if it exists) dirty so it is + * written out later. + */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return ret; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return ret; } -static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_resident_attr_resize_i(na, newsize); - ntfs_log_leave("\n"); - return ret; +static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) +{ + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_resident_attr_resize_i(na, newsize); + ntfs_log_leave("\n"); + return ret; } /** @@ -4548,160 +4597,161 @@ static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) { * We expect the caller to do this as this is a fairly low level * function and it is likely there will be further changes made. */ -static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) { - ntfs_volume *vol = na->ni->vol; - ATTR_REC *a = ctx->attr; - int name_ofs, val_ofs, err = EIO; - s64 arec_size, bytes_read; +static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) +{ + ntfs_volume *vol = na->ni->vol; + ATTR_REC *a = ctx->attr; + int name_ofs, val_ofs, err = EIO; + s64 arec_size, bytes_read; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long - long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", (unsigned long + long)na->ni->mft_no, na->type); - /* Should be called for the first extent of the attribute. */ - if (sle64_to_cpu(a->lowest_vcn)) { - ntfs_log_trace("Eeek! Should be called for the first extent of the " - "attribute. Aborting...\n"); - err = EINVAL; - return -1; - } + /* Should be called for the first extent of the attribute. */ + if (sle64_to_cpu(a->lowest_vcn)) { + ntfs_log_trace("Eeek! Should be called for the first extent of the " + "attribute. Aborting...\n"); + err = EINVAL; + return -1; + } - /* Some preliminary sanity checking. */ - if (!NAttrNonResident(na)) { - ntfs_log_trace("Eeek! Trying to make resident attribute resident. " - "Aborting...\n"); - errno = EINVAL; - return -1; - } + /* Some preliminary sanity checking. */ + if (!NAttrNonResident(na)) { + ntfs_log_trace("Eeek! Trying to make resident attribute resident. " + "Aborting...\n"); + errno = EINVAL; + return -1; + } - /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */ - if (na->type == AT_BITMAP && na->ni->mft_no == FILE_MFT) { - errno = EPERM; - return -1; - } + /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */ + if (na->type == AT_BITMAP && na->ni->mft_no == FILE_MFT) { + errno = EPERM; + return -1; + } - /* Check that the attribute is allowed to be resident. */ - if (ntfs_attr_can_be_resident(vol, na->type)) - return -1; + /* Check that the attribute is allowed to be resident. */ + if (ntfs_attr_can_be_resident(vol, na->type)) + return -1; - if (na->data_flags & ATTR_IS_ENCRYPTED) { - ntfs_log_trace("Making encrypted streams resident is not " - "implemented yet.\n"); - errno = EOPNOTSUPP; - return -1; - } + if (na->data_flags & ATTR_IS_ENCRYPTED) { + ntfs_log_trace("Making encrypted streams resident is not " + "implemented yet.\n"); + errno = EOPNOTSUPP; + return -1; + } - /* Work out offsets into and size of the resident attribute. */ - name_ofs = 24; /* = sizeof(resident_ATTR_REC); */ - val_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; - arec_size = (val_ofs + na->data_size + 7) & ~7; + /* Work out offsets into and size of the resident attribute. */ + name_ofs = 24; /* = sizeof(resident_ATTR_REC); */ + val_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; + arec_size = (val_ofs + na->data_size + 7) & ~7; - /* Sanity check the size before we start modifying the attribute. */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) + - arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) { - errno = ENOSPC; - ntfs_log_trace("Not enough space to make attribute resident\n"); - return -1; - } + /* Sanity check the size before we start modifying the attribute. */ + if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) + + arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) { + errno = ENOSPC; + ntfs_log_trace("Not enough space to make attribute resident\n"); + return -1; + } - /* Read and cache the whole runlist if not already done. */ - if (ntfs_attr_map_whole_runlist(na)) - return -1; + /* Read and cache the whole runlist if not already done. */ + if (ntfs_attr_map_whole_runlist(na)) + return -1; - /* Move the attribute name if it exists and update the offset. */ - if (a->name_length) { - memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - } - a->name_offset = cpu_to_le16(name_ofs); + /* Move the attribute name if it exists and update the offset. */ + if (a->name_length) { + memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); + } + a->name_offset = cpu_to_le16(name_ofs); - /* Resize the resident part of the attribute record. */ - if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { - /* - * Bug, because ntfs_attr_record_resize should not fail (we - * already checked that attribute fits MFT record). - */ - ntfs_log_error("BUG! Failed to resize attribute record. " - "Please report to the %s. Aborting...\n", - NTFS_DEV_LIST); - errno = EIO; - return -1; - } + /* Resize the resident part of the attribute record. */ + if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { + /* + * Bug, because ntfs_attr_record_resize should not fail (we + * already checked that attribute fits MFT record). + */ + ntfs_log_error("BUG! Failed to resize attribute record. " + "Please report to the %s. Aborting...\n", + NTFS_DEV_LIST); + errno = EIO; + return -1; + } - /* Convert the attribute record to describe a resident attribute. */ - a->non_resident = 0; - a->flags = 0; - a->value_length = cpu_to_le32(na->data_size); - a->value_offset = cpu_to_le16(val_ofs); - /* - * If a data stream was wiped out, adjust the compression mode - * to current state of compression flag - */ - if (!na->data_size - && (na->type == AT_DATA) - && (na->ni->flags & FILE_ATTR_COMPRESSED)) { - a->flags |= ATTR_IS_COMPRESSED; - na->data_flags = a->flags; - } - /* - * File names cannot be non-resident so we would never see this here - * but at least it serves as a reminder that there may be attributes - * for which we do need to set this flag. (AIA) - */ - if (a->type == AT_FILE_NAME) - a->resident_flags = RESIDENT_ATTR_IS_INDEXED; - else - a->resident_flags = 0; - a->reservedR = 0; + /* Convert the attribute record to describe a resident attribute. */ + a->non_resident = 0; + a->flags = 0; + a->value_length = cpu_to_le32(na->data_size); + a->value_offset = cpu_to_le16(val_ofs); + /* + * If a data stream was wiped out, adjust the compression mode + * to current state of compression flag + */ + if (!na->data_size + && (na->type == AT_DATA) + && (na->ni->flags & FILE_ATTR_COMPRESSED)) { + a->flags |= ATTR_IS_COMPRESSED; + na->data_flags = a->flags; + } + /* + * File names cannot be non-resident so we would never see this here + * but at least it serves as a reminder that there may be attributes + * for which we do need to set this flag. (AIA) + */ + if (a->type == AT_FILE_NAME) + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + else + a->resident_flags = 0; + a->reservedR = 0; - /* Sanity fixup... Shouldn't really happen. (AIA) */ - if (na->initialized_size > na->data_size) - na->initialized_size = na->data_size; + /* Sanity fixup... Shouldn't really happen. (AIA) */ + if (na->initialized_size > na->data_size) + na->initialized_size = na->data_size; - /* Copy data from run list to resident attribute value. */ - bytes_read = ntfs_rl_pread(vol, na->rl, 0, na->initialized_size, - (u8*)a + val_ofs); - if (bytes_read != na->initialized_size) { - if (bytes_read < 0) - err = errno; - ntfs_log_trace("Eeek! Failed to read attribute data. Leaving " - "inconstant metadata. Run chkdsk. " - "Aborting...\n"); - errno = err; - return -1; - } + /* Copy data from run list to resident attribute value. */ + bytes_read = ntfs_rl_pread(vol, na->rl, 0, na->initialized_size, + (u8*)a + val_ofs); + if (bytes_read != na->initialized_size) { + if (bytes_read < 0) + err = errno; + ntfs_log_trace("Eeek! Failed to read attribute data. Leaving " + "inconstant metadata. Run chkdsk. " + "Aborting...\n"); + errno = err; + return -1; + } - /* Clear memory in gap between initialized_size and data_size. */ - if (na->initialized_size < na->data_size) - memset((u8*)a + val_ofs + na->initialized_size, 0, - na->data_size - na->initialized_size); + /* Clear memory in gap between initialized_size and data_size. */ + if (na->initialized_size < na->data_size) + memset((u8*)a + val_ofs + na->initialized_size, 0, + na->data_size - na->initialized_size); - /* - * Deallocate clusters from the runlist. - * - * NOTE: We can use ntfs_cluster_free() because we have already mapped - * the whole run list and thus it doesn't matter that the attribute - * record is in a transiently corrupted state at this moment in time. - */ - if (ntfs_cluster_free(vol, na, 0, -1) < 0) { - err = errno; - ntfs_log_perror("Eeek! Failed to release allocated clusters"); - ntfs_log_trace("Ignoring error and leaving behind wasted " - "clusters.\n"); - } + /* + * Deallocate clusters from the runlist. + * + * NOTE: We can use ntfs_cluster_free() because we have already mapped + * the whole run list and thus it doesn't matter that the attribute + * record is in a transiently corrupted state at this moment in time. + */ + if (ntfs_cluster_free(vol, na, 0, -1) < 0) { + err = errno; + ntfs_log_perror("Eeek! Failed to release allocated clusters"); + ntfs_log_trace("Ignoring error and leaving behind wasted " + "clusters.\n"); + } - /* Throw away the now unused runlist. */ - free(na->rl); - na->rl = NULL; + /* Throw away the now unused runlist. */ + free(na->rl); + na->rl = NULL; - /* Update in-memory struct ntfs_attr. */ - NAttrClearNonResident(na); - NAttrClearSparse(na); - NAttrClearEncrypted(na); - na->initialized_size = na->data_size; - na->allocated_size = na->compressed_size = (na->data_size + 7) & ~7; - na->compression_block_size = 0; - na->compression_block_size_bits = na->compression_block_clusters = 0; - return 0; + /* Update in-memory struct ntfs_attr. */ + NAttrClearNonResident(na); + NAttrClearSparse(na); + NAttrClearEncrypted(na); + na->initialized_size = na->data_size; + na->allocated_size = na->compressed_size = (na->data_size + 7) & ~7; + na->compression_block_size = 0; + na->compression_block_size_bits = na->compression_block_clusters = 0; + return 0; } /* @@ -4709,424 +4759,417 @@ static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) { * update allocated and compressed size. */ static int ntfs_attr_update_meta(ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, - ntfs_attr_search_ctx *ctx) { - int sparse, ret = 0; + ntfs_attr_search_ctx *ctx) +{ + int sparse, ret = 0; + + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x\n", + (unsigned long long)na->ni->mft_no, na->type); + + if (a->lowest_vcn) + goto out; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x\n", - (unsigned long long)na->ni->mft_no, na->type); + a->allocated_size = cpu_to_sle64(na->allocated_size); - if (a->lowest_vcn) - goto out; + /* Update sparse bit. */ + sparse = ntfs_rl_sparse(na->rl); + if (sparse == -1) { + errno = EIO; + goto error; + } - a->allocated_size = cpu_to_sle64(na->allocated_size); + /* Attribute become sparse. */ + if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) { + /* + * Move attribute to another mft record, if attribute is too + * small to add compressed_size field to it and we have no + * free space in the current mft record. + */ + if ((le32_to_cpu(a->length) - + le16_to_cpu(a->mapping_pairs_offset) == 8) + && !(le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use))) { - /* Update sparse bit. */ - sparse = ntfs_rl_sparse(na->rl); - if (sparse == -1) { - errno = EIO; - goto error; - } - - /* Attribute become sparse. */ - if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) { - /* - * Move attribute to another mft record, if attribute is too - * small to add compressed_size field to it and we have no - * free space in the current mft record. - */ - if ((le32_to_cpu(a->length) - - le16_to_cpu(a->mapping_pairs_offset) == 8) - && !(le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use))) { - - if (!NInoAttrList(na->ni)) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_add_attrlist(na->ni)) - goto leave; - goto retry; - } - if (ntfs_attr_record_move_away(ctx, 8)) { - ntfs_log_perror("Failed to move attribute"); - goto error; - } - ntfs_attr_put_search_ctx(ctx); - goto retry; - } - if (!(le32_to_cpu(a->length) - le16_to_cpu( - a->mapping_pairs_offset))) { - errno = EIO; - ntfs_log_perror("Mapping pairs space is 0"); - goto error; - } - - NAttrSetSparse(na); - a->flags |= ATTR_IS_SPARSE; - a->compression_unit = STANDARD_COMPRESSION_UNIT; /* Windows + if (!NInoAttrList(na->ni)) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_add_attrlist(na->ni)) + goto leave; + goto retry; + } + if (ntfs_attr_record_move_away(ctx, 8)) { + ntfs_log_perror("Failed to move attribute"); + goto error; + } + ntfs_attr_put_search_ctx(ctx); + goto retry; + } + if (!(le32_to_cpu(a->length) - le16_to_cpu( + a->mapping_pairs_offset))) { + errno = EIO; + ntfs_log_perror("Mapping pairs space is 0"); + goto error; + } + + NAttrSetSparse(na); + a->flags |= ATTR_IS_SPARSE; + a->compression_unit = STANDARD_COMPRESSION_UNIT; /* Windows set it so, even if attribute is not actually compressed. */ + + memmove((u8*)a + le16_to_cpu(a->name_offset) + 8, + (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); - memmove((u8*)a + le16_to_cpu(a->name_offset) + 8, - (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); + a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8); + + a->mapping_pairs_offset = + cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) + 8); + } - a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8); + /* Attribute no longer sparse. */ + if (!sparse && (a->flags & ATTR_IS_SPARSE) && + !(a->flags & ATTR_IS_COMPRESSED)) { + + NAttrClearSparse(na); + a->flags &= ~ATTR_IS_SPARSE; + a->compression_unit = 0; + + memmove((u8*)a + le16_to_cpu(a->name_offset) - 8, + (u8*)a + le16_to_cpu(a->name_offset), + a->name_length * sizeof(ntfschar)); + + if (le16_to_cpu(a->name_offset) >= 8) + a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8); - a->mapping_pairs_offset = - cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) + 8); - } + a->mapping_pairs_offset = + cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) - 8); + } - /* Attribute no longer sparse. */ - if (!sparse && (a->flags & ATTR_IS_SPARSE) && - !(a->flags & ATTR_IS_COMPRESSED)) { + /* Update compressed size if required. */ + if (sparse || (na->data_flags & ATTR_COMPRESSION_MASK)) { + s64 new_compr_size; - NAttrClearSparse(na); - a->flags &= ~ATTR_IS_SPARSE; - a->compression_unit = 0; - - memmove((u8*)a + le16_to_cpu(a->name_offset) - 8, - (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - - if (le16_to_cpu(a->name_offset) >= 8) - a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8); - - a->mapping_pairs_offset = - cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) - 8); - } - - /* Update compressed size if required. */ - if (sparse || (na->data_flags & ATTR_COMPRESSION_MASK)) { - s64 new_compr_size; - - new_compr_size = ntfs_rl_get_compressed_size(na->ni->vol, na->rl); - if (new_compr_size == -1) - goto error; - - na->compressed_size = new_compr_size; - a->compressed_size = cpu_to_sle64(new_compr_size); - } - /* - * Set FILE_NAME dirty flag, to update sparse bit and - * allocated size in the index. - */ - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - if (sparse) - na->ni->allocated_size = na->compressed_size; - else - na->ni->allocated_size = na->allocated_size; - NInoFileNameSetDirty(na->ni); - } + new_compr_size = ntfs_rl_get_compressed_size(na->ni->vol, na->rl); + if (new_compr_size == -1) + goto error; + + na->compressed_size = new_compr_size; + a->compressed_size = cpu_to_sle64(new_compr_size); + } + /* + * Set FILE_NAME dirty flag, to update sparse bit and + * allocated size in the index. + */ + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + if (sparse) + na->ni->allocated_size = na->compressed_size; + else + na->ni->allocated_size = na->allocated_size; + NInoFileNameSetDirty(na->ni); + } out: - return ret; -leave: - ret = -1; - goto out; /* return -1 */ -retry: - ret = -2; - goto out; -error: - ret = -3; - goto out; + return ret; +leave: ret = -1; goto out; /* return -1 */ +retry: ret = -2; goto out; +error: ret = -3; goto out; } #define NTFS_VCN_DELETE_MARK -2 /** * ntfs_attr_update_mapping_pairs_i - see ntfs_attr_update_mapping_pairs */ -static int ntfs_attr_update_mapping_pairs_i(ntfs_attr *na, VCN from_vcn) { - ntfs_attr_search_ctx *ctx; - ntfs_inode *ni, *base_ni; - MFT_RECORD *m; - ATTR_RECORD *a; - VCN stop_vcn; - const runlist_element *stop_rl; - int err, mp_size, cur_max_mp_size, exp_max_mp_size, ret = -1; - BOOL finished_build; +static int ntfs_attr_update_mapping_pairs_i(ntfs_attr *na, VCN from_vcn) +{ + ntfs_attr_search_ctx *ctx; + ntfs_inode *ni, *base_ni; + MFT_RECORD *m; + ATTR_RECORD *a; + VCN stop_vcn; + const runlist_element *stop_rl; + int err, mp_size, cur_max_mp_size, exp_max_mp_size, ret = -1; + BOOL finished_build; retry: - if (!na || !na->rl || from_vcn) { - errno = EINVAL; - ntfs_log_perror("%s: na=%p", __FUNCTION__, na); - return -1; - } + if (!na || !na->rl || from_vcn) { + errno = EINVAL; + ntfs_log_perror("%s: na=%p", __FUNCTION__, na); + return -1; + } - ntfs_log_trace("Entering for inode %llu, attr 0x%x\n", - (unsigned long long)na->ni->mft_no, na->type); + ntfs_log_trace("Entering for inode %llu, attr 0x%x\n", + (unsigned long long)na->ni->mft_no, na->type); - if (!NAttrNonResident(na)) { - errno = EINVAL; - ntfs_log_perror("%s: resident attribute", __FUNCTION__); - return -1; - } + if (!NAttrNonResident(na)) { + errno = EINVAL; + ntfs_log_perror("%s: resident attribute", __FUNCTION__); + return -1; + } - if (na->ni->nr_extents == -1) - base_ni = na->ni->base_ni; - else - base_ni = na->ni; + if (na->ni->nr_extents == -1) + base_ni = na->ni->base_ni; + else + base_ni = na->ni; - ctx = ntfs_attr_get_search_ctx(base_ni, NULL); - if (!ctx) - return -1; + ctx = ntfs_attr_get_search_ctx(base_ni, NULL); + if (!ctx) + return -1; - /* Fill attribute records with new mapping pairs. */ - stop_vcn = 0; - stop_rl = na->rl; - finished_build = FALSE; - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, from_vcn, NULL, 0, ctx)) { - a = ctx->attr; - m = ctx->mrec; - /* - * If runlist is updating not from the beginning, then set - * @stop_vcn properly, i.e. to the lowest vcn of record that - * contain @from_vcn. Also we do not need @from_vcn anymore, - * set it to 0 to make ntfs_attr_lookup enumerate attributes. - */ - if (from_vcn) { - LCN first_lcn; + /* Fill attribute records with new mapping pairs. */ + stop_vcn = 0; + stop_rl = na->rl; + finished_build = FALSE; + while (!ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, from_vcn, NULL, 0, ctx)) { + a = ctx->attr; + m = ctx->mrec; + /* + * If runlist is updating not from the beginning, then set + * @stop_vcn properly, i.e. to the lowest vcn of record that + * contain @from_vcn. Also we do not need @from_vcn anymore, + * set it to 0 to make ntfs_attr_lookup enumerate attributes. + */ + if (from_vcn) { + LCN first_lcn; - stop_vcn = sle64_to_cpu(a->lowest_vcn); - from_vcn = 0; - /* - * Check whether the first run we need to update is - * the last run in runlist, if so, then deallocate - * all attrubute extents starting this one. - */ - first_lcn = ntfs_rl_vcn_to_lcn(na->rl, stop_vcn); - if (first_lcn == LCN_EINVAL) { - errno = EIO; - ntfs_log_perror("Bad runlist"); - goto put_err_out; - } - if (first_lcn == LCN_ENOENT || - first_lcn == LCN_RL_NOT_MAPPED) - finished_build = TRUE; - } + stop_vcn = sle64_to_cpu(a->lowest_vcn); + from_vcn = 0; + /* + * Check whether the first run we need to update is + * the last run in runlist, if so, then deallocate + * all attrubute extents starting this one. + */ + first_lcn = ntfs_rl_vcn_to_lcn(na->rl, stop_vcn); + if (first_lcn == LCN_EINVAL) { + errno = EIO; + ntfs_log_perror("Bad runlist"); + goto put_err_out; + } + if (first_lcn == LCN_ENOENT || + first_lcn == LCN_RL_NOT_MAPPED) + finished_build = TRUE; + } - /* - * Check whether we finished mapping pairs build, if so mark - * extent as need to delete (by setting highest vcn to - * NTFS_VCN_DELETE_MARK (-2), we shall check it later and - * delete extent) and continue search. - */ - if (finished_build) { - ntfs_log_trace("Mark attr 0x%x for delete in inode " - "%lld.\n", (unsigned)le32_to_cpu(a->type), - (long long)ctx->ntfs_ino->mft_no); - a->highest_vcn = cpu_to_sle64(NTFS_VCN_DELETE_MARK); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - continue; - } + /* + * Check whether we finished mapping pairs build, if so mark + * extent as need to delete (by setting highest vcn to + * NTFS_VCN_DELETE_MARK (-2), we shall check it later and + * delete extent) and continue search. + */ + if (finished_build) { + ntfs_log_trace("Mark attr 0x%x for delete in inode " + "%lld.\n", (unsigned)le32_to_cpu(a->type), + (long long)ctx->ntfs_ino->mft_no); + a->highest_vcn = cpu_to_sle64(NTFS_VCN_DELETE_MARK); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + continue; + } - switch (ntfs_attr_update_meta(a, na, m, ctx)) { - case -1: - return -1; - case -2: - goto retry; - case -3: - goto put_err_out; - } + switch (ntfs_attr_update_meta(a, na, m, ctx)) { + case -1: return -1; + case -2: goto retry; + case -3: goto put_err_out; + } - /* - * Determine maximum possible length of mapping pairs, - * if we shall *not* expand space for mapping pairs. - */ - cur_max_mp_size = le32_to_cpu(a->length) - - le16_to_cpu(a->mapping_pairs_offset); - /* - * Determine maximum possible length of mapping pairs in the - * current mft record, if we shall expand space for mapping - * pairs. - */ - exp_max_mp_size = le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) + cur_max_mp_size; - /* Get the size for the rest of mapping pairs array. */ - mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, stop_rl, - stop_vcn, exp_max_mp_size); - if (mp_size <= 0) { - ntfs_log_perror("%s: get MP size failed", __FUNCTION__); - goto put_err_out; - } - /* Test mapping pairs for fitting in the current mft record. */ - if (mp_size > exp_max_mp_size) { - /* - * Mapping pairs of $ATTRIBUTE_LIST attribute must fit - * in the base mft record. Try to move out other - * attributes and try again. - */ - if (na->type == AT_ATTRIBUTE_LIST) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_free_space(na->ni, mp_size - - cur_max_mp_size)) { - ntfs_log_perror("Attribute list is too " - "big. Defragment the " - "volume\n"); - return -1; - } - goto retry; - } + /* + * Determine maximum possible length of mapping pairs, + * if we shall *not* expand space for mapping pairs. + */ + cur_max_mp_size = le32_to_cpu(a->length) - + le16_to_cpu(a->mapping_pairs_offset); + /* + * Determine maximum possible length of mapping pairs in the + * current mft record, if we shall expand space for mapping + * pairs. + */ + exp_max_mp_size = le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use) + cur_max_mp_size; + /* Get the size for the rest of mapping pairs array. */ + mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, stop_rl, + stop_vcn, exp_max_mp_size); + if (mp_size <= 0) { + ntfs_log_perror("%s: get MP size failed", __FUNCTION__); + goto put_err_out; + } + /* Test mapping pairs for fitting in the current mft record. */ + if (mp_size > exp_max_mp_size) { + /* + * Mapping pairs of $ATTRIBUTE_LIST attribute must fit + * in the base mft record. Try to move out other + * attributes and try again. + */ + if (na->type == AT_ATTRIBUTE_LIST) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_free_space(na->ni, mp_size - + cur_max_mp_size)) { + ntfs_log_perror("Attribute list is too " + "big. Defragment the " + "volume\n"); + return -1; + } + goto retry; + } - /* Add attribute list if it isn't present, and retry. */ - if (!NInoAttrList(base_ni)) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_add_attrlist(base_ni)) { - ntfs_log_perror("Can not add attrlist"); - return -1; - } - goto retry; - } + /* Add attribute list if it isn't present, and retry. */ + if (!NInoAttrList(base_ni)) { + ntfs_attr_put_search_ctx(ctx); + if (ntfs_inode_add_attrlist(base_ni)) { + ntfs_log_perror("Can not add attrlist"); + return -1; + } + goto retry; + } - /* - * Set mapping pairs size to maximum possible for this - * mft record. We shall write the rest of mapping pairs - * to another MFT records. - */ - mp_size = exp_max_mp_size; - } + /* + * Set mapping pairs size to maximum possible for this + * mft record. We shall write the rest of mapping pairs + * to another MFT records. + */ + mp_size = exp_max_mp_size; + } - /* Change space for mapping pairs if we need it. */ - if (((mp_size + 7) & ~7) != cur_max_mp_size) { - if (ntfs_attr_record_resize(m, a, - le16_to_cpu(a->mapping_pairs_offset) + - mp_size)) { - errno = EIO; - ntfs_log_perror("Failed to resize attribute"); - goto put_err_out; - } - } + /* Change space for mapping pairs if we need it. */ + if (((mp_size + 7) & ~7) != cur_max_mp_size) { + if (ntfs_attr_record_resize(m, a, + le16_to_cpu(a->mapping_pairs_offset) + + mp_size)) { + errno = EIO; + ntfs_log_perror("Failed to resize attribute"); + goto put_err_out; + } + } - /* Update lowest vcn. */ - a->lowest_vcn = cpu_to_sle64(stop_vcn); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - if ((ctx->ntfs_ino->nr_extents == -1 || - NInoAttrList(ctx->ntfs_ino)) && - ctx->attr->type != AT_ATTRIBUTE_LIST) { - ctx->al_entry->lowest_vcn = cpu_to_sle64(stop_vcn); - ntfs_attrlist_mark_dirty(ctx->ntfs_ino); - } + /* Update lowest vcn. */ + a->lowest_vcn = cpu_to_sle64(stop_vcn); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + if ((ctx->ntfs_ino->nr_extents == -1 || + NInoAttrList(ctx->ntfs_ino)) && + ctx->attr->type != AT_ATTRIBUTE_LIST) { + ctx->al_entry->lowest_vcn = cpu_to_sle64(stop_vcn); + ntfs_attrlist_mark_dirty(ctx->ntfs_ino); + } - /* - * Generate the new mapping pairs array directly into the - * correct destination, i.e. the attribute record itself. - */ - if (!ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + le16_to_cpu( - a->mapping_pairs_offset), mp_size, na->rl, - stop_vcn, &stop_rl)) - finished_build = TRUE; - if (stop_rl) - stop_vcn = stop_rl->vcn; - else - stop_vcn = 0; - if (!finished_build && errno != ENOSPC) { - ntfs_log_perror("Failed to build mapping pairs"); - goto put_err_out; - } - a->highest_vcn = cpu_to_sle64(stop_vcn - 1); - } - /* Check whether error occurred. */ - if (errno != ENOENT) { - ntfs_log_perror("%s: Attribute lookup failed", __FUNCTION__); - goto put_err_out; - } + /* + * Generate the new mapping pairs array directly into the + * correct destination, i.e. the attribute record itself. + */ + if (!ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + le16_to_cpu( + a->mapping_pairs_offset), mp_size, na->rl, + stop_vcn, &stop_rl)) + finished_build = TRUE; + if (stop_rl) + stop_vcn = stop_rl->vcn; + else + stop_vcn = 0; + if (!finished_build && errno != ENOSPC) { + ntfs_log_perror("Failed to build mapping pairs"); + goto put_err_out; + } + a->highest_vcn = cpu_to_sle64(stop_vcn - 1); + } + /* Check whether error occurred. */ + if (errno != ENOENT) { + ntfs_log_perror("%s: Attribute lookup failed", __FUNCTION__); + goto put_err_out; + } - /* Deallocate not used attribute extents and return with success. */ - if (finished_build) { - ntfs_attr_reinit_search_ctx(ctx); - ntfs_log_trace("Deallocate marked extents.\n"); - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (sle64_to_cpu(ctx->attr->highest_vcn) != - NTFS_VCN_DELETE_MARK) - continue; - /* Remove unused attribute record. */ - if (ntfs_attr_record_rm(ctx)) { - ntfs_log_perror("Could not remove unused attr"); - goto put_err_out; - } - ntfs_attr_reinit_search_ctx(ctx); - } - if (errno != ENOENT) { - ntfs_log_perror("%s: Attr lookup failed", __FUNCTION__); - goto put_err_out; - } - ntfs_log_trace("Deallocate done.\n"); - ntfs_attr_put_search_ctx(ctx); - goto ok; - } - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; + /* Deallocate not used attribute extents and return with success. */ + if (finished_build) { + ntfs_attr_reinit_search_ctx(ctx); + ntfs_log_trace("Deallocate marked extents.\n"); + while (!ntfs_attr_lookup(na->type, na->name, na->name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (sle64_to_cpu(ctx->attr->highest_vcn) != + NTFS_VCN_DELETE_MARK) + continue; + /* Remove unused attribute record. */ + if (ntfs_attr_record_rm(ctx)) { + ntfs_log_perror("Could not remove unused attr"); + goto put_err_out; + } + ntfs_attr_reinit_search_ctx(ctx); + } + if (errno != ENOENT) { + ntfs_log_perror("%s: Attr lookup failed", __FUNCTION__); + goto put_err_out; + } + ntfs_log_trace("Deallocate done.\n"); + ntfs_attr_put_search_ctx(ctx); + goto ok; + } + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; - /* Allocate new MFT records for the rest of mapping pairs. */ - while (1) { - /* Calculate size of rest mapping pairs. */ - mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, - na->rl, stop_vcn, INT_MAX); - if (mp_size <= 0) { - ntfs_log_perror("%s: get mp size failed", __FUNCTION__); - goto put_err_out; - } - /* Allocate new mft record. */ - ni = ntfs_mft_record_alloc(na->ni->vol, base_ni); - if (!ni) { - ntfs_log_perror("Could not allocate new MFT record"); - goto put_err_out; - } - m = ni->mrec; - /* - * If mapping size exceed available space, set them to - * possible maximum. - */ - cur_max_mp_size = le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) - - (offsetof(ATTR_RECORD, compressed_size) + - (((na->data_flags & ATTR_COMPRESSION_MASK) - || NAttrSparse(na)) ? - sizeof(a->compressed_size) : 0)) - - ((sizeof(ntfschar) * na->name_len + 7) & ~7); - if (mp_size > cur_max_mp_size) - mp_size = cur_max_mp_size; - /* Add attribute extent to new record. */ - err = ntfs_non_resident_attr_record_add(ni, na->type, - na->name, na->name_len, stop_vcn, mp_size, - na->data_flags); - if (err == -1) { - err = errno; - ntfs_log_perror("Could not add attribute extent"); - if (ntfs_mft_record_free(na->ni->vol, ni)) - ntfs_log_perror("Could not free MFT record"); - errno = err; - goto put_err_out; - } - a = (ATTR_RECORD*)((u8*)m + err); + /* Allocate new MFT records for the rest of mapping pairs. */ + while (1) { + /* Calculate size of rest mapping pairs. */ + mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, + na->rl, stop_vcn, INT_MAX); + if (mp_size <= 0) { + ntfs_log_perror("%s: get mp size failed", __FUNCTION__); + goto put_err_out; + } + /* Allocate new mft record. */ + ni = ntfs_mft_record_alloc(na->ni->vol, base_ni); + if (!ni) { + ntfs_log_perror("Could not allocate new MFT record"); + goto put_err_out; + } + m = ni->mrec; + /* + * If mapping size exceed available space, set them to + * possible maximum. + */ + cur_max_mp_size = le32_to_cpu(m->bytes_allocated) - + le32_to_cpu(m->bytes_in_use) - + (offsetof(ATTR_RECORD, compressed_size) + + (((na->data_flags & ATTR_COMPRESSION_MASK) + || NAttrSparse(na)) ? + sizeof(a->compressed_size) : 0)) - + ((sizeof(ntfschar) * na->name_len + 7) & ~7); + if (mp_size > cur_max_mp_size) + mp_size = cur_max_mp_size; + /* Add attribute extent to new record. */ + err = ntfs_non_resident_attr_record_add(ni, na->type, + na->name, na->name_len, stop_vcn, mp_size, + na->data_flags); + if (err == -1) { + err = errno; + ntfs_log_perror("Could not add attribute extent"); + if (ntfs_mft_record_free(na->ni->vol, ni)) + ntfs_log_perror("Could not free MFT record"); + errno = err; + goto put_err_out; + } + a = (ATTR_RECORD*)((u8*)m + err); - err = ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), mp_size, na->rl, - stop_vcn, &stop_rl); - if (stop_rl) - stop_vcn = stop_rl->vcn; - else - stop_vcn = 0; - if (err < 0 && errno != ENOSPC) { - err = errno; - ntfs_log_perror("Failed to build MP"); - if (ntfs_mft_record_free(na->ni->vol, ni)) - ntfs_log_perror("Couldn't free MFT record"); - errno = err; - goto put_err_out; - } - a->highest_vcn = cpu_to_sle64(stop_vcn - 1); - ntfs_inode_mark_dirty(ni); - /* All mapping pairs has been written. */ - if (!err) - break; - } + err = ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + + le16_to_cpu(a->mapping_pairs_offset), mp_size, na->rl, + stop_vcn, &stop_rl); + if (stop_rl) + stop_vcn = stop_rl->vcn; + else + stop_vcn = 0; + if (err < 0 && errno != ENOSPC) { + err = errno; + ntfs_log_perror("Failed to build MP"); + if (ntfs_mft_record_free(na->ni->vol, ni)) + ntfs_log_perror("Couldn't free MFT record"); + errno = err; + goto put_err_out; + } + a->highest_vcn = cpu_to_sle64(stop_vcn - 1); + ntfs_inode_mark_dirty(ni); + /* All mapping pairs has been written. */ + if (!err) + break; + } ok: - ret = 0; + ret = 0; out: - return ret; + return ret; put_err_out: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - goto out; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + goto out; } #undef NTFS_VCN_DELETE_MARK @@ -5155,13 +5198,14 @@ put_err_out: * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST * or there is no free MFT records left to allocate. */ -int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_attr_update_mapping_pairs_i(na, from_vcn); - ntfs_log_leave("\n"); - return ret; +int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) +{ + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_attr_update_mapping_pairs_i(na, from_vcn); + ntfs_log_leave("\n"); + return ret; } /** @@ -5176,123 +5220,124 @@ int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) { * ENOMEM - Not enough memory to complete operation. * ERANGE - @newsize is not valid for the attribute type of @na. */ -static int ntfs_non_resident_attr_shrink(ntfs_attr *na, const s64 newsize) { - ntfs_volume *vol; - ntfs_attr_search_ctx *ctx; - VCN first_free_vcn; - s64 nr_freed_clusters; - int err; +static int ntfs_non_resident_attr_shrink(ntfs_attr *na, const s64 newsize) +{ + ntfs_volume *vol; + ntfs_attr_search_ctx *ctx; + VCN first_free_vcn; + s64 nr_freed_clusters; + int err; - ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", (unsigned long long) - na->ni->mft_no, na->type, (long long)newsize); + ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", (unsigned long long) + na->ni->mft_no, na->type, (long long)newsize); - vol = na->ni->vol; + vol = na->ni->vol; - /* - * Check the attribute type and the corresponding minimum size - * against @newsize and fail if @newsize is too small. - */ - if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { - if (errno == ERANGE) { - ntfs_log_trace("Eeek! Size bounds check failed. " - "Aborting...\n"); - } else if (errno == ENOENT) - errno = EIO; - return -1; - } + /* + * Check the attribute type and the corresponding minimum size + * against @newsize and fail if @newsize is too small. + */ + if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { + if (errno == ERANGE) { + ntfs_log_trace("Eeek! Size bounds check failed. " + "Aborting...\n"); + } else if (errno == ENOENT) + errno = EIO; + return -1; + } - /* The first cluster outside the new allocation. */ - first_free_vcn = (newsize + vol->cluster_size - 1) >> - vol->cluster_size_bits; - /* - * Compare the new allocation with the old one and only deallocate - * clusters if there is a change. - */ - if ((na->allocated_size >> vol->cluster_size_bits) != first_free_vcn) { - if (ntfs_attr_map_whole_runlist(na)) { - ntfs_log_trace("Eeek! ntfs_attr_map_whole_runlist " - "failed.\n"); - return -1; - } - /* Deallocate all clusters starting with the first free one. */ - nr_freed_clusters = ntfs_cluster_free(vol, na, first_free_vcn, - -1); - if (nr_freed_clusters < 0) { - ntfs_log_trace("Eeek! Freeing of clusters failed. " - "Aborting...\n"); - return -1; - } + /* The first cluster outside the new allocation. */ + first_free_vcn = (newsize + vol->cluster_size - 1) >> + vol->cluster_size_bits; + /* + * Compare the new allocation with the old one and only deallocate + * clusters if there is a change. + */ + if ((na->allocated_size >> vol->cluster_size_bits) != first_free_vcn) { + if (ntfs_attr_map_whole_runlist(na)) { + ntfs_log_trace("Eeek! ntfs_attr_map_whole_runlist " + "failed.\n"); + return -1; + } + /* Deallocate all clusters starting with the first free one. */ + nr_freed_clusters = ntfs_cluster_free(vol, na, first_free_vcn, + -1); + if (nr_freed_clusters < 0) { + ntfs_log_trace("Eeek! Freeing of clusters failed. " + "Aborting...\n"); + return -1; + } - /* Truncate the runlist itself. */ - if (ntfs_rl_truncate(&na->rl, first_free_vcn)) { - /* - * Failed to truncate the runlist, so just throw it - * away, it will be mapped afresh on next use. - */ - free(na->rl); - na->rl = NULL; - ntfs_log_trace("Eeek! Run list truncation failed.\n"); - return -1; - } + /* Truncate the runlist itself. */ + if (ntfs_rl_truncate(&na->rl, first_free_vcn)) { + /* + * Failed to truncate the runlist, so just throw it + * away, it will be mapped afresh on next use. + */ + free(na->rl); + na->rl = NULL; + ntfs_log_trace("Eeek! Run list truncation failed.\n"); + return -1; + } - /* Prepare to mapping pairs update. */ - na->allocated_size = first_free_vcn << vol->cluster_size_bits; - /* Write mapping pairs for new runlist. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*first_free_vcn*/)) { - ntfs_log_trace("Eeek! Mapping pairs update failed. " - "Leaving inconstant metadata. " - "Run chkdsk.\n"); - return -1; - } - } + /* Prepare to mapping pairs update. */ + na->allocated_size = first_free_vcn << vol->cluster_size_bits; + /* Write mapping pairs for new runlist. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*first_free_vcn*/)) { + ntfs_log_trace("Eeek! Mapping pairs update failed. " + "Leaving inconstant metadata. " + "Run chkdsk.\n"); + return -1; + } + } - /* Get the first attribute record. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; + /* Get the first attribute record. */ + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - err = errno; - if (err == ENOENT) - err = EIO; - ntfs_log_trace("Eeek! Lookup of first attribute extent failed. " - "Leaving inconstant metadata.\n"); - goto put_err_out; - } + if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + err = errno; + if (err == ENOENT) + err = EIO; + ntfs_log_trace("Eeek! Lookup of first attribute extent failed. " + "Leaving inconstant metadata.\n"); + goto put_err_out; + } - /* Update data and initialized size. */ - na->data_size = newsize; - ctx->attr->data_size = cpu_to_sle64(newsize); - if (newsize < na->initialized_size) { - na->initialized_size = newsize; - ctx->attr->initialized_size = cpu_to_sle64(newsize); - } - /* Update data size in the index. */ - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - NInoFileNameSetDirty(na->ni); - } + /* Update data and initialized size. */ + na->data_size = newsize; + ctx->attr->data_size = cpu_to_sle64(newsize); + if (newsize < na->initialized_size) { + na->initialized_size = newsize; + ctx->attr->initialized_size = cpu_to_sle64(newsize); + } + /* Update data size in the index. */ + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + na->ni->data_size = na->data_size; + NInoFileNameSetDirty(na->ni); + } - /* If the attribute now has zero size, make it resident. */ - if (!newsize) { - if (ntfs_attr_make_resident(na, ctx)) { - /* If couldn't make resident, just continue. */ - if (errno != EPERM) - ntfs_log_error("Failed to make attribute " - "resident. Leaving as is...\n"); - } - } + /* If the attribute now has zero size, make it resident. */ + if (!newsize) { + if (ntfs_attr_make_resident(na, ctx)) { + /* If couldn't make resident, just continue. */ + if (errno != EPERM) + ntfs_log_error("Failed to make attribute " + "resident. Leaving as is...\n"); + } + } - /* Set the inode dirty so it is written out later. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - /* Done! */ - ntfs_attr_put_search_ctx(ctx); - return 0; + /* Set the inode dirty so it is written out later. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + /* Done! */ + ntfs_attr_put_search_ctx(ctx); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } /** @@ -5309,207 +5354,209 @@ put_err_out: * ERANGE - @newsize is not valid for the attribute type of @na. * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. */ -static int ntfs_non_resident_attr_expand_i(ntfs_attr *na, const s64 newsize) { - LCN lcn_seek_from; - VCN first_free_vcn; - ntfs_volume *vol; - ntfs_attr_search_ctx *ctx; - runlist *rl, *rln; - s64 org_alloc_size; - int err; +static int ntfs_non_resident_attr_expand_i(ntfs_attr *na, const s64 newsize) +{ + LCN lcn_seek_from; + VCN first_free_vcn; + ntfs_volume *vol; + ntfs_attr_search_ctx *ctx; + runlist *rl, *rln; + s64 org_alloc_size; + int err; - ntfs_log_trace("Inode %lld, attr 0x%x, new size %lld old size %lld\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)newsize, (long long)na->data_size); + ntfs_log_trace("Inode %lld, attr 0x%x, new size %lld old size %lld\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)newsize, (long long)na->data_size); - vol = na->ni->vol; + vol = na->ni->vol; - /* - * Check the attribute type and the corresponding maximum size - * against @newsize and fail if @newsize is too big. - */ - if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { - if (errno == ENOENT) - errno = EIO; - ntfs_log_perror("%s: bounds check failed", __FUNCTION__); - return -1; - } + /* + * Check the attribute type and the corresponding maximum size + * against @newsize and fail if @newsize is too big. + */ + if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { + if (errno == ENOENT) + errno = EIO; + ntfs_log_perror("%s: bounds check failed", __FUNCTION__); + return -1; + } - /* Save for future use. */ - org_alloc_size = na->allocated_size; - /* The first cluster outside the new allocation. */ - first_free_vcn = (newsize + vol->cluster_size - 1) >> - vol->cluster_size_bits; - /* - * Compare the new allocation with the old one and only allocate - * clusters if there is a change. - */ - if ((na->allocated_size >> vol->cluster_size_bits) < first_free_vcn) { - if (ntfs_attr_map_whole_runlist(na)) { - ntfs_log_perror("ntfs_attr_map_whole_runlist failed"); - return -1; - } + /* Save for future use. */ + org_alloc_size = na->allocated_size; + /* The first cluster outside the new allocation. */ + first_free_vcn = (newsize + vol->cluster_size - 1) >> + vol->cluster_size_bits; + /* + * Compare the new allocation with the old one and only allocate + * clusters if there is a change. + */ + if ((na->allocated_size >> vol->cluster_size_bits) < first_free_vcn) { + if (ntfs_attr_map_whole_runlist(na)) { + ntfs_log_perror("ntfs_attr_map_whole_runlist failed"); + return -1; + } - /* - * If we extend $DATA attribute on NTFS 3+ volume, we can add - * sparse runs instead of real allocation of clusters. - */ - if (na->type == AT_DATA && vol->major_ver >= 3) { - rl = ntfs_malloc(0x1000); - if (!rl) - return -1; + /* + * If we extend $DATA attribute on NTFS 3+ volume, we can add + * sparse runs instead of real allocation of clusters. + */ + if (na->type == AT_DATA && vol->major_ver >= 3) { + rl = ntfs_malloc(0x1000); + if (!rl) + return -1; + + rl[0].vcn = (na->allocated_size >> + vol->cluster_size_bits); + rl[0].lcn = LCN_HOLE; + rl[0].length = first_free_vcn - + (na->allocated_size >> vol->cluster_size_bits); + rl[1].vcn = first_free_vcn; + rl[1].lcn = LCN_ENOENT; + rl[1].length = 0; + } else { + /* + * Determine first after last LCN of attribute. + * We will start seek clusters from this LCN to avoid + * fragmentation. If there are no valid LCNs in the + * attribute let the cluster allocator choose the + * starting LCN. + */ + lcn_seek_from = -1; + if (na->rl->length) { + /* Seek to the last run list element. */ + for (rl = na->rl; (rl + 1)->length; rl++) + ; + /* + * If the last LCN is a hole or similar seek + * back to last valid LCN. + */ + while (rl->lcn < 0 && rl != na->rl) + rl--; + /* + * Only set lcn_seek_from it the LCN is valid. + */ + if (rl->lcn >= 0) + lcn_seek_from = rl->lcn + rl->length; + } - rl[0].vcn = (na->allocated_size >> - vol->cluster_size_bits); - rl[0].lcn = LCN_HOLE; - rl[0].length = first_free_vcn - - (na->allocated_size >> vol->cluster_size_bits); - rl[1].vcn = first_free_vcn; - rl[1].lcn = LCN_ENOENT; - rl[1].length = 0; - } else { - /* - * Determine first after last LCN of attribute. - * We will start seek clusters from this LCN to avoid - * fragmentation. If there are no valid LCNs in the - * attribute let the cluster allocator choose the - * starting LCN. - */ - lcn_seek_from = -1; - if (na->rl->length) { - /* Seek to the last run list element. */ - for (rl = na->rl; (rl + 1)->length; rl++) - ; - /* - * If the last LCN is a hole or similar seek - * back to last valid LCN. - */ - while (rl->lcn < 0 && rl != na->rl) - rl--; - /* - * Only set lcn_seek_from it the LCN is valid. - */ - if (rl->lcn >= 0) - lcn_seek_from = rl->lcn + rl->length; - } + rl = ntfs_cluster_alloc(vol, na->allocated_size >> + vol->cluster_size_bits, first_free_vcn - + (na->allocated_size >> + vol->cluster_size_bits), lcn_seek_from, + DATA_ZONE); + if (!rl) { + ntfs_log_perror("Cluster allocation failed " + "(%lld)", + (long long)first_free_vcn - + ((long long)na->allocated_size >> + vol->cluster_size_bits)); + return -1; + } + } - rl = ntfs_cluster_alloc(vol, na->allocated_size >> - vol->cluster_size_bits, first_free_vcn - - (na->allocated_size >> - vol->cluster_size_bits), lcn_seek_from, - DATA_ZONE); - if (!rl) { - ntfs_log_perror("Cluster allocation failed " - "(%lld)", - (long long)first_free_vcn - - ((long long)na->allocated_size >> - vol->cluster_size_bits)); - return -1; - } - } + /* Append new clusters to attribute runlist. */ + rln = ntfs_runlists_merge(na->rl, rl); + if (!rln) { + /* Failed, free just allocated clusters. */ + err = errno; + ntfs_log_perror("Run list merge failed"); + ntfs_cluster_free_from_rl(vol, rl); + free(rl); + errno = err; + return -1; + } + na->rl = rln; - /* Append new clusters to attribute runlist. */ - rln = ntfs_runlists_merge(na->rl, rl); - if (!rln) { - /* Failed, free just allocated clusters. */ - err = errno; - ntfs_log_perror("Run list merge failed"); - ntfs_cluster_free_from_rl(vol, rl); - free(rl); - errno = err; - return -1; - } - na->rl = rln; - - /* Prepare to mapping pairs update. */ - na->allocated_size = first_free_vcn << vol->cluster_size_bits; - /* Write mapping pairs for new runlist. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> + /* Prepare to mapping pairs update. */ + na->allocated_size = first_free_vcn << vol->cluster_size_bits; + /* Write mapping pairs for new runlist. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> vol->cluster_size_bits*/)) { - err = errno; - ntfs_log_perror("Mapping pairs update failed"); - goto rollback; - } - } + err = errno; + ntfs_log_perror("Mapping pairs update failed"); + goto rollback; + } + } - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) { - err = errno; - if (na->allocated_size == org_alloc_size) { - errno = err; - return -1; - } else - goto rollback; - } + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) { + err = errno; + if (na->allocated_size == org_alloc_size) { + errno = err; + return -1; + } else + goto rollback; + } - if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - err = errno; - ntfs_log_perror("Lookup of first attribute extent failed"); - if (err == ENOENT) - err = EIO; - if (na->allocated_size != org_alloc_size) { - ntfs_attr_put_search_ctx(ctx); - goto rollback; - } else - goto put_err_out; - } + if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + err = errno; + ntfs_log_perror("Lookup of first attribute extent failed"); + if (err == ENOENT) + err = EIO; + if (na->allocated_size != org_alloc_size) { + ntfs_attr_put_search_ctx(ctx); + goto rollback; + } else + goto put_err_out; + } - /* Update data size. */ - na->data_size = newsize; - ctx->attr->data_size = cpu_to_sle64(newsize); - /* Update data size in the index. */ - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - NInoFileNameSetDirty(na->ni); - } - /* Set the inode dirty so it is written out later. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - /* Done! */ - ntfs_attr_put_search_ctx(ctx); - return 0; + /* Update data size. */ + na->data_size = newsize; + ctx->attr->data_size = cpu_to_sle64(newsize); + /* Update data size in the index. */ + if (na->type == AT_DATA && na->name == AT_UNNAMED) { + na->ni->data_size = na->data_size; + NInoFileNameSetDirty(na->ni); + } + /* Set the inode dirty so it is written out later. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + /* Done! */ + ntfs_attr_put_search_ctx(ctx); + return 0; rollback: - /* Free allocated clusters. */ - if (ntfs_cluster_free(vol, na, org_alloc_size >> - vol->cluster_size_bits, -1) < 0) { - err = EIO; - ntfs_log_perror("Leaking clusters"); - } - /* Now, truncate the runlist itself. */ - if (ntfs_rl_truncate(&na->rl, org_alloc_size >> - vol->cluster_size_bits)) { - /* - * Failed to truncate the runlist, so just throw it away, it - * will be mapped afresh on next use. - */ - free(na->rl); - na->rl = NULL; - ntfs_log_perror("Couldn't truncate runlist. Rollback failed"); - } else { - /* Prepare to mapping pairs update. */ - na->allocated_size = org_alloc_size; - /* Restore mapping pairs. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> + /* Free allocated clusters. */ + if (ntfs_cluster_free(vol, na, org_alloc_size >> + vol->cluster_size_bits, -1) < 0) { + err = EIO; + ntfs_log_perror("Leaking clusters"); + } + /* Now, truncate the runlist itself. */ + if (ntfs_rl_truncate(&na->rl, org_alloc_size >> + vol->cluster_size_bits)) { + /* + * Failed to truncate the runlist, so just throw it away, it + * will be mapped afresh on next use. + */ + free(na->rl); + na->rl = NULL; + ntfs_log_perror("Couldn't truncate runlist. Rollback failed"); + } else { + /* Prepare to mapping pairs update. */ + na->allocated_size = org_alloc_size; + /* Restore mapping pairs. */ + if (ntfs_attr_update_mapping_pairs(na, 0 /*na->allocated_size >> vol->cluster_size_bits*/)) { - ntfs_log_perror("Failed to restore old mapping pairs"); - } - } - errno = err; - return -1; + ntfs_log_perror("Failed to restore old mapping pairs"); + } + } + errno = err; + return -1; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } -static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_non_resident_attr_expand_i(na, newsize); - ntfs_log_leave("\n"); - return ret; +static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) +{ + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_non_resident_attr_expand_i(na, newsize); + ntfs_log_leave("\n"); + return ret; } /** @@ -5532,81 +5579,82 @@ static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) { * EOPNOTSUPP - The desired resize is not implemented yet. * EACCES - Encrypted attribute. */ -int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize) { - int ret = STATUS_ERROR; - s64 fullsize; - BOOL compressed; +int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize) +{ + int ret = STATUS_ERROR; + s64 fullsize; + BOOL compressed; - if (!na || newsize < 0 || - (na->ni->mft_no == FILE_MFT && na->type == AT_DATA)) { - ntfs_log_trace("Invalid arguments passed.\n"); - errno = EINVAL; - return STATUS_ERROR; - } + if (!na || newsize < 0 || + (na->ni->mft_no == FILE_MFT && na->type == AT_DATA)) { + ntfs_log_trace("Invalid arguments passed.\n"); + errno = EINVAL; + return STATUS_ERROR; + } - ntfs_log_enter("Entering for inode %lld, attr 0x%x, size %lld\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)newsize); + ntfs_log_enter("Entering for inode %lld, attr 0x%x, size %lld\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)newsize); - if (na->data_size == newsize) { - ntfs_log_trace("Size is already ok\n"); - ret = STATUS_OK; - goto out; - } - /* - * Encrypted attributes are not supported. We return access denied, - * which is what Windows NT4 does, too. - */ - if (na->data_flags & ATTR_IS_ENCRYPTED) { - errno = EACCES; - ntfs_log_info("Failed to truncate encrypted attribute"); - goto out; - } - /* - * TODO: Implement making handling of compressed attributes. - * Currently we can only expand the attribute or delete it, - * and only for ATTR_IS_COMPRESSED. This is however possible - * for resident attributes when there is no open fuse context - * (important case : $INDEX_ROOT:$I30) - */ - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - if (compressed - && NAttrNonResident(na) - && (((na->data_flags & ATTR_COMPRESSION_MASK) != ATTR_IS_COMPRESSED) - || (newsize && (newsize < na->data_size)))) { - errno = EOPNOTSUPP; - ntfs_log_perror("Failed to truncate compressed attribute"); - goto out; - } - if (NAttrNonResident(na)) { - /* - * For compressed data, the last block must be fully - * allocated, and we do not known the size of compression - * block until the attribute has been made non-resident. - * Moreover we can only process a single compression - * block at a time (from where we are about to write), - * so we silently do not allocate more. - * - * Note : do not request truncate on compressed files - * unless being able to face the consequences ! - */ - if (compressed && newsize) - fullsize = (na->initialized_size - | (na->compression_block_size - 1)) + 1; - else - fullsize = newsize; - if (fullsize > na->data_size) - ret = ntfs_non_resident_attr_expand(na, fullsize); - else - ret = ntfs_non_resident_attr_shrink(na, fullsize); - } else - ret = ntfs_resident_attr_resize(na, newsize); -out: - ntfs_log_leave("Return status %d\n", ret); - return ret; + if (na->data_size == newsize) { + ntfs_log_trace("Size is already ok\n"); + ret = STATUS_OK; + goto out; + } + /* + * Encrypted attributes are not supported. We return access denied, + * which is what Windows NT4 does, too. + */ + if (na->data_flags & ATTR_IS_ENCRYPTED) { + errno = EACCES; + ntfs_log_info("Failed to truncate encrypted attribute"); + goto out; + } + /* + * TODO: Implement making handling of compressed attributes. + * Currently we can only expand the attribute or delete it, + * and only for ATTR_IS_COMPRESSED. This is however possible + * for resident attributes when there is no open fuse context + * (important case : $INDEX_ROOT:$I30) + */ + compressed = (na->data_flags & ATTR_COMPRESSION_MASK) + != const_cpu_to_le16(0); + if (compressed + && NAttrNonResident(na) + && (((na->data_flags & ATTR_COMPRESSION_MASK) != ATTR_IS_COMPRESSED) + || (newsize && (newsize < na->data_size)))) { + errno = EOPNOTSUPP; + ntfs_log_perror("Failed to truncate compressed attribute"); + goto out; + } + if (NAttrNonResident(na)) { + /* + * For compressed data, the last block must be fully + * allocated, and we do not known the size of compression + * block until the attribute has been made non-resident. + * Moreover we can only process a single compression + * block at a time (from where we are about to write), + * so we silently do not allocate more. + * + * Note : do not request truncate on compressed files + * unless being able to face the consequences ! + */ + if (compressed && newsize) + fullsize = (na->initialized_size + | (na->compression_block_size - 1)) + 1; + else + fullsize = newsize; + if (fullsize > na->data_size) + ret = ntfs_non_resident_attr_expand(na, fullsize); + else + ret = ntfs_non_resident_attr_shrink(na, fullsize); + } else + ret = ntfs_resident_attr_resize(na, newsize); +out: + ntfs_log_leave("Return status %d\n", ret); + return ret; } - + /* * Stuff a hole in a compressed file * @@ -5617,80 +5665,81 @@ out: * -1 if it failed (as explained in errno) */ -static int stuff_hole(ntfs_attr *na, const s64 pos) { - s64 size; - s64 begin_size; - s64 end_size; - char *buf; - int ret; +static int stuff_hole(ntfs_attr *na, const s64 pos) +{ + s64 size; + s64 begin_size; + s64 end_size; + char *buf; + int ret; - ret = 0; - /* - * If the attribute is resident, the compression block size - * is not defined yet and we can make no decision. - * So we first try resizing to the target and if the - * attribute is still resident, we're done - */ - if (!NAttrNonResident(na)) { - ret = ntfs_resident_attr_resize(na, pos); - if (!ret && !NAttrNonResident(na)) - na->initialized_size = na->data_size = pos; - } - if (!ret && NAttrNonResident(na)) { - /* does the hole span over several compression block ? */ - if ((pos ^ na->initialized_size) - & ~(na->compression_block_size - 1)) { - begin_size = ((na->initialized_size - 1) - | (na->compression_block_size - 1)) - + 1 - na->initialized_size; - end_size = pos & (na->compression_block_size - 1); - size = (begin_size > end_size ? begin_size : end_size); - } else { - /* short stuffing in a single compression block */ - begin_size = size = pos - na->initialized_size; - end_size = 0; - } - if (size) - buf = (char*)ntfs_malloc(size); - else - buf = (char*)NULL; - if (buf || !size) { - memset(buf,0,size); - /* stuff into current block */ - if (begin_size - && (ntfs_attr_pwrite(na, - na->initialized_size, begin_size, buf) - != begin_size)) - ret = -1; - /* create an unstuffed hole */ - if (!ret - && ((na->initialized_size + end_size) < pos) - && ntfs_non_resident_attr_expand(na, - pos - end_size)) - ret = -1; - else - na->initialized_size - = na->data_size = pos - end_size; - /* stuff into the target block */ - if (!ret && end_size - && (ntfs_attr_pwrite(na, - na->initialized_size, end_size, buf) - != end_size)) - ret = -1; - if (buf) - free(buf); - } else - ret = -1; - } - /* make absolutely sure we have reached the target */ - if (!ret && (na->initialized_size != pos)) { - ntfs_log_error("Failed to stuff a compressed file" - "target %lld reached %lld\n", - (long long)pos, (long long)na->initialized_size); - errno = EIO; - ret = -1; - } - return (ret); + ret = 0; + /* + * If the attribute is resident, the compression block size + * is not defined yet and we can make no decision. + * So we first try resizing to the target and if the + * attribute is still resident, we're done + */ + if (!NAttrNonResident(na)) { + ret = ntfs_resident_attr_resize(na, pos); + if (!ret && !NAttrNonResident(na)) + na->initialized_size = na->data_size = pos; + } + if (!ret && NAttrNonResident(na)) { + /* does the hole span over several compression block ? */ + if ((pos ^ na->initialized_size) + & ~(na->compression_block_size - 1)) { + begin_size = ((na->initialized_size - 1) + | (na->compression_block_size - 1)) + + 1 - na->initialized_size; + end_size = pos & (na->compression_block_size - 1); + size = (begin_size > end_size ? begin_size : end_size); + } else { + /* short stuffing in a single compression block */ + begin_size = size = pos - na->initialized_size; + end_size = 0; + } + if (size) + buf = (char*)ntfs_malloc(size); + else + buf = (char*)NULL; + if (buf || !size) { + memset(buf,0,size); + /* stuff into current block */ + if (begin_size + && (ntfs_attr_pwrite(na, + na->initialized_size, begin_size, buf) + != begin_size)) + ret = -1; + /* create an unstuffed hole */ + if (!ret + && ((na->initialized_size + end_size) < pos) + && ntfs_non_resident_attr_expand(na, + pos - end_size)) + ret = -1; + else + na->initialized_size + = na->data_size = pos - end_size; + /* stuff into the target block */ + if (!ret && end_size + && (ntfs_attr_pwrite(na, + na->initialized_size, end_size, buf) + != end_size)) + ret = -1; + if (buf) + free(buf); + } else + ret = -1; + } + /* make absolutely sure we have reached the target */ + if (!ret && (na->initialized_size != pos)) { + ntfs_log_error("Failed to stuff a compressed file" + "target %lld reached %lld\n", + (long long)pos, (long long)na->initialized_size); + errno = EIO; + ret = -1; + } + return (ret); } /** @@ -5699,103 +5748,106 @@ static int stuff_hole(ntfs_attr *na, const s64 pos) { * @type: attribute type * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL * @name_len: length of attribute @name in Unicode characters (if @name given) - * @data_size: if non-NULL then store here the data size + * @data_size: if non-NULL then store here the data size * * This function will read the entire content of an ntfs attribute. * If @name is AT_UNNAMED then look specifically for an unnamed attribute. - * If @name is NULL then the attribute could be either named or not. + * If @name is NULL then the attribute could be either named or not. * In both those cases @name_len is not used at all. * - * On success a buffer is allocated with the content of the attribute + * On success a buffer is allocated with the content of the attribute * and which needs to be freed when it's not needed anymore. If the * @data_size parameter is non-NULL then the data size is set there. * * On error NULL is returned with errno set to the error code. */ void *ntfs_attr_readall(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len, s64 *data_size) { - ntfs_attr *na; - void *data, *ret = NULL; - s64 size; - - ntfs_log_enter("Entering\n"); - - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - ntfs_log_perror("ntfs_attr_open failed"); - goto err_exit; - } - data = ntfs_malloc(na->data_size); - if (!data) - goto out; - - size = ntfs_attr_pread(na, 0, na->data_size, data); - if (size != na->data_size) { - ntfs_log_perror("ntfs_attr_pread failed"); - free(data); - goto out; - } - ret = data; - if (data_size) - *data_size = size; + ntfschar *name, u32 name_len, s64 *data_size) +{ + ntfs_attr *na; + void *data, *ret = NULL; + s64 size; + + ntfs_log_enter("Entering\n"); + + na = ntfs_attr_open(ni, type, name, name_len); + if (!na) { + ntfs_log_perror("ntfs_attr_open failed"); + goto err_exit; + } + data = ntfs_malloc(na->data_size); + if (!data) + goto out; + + size = ntfs_attr_pread(na, 0, na->data_size, data); + if (size != na->data_size) { + ntfs_log_perror("ntfs_attr_pread failed"); + free(data); + goto out; + } + ret = data; + if (data_size) + *data_size = size; out: - ntfs_attr_close(na); + ntfs_attr_close(na); err_exit: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) { - ntfs_attr_search_ctx *ctx; - int ret; + u32 name_len) +{ + ntfs_attr_search_ctx *ctx; + int ret; + + ntfs_log_trace("Entering\n"); + + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return 0; + + ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, 0, NULL, 0, + ctx); - ntfs_log_trace("Entering\n"); - - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return 0; - - ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, 0, NULL, 0, - ctx); - - ntfs_attr_put_search_ctx(ctx); - - return !ret; + ntfs_attr_put_search_ctx(ctx); + + return !ret; } -int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) { - ntfs_attr *na; - int ret; +int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, + u32 name_len) +{ + ntfs_attr *na; + int ret; - ntfs_log_trace("Entering\n"); - - if (!ni) { - ntfs_log_error("%s: NULL inode pointer", __FUNCTION__); - errno = EINVAL; - return -1; - } - - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - /* do not log removal of non-existent stream */ - if (type != AT_DATA) { - ntfs_log_perror("Failed to open attribute 0x%02x of inode " - "0x%llx", type, (unsigned long long)ni->mft_no); - } - return -1; - } - - ret = ntfs_attr_rm(na); - if (ret) - ntfs_log_perror("Failed to remove attribute 0x%02x of inode " - "0x%llx", type, (unsigned long long)ni->mft_no); - ntfs_attr_close(na); - - return ret; + ntfs_log_trace("Entering\n"); + + if (!ni) { + ntfs_log_error("%s: NULL inode pointer", __FUNCTION__); + errno = EINVAL; + return -1; + } + + na = ntfs_attr_open(ni, type, name, name_len); + if (!na) { + /* do not log removal of non-existent stream */ + if (type != AT_DATA) { + ntfs_log_perror("Failed to open attribute 0x%02x of inode " + "0x%llx", type, (unsigned long long)ni->mft_no); + } + return -1; + } + + ret = ntfs_attr_rm(na); + if (ret) + ntfs_log_perror("Failed to remove attribute 0x%02x of inode " + "0x%llx", type, (unsigned long long)ni->mft_no); + ntfs_attr_close(na); + + return ret; } /* Below macros are 32-bit ready. */ @@ -5804,59 +5856,58 @@ int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, (((x) >> 3) & 0x11111111)) #define BITCOUNT(x) (((BCX(x) + (BCX(x) >> 4)) & 0x0F0F0F0F) % 255) -static u8 *ntfs_init_lut256(void) { - int i; - u8 *lut; - - lut = ntfs_malloc(256); - if (lut) - for (i = 0; i < 256; i++) - *(lut + i) = 8 - BITCOUNT(i); - return lut; +static u8 *ntfs_init_lut256(void) +{ + int i; + u8 *lut; + + lut = ntfs_malloc(256); + if (lut) + for(i = 0; i < 256; i++) + *(lut + i) = 8 - BITCOUNT(i); + return lut; } -s64 ntfs_attr_get_free_bits(ntfs_attr *na) { - u8 *buf, *lut; - s64 br = 0; - s64 total = 0; - s64 nr_free = 0; +s64 ntfs_attr_get_free_bits(ntfs_attr *na) +{ + u8 *buf, *lut; + s64 br = 0; + s64 total = 0; + s64 nr_free = 0; - lut = ntfs_init_lut256(); - if (!lut) - return -1; + lut = ntfs_init_lut256(); + if (!lut) + return -1; + + buf = ntfs_malloc(65536); + if (!buf) + goto out; - buf = ntfs_malloc(65536); - if (!buf) - goto out; - - while (1) { - u32 *p; - br = ntfs_attr_pread(na, total, 65536, buf); - if (br <= 0) - break; - total += br; - p = (u32 *)buf + br / 4 - 1; - for (; (u8 *)p >= buf; p--) { - nr_free += lut[ *p & 255] + - lut[(*p >> 8) & 255] + - lut[(*p >> 16) & 255] + - lut[(*p >> 24) ]; - } - switch (br % 4) { - case 3: - nr_free += lut[*(buf + br - 3)]; - case 2: - nr_free += lut[*(buf + br - 2)]; - case 1: - nr_free += lut[*(buf + br - 1)]; - } - } - free(buf); + while (1) { + u32 *p; + br = ntfs_attr_pread(na, total, 65536, buf); + if (br <= 0) + break; + total += br; + p = (u32 *)buf + br / 4 - 1; + for (; (u8 *)p >= buf; p--) { + nr_free += lut[ *p & 255] + + lut[(*p >> 8) & 255] + + lut[(*p >> 16) & 255] + + lut[(*p >> 24) ]; + } + switch (br % 4) { + case 3: nr_free += lut[*(buf + br - 3)]; + case 2: nr_free += lut[*(buf + br - 2)]; + case 1: nr_free += lut[*(buf + br - 1)]; + } + } + free(buf); out: - free(lut); - if (!total || br < 0) - return -1; - return nr_free; + free(lut); + if (!total || br < 0) + return -1; + return nr_free; } #endif diff --git a/source/libntfs/attrlist.c b/source/libntfs/attrlist.c index 424e98a9..9c62f316 100644 --- a/source/libntfs/attrlist.c +++ b/source/libntfs/attrlist.c @@ -58,37 +58,38 @@ * EINVAL - Invalid arguments passed to function or attribute haven't got * attribute list. */ -int ntfs_attrlist_need(ntfs_inode *ni) { - ATTR_LIST_ENTRY *ale; +int ntfs_attrlist_need(ntfs_inode *ni) +{ + ATTR_LIST_ENTRY *ale; - if (!ni) { - ntfs_log_trace("Invalid arguments.\n"); - errno = EINVAL; - return -1; - } + if (!ni) { + ntfs_log_trace("Invalid arguments.\n"); + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no); + ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no); - if (!NInoAttrList(ni)) { - ntfs_log_trace("Inode haven't got attribute list.\n"); - errno = EINVAL; - return -1; - } + if (!NInoAttrList(ni)) { + ntfs_log_trace("Inode haven't got attribute list.\n"); + errno = EINVAL; + return -1; + } - if (!ni->attr_list) { - ntfs_log_trace("Corrupt in-memory struct.\n"); - errno = EINVAL; - return -1; - } + if (!ni->attr_list) { + ntfs_log_trace("Corrupt in-memory struct.\n"); + errno = EINVAL; + return -1; + } - errno = 0; - ale = (ATTR_LIST_ENTRY *)ni->attr_list; - while ((u8*)ale < ni->attr_list + ni->attr_list_size) { - if (MREF_LE(ale->mft_reference) != ni->mft_no) - return 1; - ale = (ATTR_LIST_ENTRY *)((u8*)ale + le16_to_cpu(ale->length)); - } - return 0; + errno = 0; + ale = (ATTR_LIST_ENTRY *)ni->attr_list; + while ((u8*)ale < ni->attr_list + ni->attr_list_size) { + if (MREF_LE(ale->mft_reference) != ni->mft_no) + return 1; + ale = (ATTR_LIST_ENTRY *)((u8*)ale + le16_to_cpu(ale->length)); + } + return 0; } /** @@ -103,132 +104,133 @@ int ntfs_attrlist_need(ntfs_inode *ni) { * EIO - I/O error occurred or damaged filesystem. * EEXIST - Such attribute already present in attribute list. */ -int ntfs_attrlist_entry_add(ntfs_inode *ni, ATTR_RECORD *attr) { - ATTR_LIST_ENTRY *ale; - MFT_REF mref; - ntfs_attr *na = NULL; - ntfs_attr_search_ctx *ctx; - u8 *new_al; - int entry_len, entry_offset, err; +int ntfs_attrlist_entry_add(ntfs_inode *ni, ATTR_RECORD *attr) +{ + ATTR_LIST_ENTRY *ale; + MFT_REF mref; + ntfs_attr *na = NULL; + ntfs_attr_search_ctx *ctx; + u8 *new_al; + int entry_len, entry_offset, err; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", - (long long) ni->mft_no, - (unsigned) le32_to_cpu(attr->type)); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", + (long long) ni->mft_no, + (unsigned) le32_to_cpu(attr->type)); - if (!ni || !attr) { - ntfs_log_trace("Invalid arguments.\n"); - errno = EINVAL; - return -1; - } + if (!ni || !attr) { + ntfs_log_trace("Invalid arguments.\n"); + errno = EINVAL; + return -1; + } - mref = MK_LE_MREF(ni->mft_no, le16_to_cpu(ni->mrec->sequence_number)); + mref = MK_LE_MREF(ni->mft_no, le16_to_cpu(ni->mrec->sequence_number)); - if (ni->nr_extents == -1) - ni = ni->base_ni; + if (ni->nr_extents == -1) + ni = ni->base_ni; - if (!NInoAttrList(ni)) { - ntfs_log_trace("Attribute list isn't present.\n"); - errno = ENOENT; - return -1; - } + if (!NInoAttrList(ni)) { + ntfs_log_trace("Attribute list isn't present.\n"); + errno = ENOENT; + return -1; + } - /* Determine size and allocate memory for new attribute list. */ - entry_len = (sizeof(ATTR_LIST_ENTRY) + sizeof(ntfschar) * - attr->name_length + 7) & ~7; - new_al = ntfs_calloc(ni->attr_list_size + entry_len); - if (!new_al) - return -1; + /* Determine size and allocate memory for new attribute list. */ + entry_len = (sizeof(ATTR_LIST_ENTRY) + sizeof(ntfschar) * + attr->name_length + 7) & ~7; + new_al = ntfs_calloc(ni->attr_list_size + entry_len); + if (!new_al) + return -1; - /* Find place for the new entry. */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) { - err = errno; - goto err_out; - } - if (!ntfs_attr_lookup(attr->type, (attr->name_length) ? (ntfschar*) - ((u8*)attr + le16_to_cpu(attr->name_offset)) : - AT_UNNAMED, attr->name_length, CASE_SENSITIVE, - (attr->non_resident) ? le64_to_cpu(attr->lowest_vcn) : - 0, (attr->non_resident) ? NULL : ((u8*)attr + - le16_to_cpu(attr->value_offset)), (attr->non_resident) ? - 0 : le32_to_cpu(attr->value_length), ctx)) { - /* Found some extent, check it to be before new extent. */ - if (ctx->al_entry->lowest_vcn == attr->lowest_vcn) { - err = EEXIST; - ntfs_log_trace("Such attribute already present in the " - "attribute list.\n"); - ntfs_attr_put_search_ctx(ctx); - goto err_out; - } - /* Add new entry after this extent. */ - ale = (ATTR_LIST_ENTRY*)((u8*)ctx->al_entry + - le16_to_cpu(ctx->al_entry->length)); - } else { - /* Check for real errors. */ - if (errno != ENOENT) { - err = errno; - ntfs_log_trace("Attribute lookup failed.\n"); - ntfs_attr_put_search_ctx(ctx); - goto err_out; - } - /* No previous extents found. */ - ale = ctx->al_entry; - } - /* Don't need it anymore, @ctx->al_entry points to @ni->attr_list. */ - ntfs_attr_put_search_ctx(ctx); + /* Find place for the new entry. */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) { + err = errno; + goto err_out; + } + if (!ntfs_attr_lookup(attr->type, (attr->name_length) ? (ntfschar*) + ((u8*)attr + le16_to_cpu(attr->name_offset)) : + AT_UNNAMED, attr->name_length, CASE_SENSITIVE, + (attr->non_resident) ? le64_to_cpu(attr->lowest_vcn) : + 0, (attr->non_resident) ? NULL : ((u8*)attr + + le16_to_cpu(attr->value_offset)), (attr->non_resident) ? + 0 : le32_to_cpu(attr->value_length), ctx)) { + /* Found some extent, check it to be before new extent. */ + if (ctx->al_entry->lowest_vcn == attr->lowest_vcn) { + err = EEXIST; + ntfs_log_trace("Such attribute already present in the " + "attribute list.\n"); + ntfs_attr_put_search_ctx(ctx); + goto err_out; + } + /* Add new entry after this extent. */ + ale = (ATTR_LIST_ENTRY*)((u8*)ctx->al_entry + + le16_to_cpu(ctx->al_entry->length)); + } else { + /* Check for real errors. */ + if (errno != ENOENT) { + err = errno; + ntfs_log_trace("Attribute lookup failed.\n"); + ntfs_attr_put_search_ctx(ctx); + goto err_out; + } + /* No previous extents found. */ + ale = ctx->al_entry; + } + /* Don't need it anymore, @ctx->al_entry points to @ni->attr_list. */ + ntfs_attr_put_search_ctx(ctx); - /* Determine new entry offset. */ - entry_offset = ((u8 *)ale - ni->attr_list); - /* Set pointer to new entry. */ - ale = (ATTR_LIST_ENTRY *)(new_al + entry_offset); - /* Zero it to fix valgrind warning. */ - memset(ale, 0, entry_len); - /* Form new entry. */ - ale->type = attr->type; - ale->length = cpu_to_le16(entry_len); - ale->name_length = attr->name_length; - ale->name_offset = offsetof(ATTR_LIST_ENTRY, name); - if (attr->non_resident) - ale->lowest_vcn = attr->lowest_vcn; - else - ale->lowest_vcn = 0; - ale->mft_reference = mref; - ale->instance = attr->instance; - memcpy(ale->name, (u8 *)attr + le16_to_cpu(attr->name_offset), - attr->name_length * sizeof(ntfschar)); + /* Determine new entry offset. */ + entry_offset = ((u8 *)ale - ni->attr_list); + /* Set pointer to new entry. */ + ale = (ATTR_LIST_ENTRY *)(new_al + entry_offset); + /* Zero it to fix valgrind warning. */ + memset(ale, 0, entry_len); + /* Form new entry. */ + ale->type = attr->type; + ale->length = cpu_to_le16(entry_len); + ale->name_length = attr->name_length; + ale->name_offset = offsetof(ATTR_LIST_ENTRY, name); + if (attr->non_resident) + ale->lowest_vcn = attr->lowest_vcn; + else + ale->lowest_vcn = 0; + ale->mft_reference = mref; + ale->instance = attr->instance; + memcpy(ale->name, (u8 *)attr + le16_to_cpu(attr->name_offset), + attr->name_length * sizeof(ntfschar)); - /* Resize $ATTRIBUTE_LIST to new length. */ - na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); - if (!na) { - err = errno; - ntfs_log_trace("Failed to open $ATTRIBUTE_LIST attribute.\n"); - goto err_out; - } - if (ntfs_attr_truncate(na, ni->attr_list_size + entry_len)) { - err = errno; - ntfs_log_trace("$ATTRIBUTE_LIST resize failed.\n"); - goto err_out; - } + /* Resize $ATTRIBUTE_LIST to new length. */ + na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); + if (!na) { + err = errno; + ntfs_log_trace("Failed to open $ATTRIBUTE_LIST attribute.\n"); + goto err_out; + } + if (ntfs_attr_truncate(na, ni->attr_list_size + entry_len)) { + err = errno; + ntfs_log_trace("$ATTRIBUTE_LIST resize failed.\n"); + goto err_out; + } - /* Copy entries from old attribute list to new. */ - memcpy(new_al, ni->attr_list, entry_offset); - memcpy(new_al + entry_offset + entry_len, ni->attr_list + - entry_offset, ni->attr_list_size - entry_offset); + /* Copy entries from old attribute list to new. */ + memcpy(new_al, ni->attr_list, entry_offset); + memcpy(new_al + entry_offset + entry_len, ni->attr_list + + entry_offset, ni->attr_list_size - entry_offset); - /* Set new runlist. */ - free(ni->attr_list); - ni->attr_list = new_al; - ni->attr_list_size = ni->attr_list_size + entry_len; - NInoAttrListSetDirty(ni); - /* Done! */ - ntfs_attr_close(na); - return 0; + /* Set new runlist. */ + free(ni->attr_list); + ni->attr_list = new_al; + ni->attr_list_size = ni->attr_list_size + entry_len; + NInoAttrListSetDirty(ni); + /* Done! */ + ntfs_attr_close(na); + return 0; err_out: - if (na) - ntfs_attr_close(na); - free(new_al); - errno = err; - return -1; + if (na) + ntfs_attr_close(na); + free(new_al); + errno = err; + return -1; } /** @@ -239,73 +241,74 @@ err_out: * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attrlist_entry_rm(ntfs_attr_search_ctx *ctx) { - u8 *new_al; - int new_al_len; - ntfs_inode *base_ni; - ntfs_attr *na; - ATTR_LIST_ENTRY *ale; - int err; +int ntfs_attrlist_entry_rm(ntfs_attr_search_ctx *ctx) +{ + u8 *new_al; + int new_al_len; + ntfs_inode *base_ni; + ntfs_attr *na; + ATTR_LIST_ENTRY *ale; + int err; - if (!ctx || !ctx->ntfs_ino || !ctx->al_entry) { - ntfs_log_trace("Invalid arguments.\n"); - errno = EINVAL; - return -1; - } + if (!ctx || !ctx->ntfs_ino || !ctx->al_entry) { + ntfs_log_trace("Invalid arguments.\n"); + errno = EINVAL; + return -1; + } - if (ctx->base_ntfs_ino) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; - ale = ctx->al_entry; + if (ctx->base_ntfs_ino) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; + ale = ctx->al_entry; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld.\n", - (long long) ctx->ntfs_ino->mft_no, - (unsigned) le32_to_cpu(ctx->al_entry->type), - (long long) le64_to_cpu(ctx->al_entry->lowest_vcn)); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld.\n", + (long long) ctx->ntfs_ino->mft_no, + (unsigned) le32_to_cpu(ctx->al_entry->type), + (long long) le64_to_cpu(ctx->al_entry->lowest_vcn)); - if (!NInoAttrList(base_ni)) { - ntfs_log_trace("Attribute list isn't present.\n"); - errno = ENOENT; - return -1; - } + if (!NInoAttrList(base_ni)) { + ntfs_log_trace("Attribute list isn't present.\n"); + errno = ENOENT; + return -1; + } - /* Allocate memory for new attribute list. */ - new_al_len = base_ni->attr_list_size - le16_to_cpu(ale->length); - new_al = ntfs_calloc(new_al_len); - if (!new_al) - return -1; + /* Allocate memory for new attribute list. */ + new_al_len = base_ni->attr_list_size - le16_to_cpu(ale->length); + new_al = ntfs_calloc(new_al_len); + if (!new_al) + return -1; - /* Reisze $ATTRIBUTE_LIST to new length. */ - na = ntfs_attr_open(base_ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); - if (!na) { - err = errno; - ntfs_log_trace("Failed to open $ATTRIBUTE_LIST attribute.\n"); - goto err_out; - } - if (ntfs_attr_truncate(na, new_al_len)) { - err = errno; - ntfs_log_trace("$ATTRIBUTE_LIST resize failed.\n"); - goto err_out; - } + /* Reisze $ATTRIBUTE_LIST to new length. */ + na = ntfs_attr_open(base_ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); + if (!na) { + err = errno; + ntfs_log_trace("Failed to open $ATTRIBUTE_LIST attribute.\n"); + goto err_out; + } + if (ntfs_attr_truncate(na, new_al_len)) { + err = errno; + ntfs_log_trace("$ATTRIBUTE_LIST resize failed.\n"); + goto err_out; + } - /* Copy entries from old attribute list to new. */ - memcpy(new_al, base_ni->attr_list, (u8*)ale - base_ni->attr_list); - memcpy(new_al + ((u8*)ale - base_ni->attr_list), (u8*)ale + le16_to_cpu( - ale->length), new_al_len - ((u8*)ale - base_ni->attr_list)); + /* Copy entries from old attribute list to new. */ + memcpy(new_al, base_ni->attr_list, (u8*)ale - base_ni->attr_list); + memcpy(new_al + ((u8*)ale - base_ni->attr_list), (u8*)ale + le16_to_cpu( + ale->length), new_al_len - ((u8*)ale - base_ni->attr_list)); - /* Set new runlist. */ - free(base_ni->attr_list); - base_ni->attr_list = new_al; - base_ni->attr_list_size = new_al_len; - NInoAttrListSetDirty(base_ni); - /* Done! */ - ntfs_attr_close(na); - return 0; + /* Set new runlist. */ + free(base_ni->attr_list); + base_ni->attr_list = new_al; + base_ni->attr_list_size = new_al_len; + NInoAttrListSetDirty(base_ni); + /* Done! */ + ntfs_attr_close(na); + return 0; err_out: - if (na) - ntfs_attr_close(na); - free(new_al); - errno = err; - return -1; + if (na) + ntfs_attr_close(na); + free(new_al); + errno = err; + return -1; } diff --git a/source/libntfs/attrlist.h b/source/libntfs/attrlist.h index fd4c505d..2952e48b 100644 --- a/source/libntfs/attrlist.h +++ b/source/libntfs/attrlist.h @@ -1,5 +1,5 @@ /* - * attrlist.h - Exports for attribute list attribute handling. + * attrlist.h - Exports for attribute list attribute handling. * Originated from Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov @@ -40,11 +40,12 @@ extern int ntfs_attrlist_entry_rm(ntfs_attr_search_ctx *ctx); * * This function cannot fail. */ -static __inline__ void ntfs_attrlist_mark_dirty(ntfs_inode *ni) { - if (ni->nr_extents == -1) - NInoAttrListSetDirty(ni->base_ni); - else - NInoAttrListSetDirty(ni); +static __inline__ void ntfs_attrlist_mark_dirty(ntfs_inode *ni) +{ + if (ni->nr_extents == -1) + NInoAttrListSetDirty(ni->base_ni); + else + NInoAttrListSetDirty(ni); } #endif /* defined _NTFS_ATTRLIST_H */ diff --git a/source/libntfs/bit_ops.h b/source/libntfs/bit_ops.h index ebee82bb..762be0b3 100644 --- a/source/libntfs/bit_ops.h +++ b/source/libntfs/bit_ops.h @@ -3,7 +3,7 @@ Functions for dealing with conversion of data between types Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -35,23 +35,23 @@ Functions to deal with little endian values stored in uint8_t arrays -----------------------------------------------------------------*/ static inline uint16_t u8array_to_u16 (const uint8_t* item, int offset) { - return ( item[offset] | (item[offset + 1] << 8)); + return ( item[offset] | (item[offset + 1] << 8)); } static inline uint32_t u8array_to_u32 (const uint8_t* item, int offset) { - return ( item[offset] | (item[offset + 1] << 8) | (item[offset + 2] << 16) | (item[offset + 3] << 24)); + return ( item[offset] | (item[offset + 1] << 8) | (item[offset + 2] << 16) | (item[offset + 3] << 24)); } static inline void u16_to_u8array (uint8_t* item, int offset, uint16_t value) { - item[offset] = (uint8_t) value; - item[offset + 1] = (uint8_t)(value >> 8); + item[offset] = (uint8_t) value; + item[offset + 1] = (uint8_t)(value >> 8); } static inline void u32_to_u8array (uint8_t* item, int offset, uint32_t value) { - item[offset] = (uint8_t) value; - item[offset + 1] = (uint8_t)(value >> 8); - item[offset + 2] = (uint8_t)(value >> 16); - item[offset + 3] = (uint8_t)(value >> 24); + item[offset] = (uint8_t) value; + item[offset + 1] = (uint8_t)(value >> 8); + item[offset + 2] = (uint8_t)(value >> 16); + item[offset + 3] = (uint8_t)(value >> 24); } #endif // _BIT_OPS_H diff --git a/source/libntfs/bitmap.c b/source/libntfs/bitmap.c index 65f3ff80..65162a29 100644 --- a/source/libntfs/bitmap.c +++ b/source/libntfs/bitmap.c @@ -53,13 +53,14 @@ * * Set the bit @bit in the @bitmap to @new_value. Ignore all errors. */ -void ntfs_bit_set(u8 *bitmap, const u64 bit, const u8 new_value) { - if (!bitmap || new_value > 1) - return; - if (!new_value) - bitmap[bit >> 3] &= ~(1 << (bit & 7)); - else - bitmap[bit >> 3] |= (1 << (bit & 7)); +void ntfs_bit_set(u8 *bitmap, const u64 bit, const u8 new_value) +{ + if (!bitmap || new_value > 1) + return; + if (!new_value) + bitmap[bit >> 3] &= ~(1 << (bit & 7)); + else + bitmap[bit >> 3] |= (1 << (bit & 7)); } /** @@ -70,10 +71,11 @@ void ntfs_bit_set(u8 *bitmap, const u64 bit, const u8 new_value) { * Get and return the value of the bit @bit in @bitmap (0 or 1). * Return -1 on error. */ -char ntfs_bit_get(const u8 *bitmap, const u64 bit) { - if (!bitmap) - return -1; - return (bitmap[bit >> 3] >> (bit & 7)) & 1; +char ntfs_bit_get(const u8 *bitmap, const u64 bit) +{ + if (!bitmap) + return -1; + return (bitmap[bit >> 3] >> (bit & 7)) & 1; } /** @@ -85,16 +87,17 @@ char ntfs_bit_get(const u8 *bitmap, const u64 bit) { * Return the value of the bit @bit and set it to @new_value (0 or 1). * Return -1 on error. */ -char ntfs_bit_get_and_set(u8 *bitmap, const u64 bit, const u8 new_value) { - register u8 old_bit, shift; +char ntfs_bit_get_and_set(u8 *bitmap, const u64 bit, const u8 new_value) +{ + register u8 old_bit, shift; - if (!bitmap || new_value > 1) - return -1; - shift = bit & 7; - old_bit = (bitmap[bit >> 3] >> shift) & 1; - if (new_value != old_bit) - bitmap[bit >> 3] ^= 1 << shift; - return old_bit; + if (!bitmap || new_value > 1) + return -1; + shift = bit & 7; + old_bit = (bitmap[bit >> 3] >> shift) & 1; + if (new_value != old_bit) + bitmap[bit >> 3] ^= 1 << shift; + return old_bit; } /** @@ -110,144 +113,145 @@ char ntfs_bit_get_and_set(u8 *bitmap, const u64 bit, const u8 new_value) { * On success return 0 and on error return -1 with errno set to the error code. */ static int ntfs_bitmap_set_bits_in_run(ntfs_attr *na, s64 start_bit, - s64 count, int value) { - s64 bufsize, br; - u8 *buf, *lastbyte_buf; - int bit, firstbyte, lastbyte, lastbyte_pos, tmp, ret = -1; + s64 count, int value) +{ + s64 bufsize, br; + u8 *buf, *lastbyte_buf; + int bit, firstbyte, lastbyte, lastbyte_pos, tmp, ret = -1; - if (!na || start_bit < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s: Invalid argument (%p, %lld, %lld)", - __FUNCTION__, na, (long long)start_bit, (long long)count); - return -1; - } + if (!na || start_bit < 0 || count < 0) { + errno = EINVAL; + ntfs_log_perror("%s: Invalid argument (%p, %lld, %lld)", + __FUNCTION__, na, (long long)start_bit, (long long)count); + return -1; + } - bit = start_bit & 7; - if (bit) - firstbyte = 1; - else - firstbyte = 0; + bit = start_bit & 7; + if (bit) + firstbyte = 1; + else + firstbyte = 0; - /* Calculate the required buffer size in bytes, capping it at 8kiB. */ - bufsize = ((count - (bit ? 8 - bit : 0) + 7) >> 3) + firstbyte; - if (bufsize > 8192) - bufsize = 8192; + /* Calculate the required buffer size in bytes, capping it at 8kiB. */ + bufsize = ((count - (bit ? 8 - bit : 0) + 7) >> 3) + firstbyte; + if (bufsize > 8192) + bufsize = 8192; - buf = ntfs_malloc(bufsize); - if (!buf) - return -1; + buf = ntfs_malloc(bufsize); + if (!buf) + return -1; + + /* Depending on @value, zero or set all bits in the allocated buffer. */ + memset(buf, value ? 0xff : 0, bufsize); - /* Depending on @value, zero or set all bits in the allocated buffer. */ - memset(buf, value ? 0xff : 0, bufsize); + /* If there is a first partial byte... */ + if (bit) { + /* read it in... */ + br = ntfs_attr_pread(na, start_bit >> 3, 1, buf); + if (br != 1) { + if (br >= 0) + errno = EIO; + goto free_err_out; + } + /* and set or clear the appropriate bits in it. */ + while ((bit & 7) && count--) { + if (value) + *buf |= 1 << bit++; + else + *buf &= ~(1 << bit++); + } + /* Update @start_bit to the new position. */ + start_bit = (start_bit + 7) & ~7; + } - /* If there is a first partial byte... */ - if (bit) { - /* read it in... */ - br = ntfs_attr_pread(na, start_bit >> 3, 1, buf); - if (br != 1) { - if (br >= 0) - errno = EIO; - goto free_err_out; - } - /* and set or clear the appropriate bits in it. */ - while ((bit & 7) && count--) { - if (value) - *buf |= 1 << bit++; - else - *buf &= ~(1 << bit++); - } - /* Update @start_bit to the new position. */ - start_bit = (start_bit + 7) & ~7; - } + /* Loop until @count reaches zero. */ + lastbyte = 0; + lastbyte_buf = NULL; + bit = count & 7; + do { + /* If there is a last partial byte... */ + if (count > 0 && bit) { + lastbyte_pos = ((count + 7) >> 3) + firstbyte; + if (!lastbyte_pos) { + // FIXME: Eeek! BUG! + ntfs_log_error("Lastbyte is zero. Leaving " + "inconsistent metadata.\n"); + errno = EIO; + goto free_err_out; + } + /* and it is in the currently loaded bitmap window... */ + if (lastbyte_pos <= bufsize) { + lastbyte_buf = buf + lastbyte_pos - 1; - /* Loop until @count reaches zero. */ - lastbyte = 0; - lastbyte_buf = NULL; - bit = count & 7; - do { - /* If there is a last partial byte... */ - if (count > 0 && bit) { - lastbyte_pos = ((count + 7) >> 3) + firstbyte; - if (!lastbyte_pos) { - // FIXME: Eeek! BUG! - ntfs_log_error("Lastbyte is zero. Leaving " - "inconsistent metadata.\n"); - errno = EIO; - goto free_err_out; - } - /* and it is in the currently loaded bitmap window... */ - if (lastbyte_pos <= bufsize) { - lastbyte_buf = buf + lastbyte_pos - 1; + /* read the byte in... */ + br = ntfs_attr_pread(na, (start_bit + count) >> + 3, 1, lastbyte_buf); + if (br != 1) { + // FIXME: Eeek! We need rollback! (AIA) + if (br >= 0) + errno = EIO; + ntfs_log_perror("Reading of last byte " + "failed (%lld). Leaving inconsistent " + "metadata", (long long)br); + goto free_err_out; + } + /* and set/clear the appropriate bits in it. */ + while (bit && count--) { + if (value) + *lastbyte_buf |= 1 << --bit; + else + *lastbyte_buf &= ~(1 << --bit); + } + /* We don't want to come back here... */ + bit = 0; + /* We have a last byte that we have handled. */ + lastbyte = 1; + } + } - /* read the byte in... */ - br = ntfs_attr_pread(na, (start_bit + count) >> - 3, 1, lastbyte_buf); - if (br != 1) { - // FIXME: Eeek! We need rollback! (AIA) - if (br >= 0) - errno = EIO; - ntfs_log_perror("Reading of last byte " - "failed (%lld). Leaving inconsistent " - "metadata", (long long)br); - goto free_err_out; - } - /* and set/clear the appropriate bits in it. */ - while (bit && count--) { - if (value) - *lastbyte_buf |= 1 << --bit; - else - *lastbyte_buf &= ~(1 << --bit); - } - /* We don't want to come back here... */ - bit = 0; - /* We have a last byte that we have handled. */ - lastbyte = 1; - } - } + /* Write the prepared buffer to disk. */ + tmp = (start_bit >> 3) - firstbyte; + br = ntfs_attr_pwrite(na, tmp, bufsize, buf); + if (br != bufsize) { + // FIXME: Eeek! We need rollback! (AIA) + if (br >= 0) + errno = EIO; + ntfs_log_perror("Failed to write buffer to bitmap " + "(%lld != %lld). Leaving inconsistent metadata", + (long long)br, (long long)bufsize); + goto free_err_out; + } - /* Write the prepared buffer to disk. */ - tmp = (start_bit >> 3) - firstbyte; - br = ntfs_attr_pwrite(na, tmp, bufsize, buf); - if (br != bufsize) { - // FIXME: Eeek! We need rollback! (AIA) - if (br >= 0) - errno = EIO; - ntfs_log_perror("Failed to write buffer to bitmap " - "(%lld != %lld). Leaving inconsistent metadata", - (long long)br, (long long)bufsize); - goto free_err_out; - } - - /* Update counters. */ - tmp = (bufsize - firstbyte - lastbyte) << 3; - if (firstbyte) { - firstbyte = 0; - /* - * Re-set the partial first byte so a subsequent write - * of the buffer does not have stale, incorrect bits. - */ - *buf = value ? 0xff : 0; - } - start_bit += tmp; - count -= tmp; - if (bufsize > (tmp = (count + 7) >> 3)) - bufsize = tmp; - - if (lastbyte && count != 0) { - // FIXME: Eeek! BUG! - ntfs_log_error("Last buffer but count is not zero " - "(%lld). Leaving inconsistent metadata.\n", - (long long)count); - errno = EIO; - goto free_err_out; - } - } while (count > 0); - - ret = 0; + /* Update counters. */ + tmp = (bufsize - firstbyte - lastbyte) << 3; + if (firstbyte) { + firstbyte = 0; + /* + * Re-set the partial first byte so a subsequent write + * of the buffer does not have stale, incorrect bits. + */ + *buf = value ? 0xff : 0; + } + start_bit += tmp; + count -= tmp; + if (bufsize > (tmp = (count + 7) >> 3)) + bufsize = tmp; + if (lastbyte && count != 0) { + // FIXME: Eeek! BUG! + ntfs_log_error("Last buffer but count is not zero " + "(%lld). Leaving inconsistent metadata.\n", + (long long)count); + errno = EIO; + goto free_err_out; + } + } while (count > 0); + + ret = 0; + free_err_out: - free(buf); - return ret; + free(buf); + return ret; } /** @@ -261,14 +265,15 @@ free_err_out: * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_bitmap_set_run(ntfs_attr *na, s64 start_bit, s64 count) { - int ret; - - ntfs_log_enter("Set from bit %lld, count %lld\n", - (long long)start_bit, (long long)count); - ret = ntfs_bitmap_set_bits_in_run(na, start_bit, count, 1); - ntfs_log_leave("\n"); - return ret; +int ntfs_bitmap_set_run(ntfs_attr *na, s64 start_bit, s64 count) +{ + int ret; + + ntfs_log_enter("Set from bit %lld, count %lld\n", + (long long)start_bit, (long long)count); + ret = ntfs_bitmap_set_bits_in_run(na, start_bit, count, 1); + ntfs_log_leave("\n"); + return ret; } /** @@ -282,13 +287,14 @@ int ntfs_bitmap_set_run(ntfs_attr *na, s64 start_bit, s64 count) { * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_bitmap_clear_run(ntfs_attr *na, s64 start_bit, s64 count) { - int ret; - - ntfs_log_enter("Clear from bit %lld, count %lld\n", - (long long)start_bit, (long long)count); - ret = ntfs_bitmap_set_bits_in_run(na, start_bit, count, 0); - ntfs_log_leave("\n"); - return ret; +int ntfs_bitmap_clear_run(ntfs_attr *na, s64 start_bit, s64 count) +{ + int ret; + + ntfs_log_enter("Clear from bit %lld, count %lld\n", + (long long)start_bit, (long long)count); + ret = ntfs_bitmap_set_bits_in_run(na, start_bit, count, 0); + ntfs_log_leave("\n"); + return ret; } diff --git a/source/libntfs/bitmap.h b/source/libntfs/bitmap.h index 08ebc75b..10b5f6c5 100644 --- a/source/libntfs/bitmap.h +++ b/source/libntfs/bitmap.h @@ -51,8 +51,9 @@ extern int ntfs_bitmap_clear_run(ntfs_attr *na, s64 start_bit, s64 count); * * On success return 0 and on error return -1 with errno set to the error code. */ -static __inline__ int ntfs_bitmap_set_bit(ntfs_attr *na, s64 bit) { - return ntfs_bitmap_set_run(na, bit, 1); +static __inline__ int ntfs_bitmap_set_bit(ntfs_attr *na, s64 bit) +{ + return ntfs_bitmap_set_run(na, bit, 1); } /** @@ -64,8 +65,9 @@ static __inline__ int ntfs_bitmap_set_bit(ntfs_attr *na, s64 bit) { * * On success return 0 and on error return -1 with errno set to the error code. */ -static __inline__ int ntfs_bitmap_clear_bit(ntfs_attr *na, s64 bit) { - return ntfs_bitmap_clear_run(na, bit, 1); +static __inline__ int ntfs_bitmap_clear_bit(ntfs_attr *na, s64 bit) +{ + return ntfs_bitmap_clear_run(na, bit, 1); } /* @@ -74,8 +76,9 @@ static __inline__ int ntfs_bitmap_clear_bit(ntfs_attr *na, s64 bit) { * @word: value to rotate * @shift: bits to roll */ -static __inline__ u32 ntfs_rol32(u32 word, unsigned int shift) { - return (word << shift) | (word >> (32 - shift)); +static __inline__ u32 ntfs_rol32(u32 word, unsigned int shift) +{ + return (word << shift) | (word >> (32 - shift)); } /* @@ -84,8 +87,9 @@ static __inline__ u32 ntfs_rol32(u32 word, unsigned int shift) { * @word: value to rotate * @shift: bits to roll */ -static __inline__ u32 ntfs_ror32(u32 word, unsigned int shift) { - return (word >> shift) | (word << (32 - shift)); +static __inline__ u32 ntfs_ror32(u32 word, unsigned int shift) +{ + return (word >> shift) | (word << (32 - shift)); } #endif /* defined _NTFS_BITMAP_H */ diff --git a/source/libntfs/bootsect.c b/source/libntfs/bootsect.c index 8aa24b9b..e9bea370 100644 --- a/source/libntfs/bootsect.c +++ b/source/libntfs/bootsect.c @@ -57,124 +57,106 @@ * * Return TRUE if @b contains a valid ntfs boot sector and FALSE if not. */ -BOOL ntfs_boot_sector_is_ntfs(NTFS_BOOT_SECTOR *b) { - u32 i; - BOOL ret = FALSE; +BOOL ntfs_boot_sector_is_ntfs(NTFS_BOOT_SECTOR *b) +{ + u32 i; + BOOL ret = FALSE; - ntfs_log_debug("Beginning bootsector check.\n"); + ntfs_log_debug("Beginning bootsector check.\n"); - ntfs_log_debug("Checking OEMid, NTFS signature.\n"); - if (b->oem_id != cpu_to_le64(0x202020205346544eULL)) { /* "NTFS " */ - ntfs_log_error("NTFS signature is missing.\n"); - goto not_ntfs; - } + ntfs_log_debug("Checking OEMid, NTFS signature.\n"); + if (b->oem_id != cpu_to_le64(0x202020205346544eULL)) { /* "NTFS " */ + ntfs_log_error("NTFS signature is missing.\n"); + goto not_ntfs; + } - ntfs_log_debug("Checking bytes per sector.\n"); - if (le16_to_cpu(b->bpb.bytes_per_sector) < 256 || - le16_to_cpu(b->bpb.bytes_per_sector) > 4096) { - ntfs_log_error("Unexpected bytes per sector value (%d).\n", - le16_to_cpu(b->bpb.bytes_per_sector)); - goto not_ntfs; - } + ntfs_log_debug("Checking bytes per sector.\n"); + if (le16_to_cpu(b->bpb.bytes_per_sector) < 256 || + le16_to_cpu(b->bpb.bytes_per_sector) > 4096) { + ntfs_log_error("Unexpected bytes per sector value (%d).\n", + le16_to_cpu(b->bpb.bytes_per_sector)); + goto not_ntfs; + } - ntfs_log_debug("Checking sectors per cluster.\n"); - switch (b->bpb.sectors_per_cluster) { - case 1: - case 2: - case 4: - case 8: - case 16: - case 32: - case 64: - case 128: - break; - default: - ntfs_log_error("Unexpected sectors per cluster value (%d).\n", - b->bpb.sectors_per_cluster); - goto not_ntfs; - } + ntfs_log_debug("Checking sectors per cluster.\n"); + switch (b->bpb.sectors_per_cluster) { + case 1: case 2: case 4: case 8: case 16: case 32: case 64: case 128: + break; + default: + ntfs_log_error("Unexpected sectors per cluster value (%d).\n", + b->bpb.sectors_per_cluster); + goto not_ntfs; + } - ntfs_log_debug("Checking cluster size.\n"); - i = (u32)le16_to_cpu(b->bpb.bytes_per_sector) * - b->bpb.sectors_per_cluster; - if (i > 65536) { - ntfs_log_error("Unexpected cluster size (%d).\n", i); - goto not_ntfs; - } + ntfs_log_debug("Checking cluster size.\n"); + i = (u32)le16_to_cpu(b->bpb.bytes_per_sector) * + b->bpb.sectors_per_cluster; + if (i > 65536) { + ntfs_log_error("Unexpected cluster size (%d).\n", i); + goto not_ntfs; + } - ntfs_log_debug("Checking reserved fields are zero.\n"); - if (le16_to_cpu(b->bpb.reserved_sectors) || - le16_to_cpu(b->bpb.root_entries) || - le16_to_cpu(b->bpb.sectors) || - le16_to_cpu(b->bpb.sectors_per_fat) || - le32_to_cpu(b->bpb.large_sectors) || - b->bpb.fats) { - ntfs_log_error("Reserved fields aren't zero " - "(%d, %d, %d, %d, %d, %d).\n", - le16_to_cpu(b->bpb.reserved_sectors), - le16_to_cpu(b->bpb.root_entries), - le16_to_cpu(b->bpb.sectors), - le16_to_cpu(b->bpb.sectors_per_fat), - le32_to_cpu(b->bpb.large_sectors), - b->bpb.fats); - goto not_ntfs; - } + ntfs_log_debug("Checking reserved fields are zero.\n"); + if (le16_to_cpu(b->bpb.reserved_sectors) || + le16_to_cpu(b->bpb.root_entries) || + le16_to_cpu(b->bpb.sectors) || + le16_to_cpu(b->bpb.sectors_per_fat) || + le32_to_cpu(b->bpb.large_sectors) || + b->bpb.fats) { + ntfs_log_error("Reserved fields aren't zero " + "(%d, %d, %d, %d, %d, %d).\n", + le16_to_cpu(b->bpb.reserved_sectors), + le16_to_cpu(b->bpb.root_entries), + le16_to_cpu(b->bpb.sectors), + le16_to_cpu(b->bpb.sectors_per_fat), + le32_to_cpu(b->bpb.large_sectors), + b->bpb.fats); + goto not_ntfs; + } - ntfs_log_debug("Checking clusters per mft record.\n"); - if ((u8)b->clusters_per_mft_record < 0xe1 || - (u8)b->clusters_per_mft_record > 0xf7) { - switch (b->clusters_per_mft_record) { - case 1: - case 2: - case 4: - case 8: - case 0x10: - case 0x20: - case 0x40: - break; - default: - ntfs_log_error("Unexpected clusters per mft record " - "(%d).\n", b->clusters_per_mft_record); - goto not_ntfs; - } - } + ntfs_log_debug("Checking clusters per mft record.\n"); + if ((u8)b->clusters_per_mft_record < 0xe1 || + (u8)b->clusters_per_mft_record > 0xf7) { + switch (b->clusters_per_mft_record) { + case 1: case 2: case 4: case 8: case 0x10: case 0x20: case 0x40: + break; + default: + ntfs_log_error("Unexpected clusters per mft record " + "(%d).\n", b->clusters_per_mft_record); + goto not_ntfs; + } + } - ntfs_log_debug("Checking clusters per index block.\n"); - if ((u8)b->clusters_per_index_record < 0xe1 || - (u8)b->clusters_per_index_record > 0xf7) { - switch (b->clusters_per_index_record) { - case 1: - case 2: - case 4: - case 8: - case 0x10: - case 0x20: - case 0x40: - break; - default: - ntfs_log_error("Unexpected clusters per index record " - "(%d).\n", b->clusters_per_index_record); - goto not_ntfs; - } - } + ntfs_log_debug("Checking clusters per index block.\n"); + if ((u8)b->clusters_per_index_record < 0xe1 || + (u8)b->clusters_per_index_record > 0xf7) { + switch (b->clusters_per_index_record) { + case 1: case 2: case 4: case 8: case 0x10: case 0x20: case 0x40: + break; + default: + ntfs_log_error("Unexpected clusters per index record " + "(%d).\n", b->clusters_per_index_record); + goto not_ntfs; + } + } - if (b->end_of_sector_marker != cpu_to_le16(0xaa55)) - ntfs_log_debug("Warning: Bootsector has invalid end of sector " - "marker.\n"); + if (b->end_of_sector_marker != cpu_to_le16(0xaa55)) + ntfs_log_debug("Warning: Bootsector has invalid end of sector " + "marker.\n"); - ntfs_log_debug("Bootsector check completed successfully.\n"); + ntfs_log_debug("Bootsector check completed successfully.\n"); - ret = TRUE; + ret = TRUE; not_ntfs: - return ret; + return ret; } static const char *last_sector_error = - "HINTS: Either the volume is a RAID/LDM but it wasn't setup yet,\n" - " or it was not setup correctly (e.g. by not using mdadm --build ...),\n" - " or a wrong device is tried to be mounted,\n" - " or the partition table is corrupt (partition is smaller than NTFS),\n" - " or the NTFS boot sector is corrupt (NTFS size is not valid).\n"; +"HINTS: Either the volume is a RAID/LDM but it wasn't setup yet,\n" +" or it was not setup correctly (e.g. by not using mdadm --build ...),\n" +" or a wrong device is tried to be mounted,\n" +" or the partition table is corrupt (partition is smaller than NTFS),\n" +" or the NTFS boot sector is corrupt (NTFS size is not valid).\n"; /** * ntfs_boot_sector_parse - setup an ntfs volume from an ntfs boot sector @@ -186,117 +168,118 @@ static const char *last_sector_error = * * Return 0 on success or -1 on error with errno set to the error code EINVAL. */ -int ntfs_boot_sector_parse(ntfs_volume *vol, const NTFS_BOOT_SECTOR *bs) { - s64 sectors; - u8 sectors_per_cluster; - s8 c; +int ntfs_boot_sector_parse(ntfs_volume *vol, const NTFS_BOOT_SECTOR *bs) +{ + s64 sectors; + u8 sectors_per_cluster; + s8 c; - /* We return -1 with errno = EINVAL on error. */ - errno = EINVAL; + /* We return -1 with errno = EINVAL on error. */ + errno = EINVAL; - vol->sector_size = le16_to_cpu(bs->bpb.bytes_per_sector); - vol->sector_size_bits = ffs(vol->sector_size) - 1; - ntfs_log_debug("SectorSize = 0x%x\n", vol->sector_size); - ntfs_log_debug("SectorSizeBits = %u\n", vol->sector_size_bits); - /* - * The bounds checks on mft_lcn and mft_mirr_lcn (i.e. them being - * below or equal the number_of_clusters) really belong in the - * ntfs_boot_sector_is_ntfs but in this way we can just do this once. - */ - sectors_per_cluster = bs->bpb.sectors_per_cluster; - ntfs_log_debug("SectorsPerCluster = 0x%x\n", sectors_per_cluster); - if (sectors_per_cluster & (sectors_per_cluster - 1)) { - ntfs_log_error("sectors_per_cluster (%d) is not a power of 2." - "\n", sectors_per_cluster); - return -1; - } + vol->sector_size = le16_to_cpu(bs->bpb.bytes_per_sector); + vol->sector_size_bits = ffs(vol->sector_size) - 1; + ntfs_log_debug("SectorSize = 0x%x\n", vol->sector_size); + ntfs_log_debug("SectorSizeBits = %u\n", vol->sector_size_bits); + /* + * The bounds checks on mft_lcn and mft_mirr_lcn (i.e. them being + * below or equal the number_of_clusters) really belong in the + * ntfs_boot_sector_is_ntfs but in this way we can just do this once. + */ + sectors_per_cluster = bs->bpb.sectors_per_cluster; + ntfs_log_debug("SectorsPerCluster = 0x%x\n", sectors_per_cluster); + if (sectors_per_cluster & (sectors_per_cluster - 1)) { + ntfs_log_error("sectors_per_cluster (%d) is not a power of 2." + "\n", sectors_per_cluster); + return -1; + } + + sectors = sle64_to_cpu(bs->number_of_sectors); + ntfs_log_debug("NumberOfSectors = %lld\n", (long long)sectors); + if (!sectors) { + ntfs_log_error("Volume size is set to zero.\n"); + return -1; + } + if (vol->dev->d_ops->seek(vol->dev, + (sectors - 1) << vol->sector_size_bits, + SEEK_SET) == -1) { + ntfs_log_perror("Failed to read last sector (%lld)", + (long long)sectors); + ntfs_log_error("%s", last_sector_error); + return -1; + } + + vol->nr_clusters = sectors >> (ffs(sectors_per_cluster) - 1); - sectors = sle64_to_cpu(bs->number_of_sectors); - ntfs_log_debug("NumberOfSectors = %lld\n", (long long)sectors); - if (!sectors) { - ntfs_log_error("Volume size is set to zero.\n"); - return -1; - } - if (vol->dev->d_ops->seek(vol->dev, - (sectors - 1) << vol->sector_size_bits, - SEEK_SET) == -1) { - ntfs_log_perror("Failed to read last sector (%lld)", - (long long)sectors); - ntfs_log_error("%s", last_sector_error); - return -1; - } - - vol->nr_clusters = sectors >> (ffs(sectors_per_cluster) - 1); - - vol->mft_lcn = sle64_to_cpu(bs->mft_lcn); - vol->mftmirr_lcn = sle64_to_cpu(bs->mftmirr_lcn); - ntfs_log_debug("MFT LCN = %lld\n", (long long)vol->mft_lcn); - ntfs_log_debug("MFTMirr LCN = %lld\n", (long long)vol->mftmirr_lcn); - if (vol->mft_lcn > vol->nr_clusters || - vol->mftmirr_lcn > vol->nr_clusters) { - ntfs_log_error("$MFT LCN (%lld) or $MFTMirr LCN (%lld) is " - "greater than the number of clusters (%lld).\n", - (long long)vol->mft_lcn, (long long)vol->mftmirr_lcn, - (long long)vol->nr_clusters); - return -1; - } - - vol->cluster_size = sectors_per_cluster * vol->sector_size; - if (vol->cluster_size & (vol->cluster_size - 1)) { - ntfs_log_error("cluster_size (%d) is not a power of 2.\n", - vol->cluster_size); - return -1; - } - vol->cluster_size_bits = ffs(vol->cluster_size) - 1; - /* - * Need to get the clusters per mft record and handle it if it is - * negative. Then calculate the mft_record_size. A value of 0x80 is - * illegal, thus signed char is actually ok! - */ - c = bs->clusters_per_mft_record; - ntfs_log_debug("ClusterSize = 0x%x\n", (unsigned)vol->cluster_size); - ntfs_log_debug("ClusterSizeBits = %u\n", vol->cluster_size_bits); - ntfs_log_debug("ClustersPerMftRecord = 0x%x\n", c); - /* - * When clusters_per_mft_record is negative, it means that it is to - * be taken to be the negative base 2 logarithm of the mft_record_size - * min bytes. Then: - * mft_record_size = 2^(-clusters_per_mft_record) bytes. - */ - if (c < 0) - vol->mft_record_size = 1 << -c; - else - vol->mft_record_size = c << vol->cluster_size_bits; - if (vol->mft_record_size & (vol->mft_record_size - 1)) { - ntfs_log_error("mft_record_size (%d) is not a power of 2.\n", - vol->mft_record_size); - return -1; - } - vol->mft_record_size_bits = ffs(vol->mft_record_size) - 1; - ntfs_log_debug("MftRecordSize = 0x%x\n", (unsigned)vol->mft_record_size); - ntfs_log_debug("MftRecordSizeBits = %u\n", vol->mft_record_size_bits); - /* Same as above for INDX record. */ - c = bs->clusters_per_index_record; - ntfs_log_debug("ClustersPerINDXRecord = 0x%x\n", c); - if (c < 0) - vol->indx_record_size = 1 << -c; - else - vol->indx_record_size = c << vol->cluster_size_bits; - vol->indx_record_size_bits = ffs(vol->indx_record_size) - 1; - ntfs_log_debug("INDXRecordSize = 0x%x\n", (unsigned)vol->indx_record_size); - ntfs_log_debug("INDXRecordSizeBits = %u\n", vol->indx_record_size_bits); - /* - * Work out the size of the MFT mirror in number of mft records. If the - * cluster size is less than or equal to the size taken by four mft - * records, the mft mirror stores the first four mft records. If the - * cluster size is bigger than the size taken by four mft records, the - * mft mirror contains as many mft records as will fit into one - * cluster. - */ - if (vol->cluster_size <= 4 * vol->mft_record_size) - vol->mftmirr_size = 4; - else - vol->mftmirr_size = vol->cluster_size / vol->mft_record_size; - return 0; + vol->mft_lcn = sle64_to_cpu(bs->mft_lcn); + vol->mftmirr_lcn = sle64_to_cpu(bs->mftmirr_lcn); + ntfs_log_debug("MFT LCN = %lld\n", (long long)vol->mft_lcn); + ntfs_log_debug("MFTMirr LCN = %lld\n", (long long)vol->mftmirr_lcn); + if (vol->mft_lcn > vol->nr_clusters || + vol->mftmirr_lcn > vol->nr_clusters) { + ntfs_log_error("$MFT LCN (%lld) or $MFTMirr LCN (%lld) is " + "greater than the number of clusters (%lld).\n", + (long long)vol->mft_lcn, (long long)vol->mftmirr_lcn, + (long long)vol->nr_clusters); + return -1; + } + + vol->cluster_size = sectors_per_cluster * vol->sector_size; + if (vol->cluster_size & (vol->cluster_size - 1)) { + ntfs_log_error("cluster_size (%d) is not a power of 2.\n", + vol->cluster_size); + return -1; + } + vol->cluster_size_bits = ffs(vol->cluster_size) - 1; + /* + * Need to get the clusters per mft record and handle it if it is + * negative. Then calculate the mft_record_size. A value of 0x80 is + * illegal, thus signed char is actually ok! + */ + c = bs->clusters_per_mft_record; + ntfs_log_debug("ClusterSize = 0x%x\n", (unsigned)vol->cluster_size); + ntfs_log_debug("ClusterSizeBits = %u\n", vol->cluster_size_bits); + ntfs_log_debug("ClustersPerMftRecord = 0x%x\n", c); + /* + * When clusters_per_mft_record is negative, it means that it is to + * be taken to be the negative base 2 logarithm of the mft_record_size + * min bytes. Then: + * mft_record_size = 2^(-clusters_per_mft_record) bytes. + */ + if (c < 0) + vol->mft_record_size = 1 << -c; + else + vol->mft_record_size = c << vol->cluster_size_bits; + if (vol->mft_record_size & (vol->mft_record_size - 1)) { + ntfs_log_error("mft_record_size (%d) is not a power of 2.\n", + vol->mft_record_size); + return -1; + } + vol->mft_record_size_bits = ffs(vol->mft_record_size) - 1; + ntfs_log_debug("MftRecordSize = 0x%x\n", (unsigned)vol->mft_record_size); + ntfs_log_debug("MftRecordSizeBits = %u\n", vol->mft_record_size_bits); + /* Same as above for INDX record. */ + c = bs->clusters_per_index_record; + ntfs_log_debug("ClustersPerINDXRecord = 0x%x\n", c); + if (c < 0) + vol->indx_record_size = 1 << -c; + else + vol->indx_record_size = c << vol->cluster_size_bits; + vol->indx_record_size_bits = ffs(vol->indx_record_size) - 1; + ntfs_log_debug("INDXRecordSize = 0x%x\n", (unsigned)vol->indx_record_size); + ntfs_log_debug("INDXRecordSizeBits = %u\n", vol->indx_record_size_bits); + /* + * Work out the size of the MFT mirror in number of mft records. If the + * cluster size is less than or equal to the size taken by four mft + * records, the mft mirror stores the first four mft records. If the + * cluster size is bigger than the size taken by four mft records, the + * mft mirror contains as many mft records as will fit into one + * cluster. + */ + if (vol->cluster_size <= 4 * vol->mft_record_size) + vol->mftmirr_size = 4; + else + vol->mftmirr_size = vol->cluster_size / vol->mft_record_size; + return 0; } diff --git a/source/libntfs/bootsect.h b/source/libntfs/bootsect.h index 017eb1e8..a299e821 100644 --- a/source/libntfs/bootsect.h +++ b/source/libntfs/bootsect.h @@ -1,5 +1,5 @@ /* - * bootsect.h - Exports for bootsector record handling. + * bootsect.h - Exports for bootsector record handling. * Originated from the Linux-NTFS project. * * Copyright (c) 2000-2002 Anton Altaparmakov diff --git a/source/libntfs/cache.c b/source/libntfs/cache.c index 4f4c2e94..0fe46543 100644 --- a/source/libntfs/cache.c +++ b/source/libntfs/cache.c @@ -51,349 +51,340 @@ #define CACHE_FREE UINT_MAX NTFS_CACHE* _NTFS_cache_constructor (unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition) { - NTFS_CACHE* cache; - unsigned int i; - NTFS_CACHE_ENTRY* cacheEntries; + NTFS_CACHE* cache; + unsigned int i; + NTFS_CACHE_ENTRY* cacheEntries; - if (numberOfPages==0 || sectorsPerPage==0) return NULL; + if(numberOfPages==0 || sectorsPerPage==0) return NULL; - if (numberOfPages < 4) { - numberOfPages = 4; - } + if (numberOfPages < 4) { + numberOfPages = 4; + } - if (sectorsPerPage < 32) { - sectorsPerPage = 32; - } + if (sectorsPerPage < 32) { + sectorsPerPage = 32; + } - cache = (NTFS_CACHE*) ntfs_alloc (sizeof(NTFS_CACHE)); - if (cache == NULL) { - return NULL; - } + cache = (NTFS_CACHE*) ntfs_alloc (sizeof(NTFS_CACHE)); + if (cache == NULL) { + return NULL; + } - cache->disc = discInterface; - cache->endOfPartition = endOfPartition; - cache->numberOfPages = numberOfPages; - cache->sectorsPerPage = sectorsPerPage; + cache->disc = discInterface; + cache->endOfPartition = endOfPartition; + cache->numberOfPages = numberOfPages; + cache->sectorsPerPage = sectorsPerPage; - cacheEntries = (NTFS_CACHE_ENTRY*) ntfs_alloc ( sizeof(NTFS_CACHE_ENTRY) * numberOfPages); - if (cacheEntries == NULL) { - ntfs_free (cache); - return NULL; - } + cacheEntries = (NTFS_CACHE_ENTRY*) ntfs_alloc ( sizeof(NTFS_CACHE_ENTRY) * numberOfPages); + if (cacheEntries == NULL) { + ntfs_free (cache); + return NULL; + } - for (i = 0; i < numberOfPages; i++) { - cacheEntries[i].sector = CACHE_FREE; - cacheEntries[i].count = 0; - cacheEntries[i].last_access = 0; - cacheEntries[i].dirty = false; - cacheEntries[i].cache = (uint8_t*) ntfs_align ( sectorsPerPage * BYTES_PER_READ ); - } + for (i = 0; i < numberOfPages; i++) { + cacheEntries[i].sector = CACHE_FREE; + cacheEntries[i].count = 0; + cacheEntries[i].last_access = 0; + cacheEntries[i].dirty = false; + cacheEntries[i].cache = (uint8_t*) ntfs_align ( sectorsPerPage * BYTES_PER_READ ); + } - cache->cacheEntries = cacheEntries; + cache->cacheEntries = cacheEntries; - return cache; + return cache; } void _NTFS_cache_destructor (NTFS_CACHE* cache) { - unsigned int i; + unsigned int i; - if (cache==NULL) return; + if(cache==NULL) return; - // Clear out cache before destroying it - _NTFS_cache_flush(cache); + // Clear out cache before destroying it + _NTFS_cache_flush(cache); - // Free memory in reverse allocation order - for (i = 0; i < cache->numberOfPages; i++) { - ntfs_free (cache->cacheEntries[i].cache); - } - ntfs_free (cache->cacheEntries); - ntfs_free (cache); + // Free memory in reverse allocation order + for (i = 0; i < cache->numberOfPages; i++) { + ntfs_free (cache->cacheEntries[i].cache); + } + ntfs_free (cache->cacheEntries); + ntfs_free (cache); } -static inline u64 accessTime() { - return gettime(); -} +static inline u64 accessTime(){ return gettime(); } -static NTFS_CACHE_ENTRY* _NTFS_cache_getPage(NTFS_CACHE *cache,sec_t sector) { - unsigned int i; - NTFS_CACHE_ENTRY* cacheEntries = cache->cacheEntries; - unsigned int numberOfPages = cache->numberOfPages; - unsigned int sectorsPerPage = cache->sectorsPerPage; +static NTFS_CACHE_ENTRY* _NTFS_cache_getPage(NTFS_CACHE *cache,sec_t sector) +{ + unsigned int i; + NTFS_CACHE_ENTRY* cacheEntries = cache->cacheEntries; + unsigned int numberOfPages = cache->numberOfPages; + unsigned int sectorsPerPage = cache->sectorsPerPage; - bool foundFree = false; - unsigned int oldUsed = 0; - unsigned int oldAccess = UINT_MAX; + bool foundFree = false; + unsigned int oldUsed = 0; + unsigned int oldAccess = UINT_MAX; - for (i=0;i=cacheEntries[i].sector && sector<(cacheEntries[i].sector + cacheEntries[i].count)) { - cacheEntries[i].last_access = accessTime(); - return &(cacheEntries[i]); - } + for(i=0;i=cacheEntries[i].sector && sector<(cacheEntries[i].sector + cacheEntries[i].count)) { + cacheEntries[i].last_access = accessTime(); + return &(cacheEntries[i]); + } - if (foundFree==false && (cacheEntries[i].sector==CACHE_FREE || cacheEntries[i].last_accessdisc->writeSectors(cacheEntries[oldUsed].sector,cacheEntries[oldUsed].count,cacheEntries[oldUsed].cache)) return NULL; - cacheEntries[oldUsed].dirty = false; - } - sector = (sector/sectorsPerPage)*sectorsPerPage; // align base sector to page size - sec_t next_page = sector + sectorsPerPage; - if (next_page > cache->endOfPartition) next_page = cache->endOfPartition; + if(foundFree==false && cacheEntries[oldUsed].dirty==true) { + if(!cache->disc->writeSectors(cacheEntries[oldUsed].sector,cacheEntries[oldUsed].count,cacheEntries[oldUsed].cache)) return NULL; + cacheEntries[oldUsed].dirty = false; + } + sector = (sector/sectorsPerPage)*sectorsPerPage; // align base sector to page size + sec_t next_page = sector + sectorsPerPage; + if(next_page > cache->endOfPartition) next_page = cache->endOfPartition; - if (!cache->disc->readSectors(sector,next_page-sector,cacheEntries[oldUsed].cache)) return NULL; + if(!cache->disc->readSectors(sector,next_page-sector,cacheEntries[oldUsed].cache)) return NULL; - cacheEntries[oldUsed].sector = sector; - cacheEntries[oldUsed].count = next_page-sector; - cacheEntries[oldUsed].last_access = accessTime(); + cacheEntries[oldUsed].sector = sector; + cacheEntries[oldUsed].count = next_page-sector; + cacheEntries[oldUsed].last_access = accessTime(); - return &(cacheEntries[oldUsed]); + return &(cacheEntries[oldUsed]); } static NTFS_CACHE_ENTRY* _NTFS_cache_findPage(NTFS_CACHE *cache, sec_t sector, sec_t count) { - unsigned int i; - NTFS_CACHE_ENTRY* cacheEntries = cache->cacheEntries; - unsigned int numberOfPages = cache->numberOfPages; - NTFS_CACHE_ENTRY *entry = NULL; - sec_t lowest = UINT_MAX; + unsigned int i; + NTFS_CACHE_ENTRY* cacheEntries = cache->cacheEntries; + unsigned int numberOfPages = cache->numberOfPages; + NTFS_CACHE_ENTRY *entry = NULL; + sec_t lowest = UINT_MAX; - for (i=0;i cacheEntries[i].sector) { - intersect = sector - cacheEntries[i].sector < cacheEntries[i].count; - } else { - intersect = cacheEntries[i].sector - sector < count; - } + for(i=0;i cacheEntries[i].sector) { + intersect = sector - cacheEntries[i].sector < cacheEntries[i].count; + } else { + intersect = cacheEntries[i].sector - sector < count; + } - if ( intersect && (cacheEntries[i].sector < lowest)) { - lowest = cacheEntries[i].sector; - entry = &cacheEntries[i]; - } - } - } + if ( intersect && (cacheEntries[i].sector < lowest)) { + lowest = cacheEntries[i].sector; + entry = &cacheEntries[i]; + } + } + } - return entry; + return entry; } -bool _NTFS_cache_readSectors(NTFS_CACHE *cache,sec_t sector,sec_t numSectors,void *buffer) { - sec_t sec; - sec_t secs_to_read; - NTFS_CACHE_ENTRY *entry; - uint8_t *dest = buffer; +bool _NTFS_cache_readSectors(NTFS_CACHE *cache,sec_t sector,sec_t numSectors,void *buffer) +{ + sec_t sec; + sec_t secs_to_read; + NTFS_CACHE_ENTRY *entry; + uint8_t *dest = buffer; - while (numSectors>0) { - entry = _NTFS_cache_getPage(cache,sector); - if (entry==NULL) return false; + while(numSectors>0) { + entry = _NTFS_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - secs_to_read = entry->count - sec; - if (secs_to_read>numSectors) secs_to_read = numSectors; + sec = sector - entry->sector; + secs_to_read = entry->count - sec; + if(secs_to_read>numSectors) secs_to_read = numSectors; - memcpy(dest,entry->cache + (sec*BYTES_PER_READ),(secs_to_read*BYTES_PER_READ)); + memcpy(dest,entry->cache + (sec*BYTES_PER_READ),(secs_to_read*BYTES_PER_READ)); - dest += (secs_to_read*BYTES_PER_READ); - sector += secs_to_read; - numSectors -= secs_to_read; - } + dest += (secs_to_read*BYTES_PER_READ); + sector += secs_to_read; + numSectors -= secs_to_read; + } - return true; + return true; } /* Reads some data from a cache page, determined by the sector number */ -bool _NTFS_cache_readPartialSector (NTFS_CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size) { - sec_t sec; - NTFS_CACHE_ENTRY *entry; +bool _NTFS_cache_readPartialSector (NTFS_CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size) +{ + sec_t sec; + NTFS_CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if (offset + size > BYTES_PER_READ) return false; - entry = _NTFS_cache_getPage(cache,sector); - if (entry==NULL) return false; + entry = _NTFS_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - memcpy(buffer,entry->cache + ((sec*BYTES_PER_READ) + offset),size); + sec = sector - entry->sector; + memcpy(buffer,entry->cache + ((sec*BYTES_PER_READ) + offset),size); - return true; + return true; } bool _NTFS_cache_readLittleEndianValue (NTFS_CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes) { - uint8_t buf[4]; - if (!_NTFS_cache_readPartialSector(cache, buf, sector, offset, num_bytes)) return false; + uint8_t buf[4]; + if (!_NTFS_cache_readPartialSector(cache, buf, sector, offset, num_bytes)) return false; - switch (num_bytes) { - case 1: - *value = buf[0]; - break; - case 2: - *value = u8array_to_u16(buf,0); - break; - case 4: - *value = u8array_to_u32(buf,0); - break; - default: - return false; - } - return true; + switch(num_bytes) { + case 1: *value = buf[0]; break; + case 2: *value = u8array_to_u16(buf,0); break; + case 4: *value = u8array_to_u32(buf,0); break; + default: return false; + } + return true; } /* Writes some data to a cache page, making sure it is loaded into memory first. */ -bool _NTFS_cache_writePartialSector (NTFS_CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) { - sec_t sec; - NTFS_CACHE_ENTRY *entry; +bool _NTFS_cache_writePartialSector (NTFS_CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) +{ + sec_t sec; + NTFS_CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if (offset + size > BYTES_PER_READ) return false; - entry = _NTFS_cache_getPage(cache,sector); - if (entry==NULL) return false; + entry = _NTFS_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); + sec = sector - entry->sector; + memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); - entry->dirty = true; - return true; + entry->dirty = true; + return true; } bool _NTFS_cache_writeLittleEndianValue (NTFS_CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, int size) { - uint8_t buf[4] = {0, 0, 0, 0}; + uint8_t buf[4] = {0, 0, 0, 0}; - switch (size) { - case 1: - buf[0] = value; - break; - case 2: - u16_to_u8array(buf, 0, value); - break; - case 4: - u32_to_u8array(buf, 0, value); - break; - default: - return false; - } + switch(size) { + case 1: buf[0] = value; break; + case 2: u16_to_u8array(buf, 0, value); break; + case 4: u32_to_u8array(buf, 0, value); break; + default: return false; + } - return _NTFS_cache_writePartialSector(cache, buf, sector, offset, size); + return _NTFS_cache_writePartialSector(cache, buf, sector, offset, size); } /* Writes some data to a cache page, zeroing out the page first */ -bool _NTFS_cache_eraseWritePartialSector (NTFS_CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) { - sec_t sec; - NTFS_CACHE_ENTRY *entry; +bool _NTFS_cache_eraseWritePartialSector (NTFS_CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) +{ + sec_t sec; + NTFS_CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if (offset + size > BYTES_PER_READ) return false; - entry = _NTFS_cache_getPage(cache,sector); - if (entry==NULL) return false; + entry = _NTFS_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - memset(entry->cache + (sec*BYTES_PER_READ),0,BYTES_PER_READ); - memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); + sec = sector - entry->sector; + memset(entry->cache + (sec*BYTES_PER_READ),0,BYTES_PER_READ); + memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); - entry->dirty = true; - return true; + entry->dirty = true; + return true; } -bool _NTFS_cache_writeSectors (NTFS_CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer) { - sec_t sec; - sec_t secs_to_write; - NTFS_CACHE_ENTRY* entry; - const uint8_t *src = buffer; +bool _NTFS_cache_writeSectors (NTFS_CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer) +{ + sec_t sec; + sec_t secs_to_write; + NTFS_CACHE_ENTRY* entry; + const uint8_t *src = buffer; - while (numSectors>0) { - /* - entry = _NTFS_cache_getPage(cache,sector); - if(entry==NULL) return false; + while(numSectors>0) + { +/* + entry = _NTFS_cache_getPage(cache,sector); + if(entry==NULL) return false; - sec = sector - entry->sector; - secs_to_write = entry->count - sec; - if(secs_to_write>numSectors) secs_to_write = numSectors; + sec = sector - entry->sector; + secs_to_write = entry->count - sec; + if(secs_to_write>numSectors) secs_to_write = numSectors; - memcpy(entry->cache + (sec*BYTES_PER_READ),src,(secs_to_write*BYTES_PER_READ)); + memcpy(entry->cache + (sec*BYTES_PER_READ),src,(secs_to_write*BYTES_PER_READ)); - src += (secs_to_write*BYTES_PER_READ); - sector += secs_to_write; - numSectors -= secs_to_write; + src += (secs_to_write*BYTES_PER_READ); + sector += secs_to_write; + numSectors -= secs_to_write; - entry->dirty = true; - */ - entry = _NTFS_cache_findPage(cache,sector,numSectors); + entry->dirty = true; +*/ + entry = _NTFS_cache_findPage(cache,sector,numSectors); - if (entry!=NULL) { + if(entry!=NULL) { - if ( entry->sector > sector) { + if ( entry->sector > sector) { - secs_to_write = entry->sector - sector; + secs_to_write = entry->sector - sector; - cache->disc->writeSectors(sector,secs_to_write,src); - src += (secs_to_write*BYTES_PER_READ); - sector += secs_to_write; - numSectors -= secs_to_write; - } + cache->disc->writeSectors(sector,secs_to_write,src); + src += (secs_to_write*BYTES_PER_READ); + sector += secs_to_write; + numSectors -= secs_to_write; + } - sec = sector - entry->sector; - secs_to_write = entry->count - sec; + sec = sector - entry->sector; + secs_to_write = entry->count - sec; - if (secs_to_write>numSectors) secs_to_write = numSectors; + if(secs_to_write>numSectors) secs_to_write = numSectors; - memcpy(entry->cache + (sec*BYTES_PER_READ),src,(secs_to_write*BYTES_PER_READ)); + memcpy(entry->cache + (sec*BYTES_PER_READ),src,(secs_to_write*BYTES_PER_READ)); - src += (secs_to_write*BYTES_PER_READ); - sector += secs_to_write; - numSectors -= secs_to_write; + src += (secs_to_write*BYTES_PER_READ); + sector += secs_to_write; + numSectors -= secs_to_write; - entry->dirty = true; + entry->dirty = true; - } else { - cache->disc->writeSectors(sector,numSectors,src); - numSectors=0; - } - } - return true; + } else { + cache->disc->writeSectors(sector,numSectors,src); + numSectors=0; + } + } + return true; } /* Flushes all dirty pages to disc, clearing the dirty flag. */ bool _NTFS_cache_flush (NTFS_CACHE* cache) { - unsigned int i; - if (cache==NULL) return true; + unsigned int i; + if(cache==NULL) return true; - for (i = 0; i < cache->numberOfPages; i++) { - if (cache->cacheEntries[i].dirty) { - if (!cache->disc->writeSectors (cache->cacheEntries[i].sector, cache->cacheEntries[i].count, cache->cacheEntries[i].cache)) { - return false; - } - } - cache->cacheEntries[i].dirty = false; - } + for (i = 0; i < cache->numberOfPages; i++) { + if (cache->cacheEntries[i].dirty) { + if (!cache->disc->writeSectors (cache->cacheEntries[i].sector, cache->cacheEntries[i].count, cache->cacheEntries[i].cache)) { + return false; + } + } + cache->cacheEntries[i].dirty = false; + } - return true; + return true; } void _NTFS_cache_invalidate (NTFS_CACHE* cache) { - unsigned int i; - if (cache==NULL) + unsigned int i; + if(cache==NULL) return; - _NTFS_cache_flush(cache); - for (i = 0; i < cache->numberOfPages; i++) { - cache->cacheEntries[i].sector = CACHE_FREE; - cache->cacheEntries[i].last_access = 0; - cache->cacheEntries[i].count = 0; - cache->cacheEntries[i].dirty = false; - } + _NTFS_cache_flush(cache); + for (i = 0; i < cache->numberOfPages; i++) { + cache->cacheEntries[i].sector = CACHE_FREE; + cache->cacheEntries[i].last_access = 0; + cache->cacheEntries[i].count = 0; + cache->cacheEntries[i].dirty = false; + } } diff --git a/source/libntfs/cache.h b/source/libntfs/cache.h index c0f5d1dd..d45208bf 100644 --- a/source/libntfs/cache.h +++ b/source/libntfs/cache.h @@ -49,19 +49,19 @@ #define BYTES_PER_READ 512 typedef struct { - sec_t sector; - unsigned int count; - u64 last_access; - bool dirty; - u8* cache; + sec_t sector; + unsigned int count; + u64 last_access; + bool dirty; + u8* cache; } NTFS_CACHE_ENTRY; typedef struct { - const DISC_INTERFACE* disc; - sec_t endOfPartition; - unsigned int numberOfPages; - unsigned int sectorsPerPage; - NTFS_CACHE_ENTRY* cacheEntries; + const DISC_INTERFACE* disc; + sec_t endOfPartition; + unsigned int numberOfPages; + unsigned int sectorsPerPage; + NTFS_CACHE_ENTRY* cacheEntries; } NTFS_CACHE; /* diff --git a/source/libntfs/collate.c b/source/libntfs/collate.c index 99af62bf..20e5db1e 100644 --- a/source/libntfs/collate.c +++ b/source/libntfs/collate.c @@ -33,19 +33,20 @@ #include "unistr.h" #include "logging.h" -BOOL ntfs_is_collation_rule_supported(COLLATION_RULES cr) { - /* - * FIXME: At the moment we only support COLLATION_BINARY, - * COLLATION_NTOFS_ULONG and COLLATION_FILE_NAME so we return false - * for everything else. - * JPA added COLLATION_NTOFS_SECURITY_HASH - */ - if (cr != COLLATION_BINARY && cr != COLLATION_NTOFS_ULONG - && cr != COLLATION_FILE_NAME - && cr != COLLATION_NTOFS_SECURITY_HASH - && cr != COLLATION_NTOFS_ULONGS) - return FALSE; - return TRUE; +BOOL ntfs_is_collation_rule_supported(COLLATION_RULES cr) +{ + /* + * FIXME: At the moment we only support COLLATION_BINARY, + * COLLATION_NTOFS_ULONG and COLLATION_FILE_NAME so we return false + * for everything else. + * JPA added COLLATION_NTOFS_SECURITY_HASH + */ + if (cr != COLLATION_BINARY && cr != COLLATION_NTOFS_ULONG + && cr != COLLATION_FILE_NAME + && cr != COLLATION_NTOFS_SECURITY_HASH + && cr != COLLATION_NTOFS_ULONGS) + return FALSE; + return TRUE; } /** @@ -61,20 +62,21 @@ BOOL ntfs_is_collation_rule_supported(COLLATION_RULES cr) { * Returns: */ static int ntfs_collate_binary(ntfs_volume *vol __attribute__((unused)), - const void *data1, const int data1_len, - const void *data2, const int data2_len) { - int rc; + const void *data1, const int data1_len, + const void *data2, const int data2_len) +{ + int rc; - ntfs_log_trace("Entering.\n"); - rc = memcmp(data1, data2, min(data1_len, data2_len)); - if (!rc && (data1_len != data2_len)) { - if (data1_len < data2_len) - rc = -1; - else - rc = 1; - } - ntfs_log_trace("Done, returning %i.\n", rc); - return rc; + ntfs_log_trace("Entering.\n"); + rc = memcmp(data1, data2, min(data1_len, data2_len)); + if (!rc && (data1_len != data2_len)) { + if (data1_len < data2_len) + rc = -1; + else + rc = 1; + } + ntfs_log_trace("Done, returning %i.\n", rc); + return rc; } /** @@ -90,28 +92,29 @@ static int ntfs_collate_binary(ntfs_volume *vol __attribute__((unused)), * Returns: */ static int ntfs_collate_ntofs_ulong(ntfs_volume *vol __attribute__((unused)), - const void *data1, const int data1_len, - const void *data2, const int data2_len) { - int rc; - u32 d1, d2; + const void *data1, const int data1_len, + const void *data2, const int data2_len) +{ + int rc; + u32 d1, d2; - ntfs_log_trace("Entering.\n"); - if (data1_len != data2_len || data1_len != 4) { - ntfs_log_error("data1_len or/and data2_len not equal to 4.\n"); - return NTFS_COLLATION_ERROR; - } - d1 = le32_to_cpup(data1); - d2 = le32_to_cpup(data2); - if (d1 < d2) - rc = -1; - else { - if (d1 == d2) - rc = 0; - else - rc = 1; - } - ntfs_log_trace("Done, returning %i.\n", rc); - return rc; + ntfs_log_trace("Entering.\n"); + if (data1_len != data2_len || data1_len != 4) { + ntfs_log_error("data1_len or/and data2_len not equal to 4.\n"); + return NTFS_COLLATION_ERROR; + } + d1 = le32_to_cpup(data1); + d2 = le32_to_cpup(data2); + if (d1 < d2) + rc = -1; + else { + if (d1 == d2) + rc = 0; + else + rc = 1; + } + ntfs_log_trace("Done, returning %i.\n", rc); + return rc; } /** @@ -121,37 +124,38 @@ static int ntfs_collate_ntofs_ulong(ntfs_volume *vol __attribute__((unused)), */ static int ntfs_collate_ntofs_ulongs(ntfs_volume *vol __attribute__((unused)), - const void *data1, const int data1_len, - const void *data2, const int data2_len) { - int rc; - int len; - const le32 *p1, *p2; - u32 d1, d2; + const void *data1, const int data1_len, + const void *data2, const int data2_len) +{ + int rc; + int len; + const le32 *p1, *p2; + u32 d1, d2; - ntfs_log_trace("Entering.\n"); - if ((data1_len != data2_len) || (data1_len <= 0) || (data1_len & 3)) { - ntfs_log_error("data1_len or data2_len not valid\n"); - return NTFS_COLLATION_ERROR; - } - p1 = (const le32*)data1; - p2 = (const le32*)data2; - len = data1_len; - do { - d1 = le32_to_cpup(p1); - p1++; - d2 = le32_to_cpup(p2); - p2++; - } while ((d1 == d2) && ((len -= 4) > 0)); - if (d1 < d2) - rc = -1; - else { - if (d1 == d2) - rc = 0; - else - rc = 1; - } - ntfs_log_trace("Done, returning %i.\n", rc); - return rc; + ntfs_log_trace("Entering.\n"); + if ((data1_len != data2_len) || (data1_len <= 0) || (data1_len & 3)) { + ntfs_log_error("data1_len or data2_len not valid\n"); + return NTFS_COLLATION_ERROR; + } + p1 = (const le32*)data1; + p2 = (const le32*)data2; + len = data1_len; + do { + d1 = le32_to_cpup(p1); + p1++; + d2 = le32_to_cpup(p2); + p2++; + } while ((d1 == d2) && ((len -= 4) > 0)); + if (d1 < d2) + rc = -1; + else { + if (d1 == d2) + rc = 0; + else + rc = 1; + } + ntfs_log_trace("Done, returning %i.\n", rc); + return rc; } /** @@ -168,43 +172,44 @@ static int ntfs_collate_ntofs_ulongs(ntfs_volume *vol __attribute__((unused)), * Returns: -1, 0 or 1 depending of how the keys compare */ static int ntfs_collate_ntofs_security_hash(ntfs_volume *vol __attribute__((unused)), - const void *data1, const int data1_len, - const void *data2, const int data2_len) { - int rc; - u32 d1, d2; - const u32 *p1, *p2; + const void *data1, const int data1_len, + const void *data2, const int data2_len) +{ + int rc; + u32 d1, d2; + const u32 *p1, *p2; - ntfs_log_trace("Entering.\n"); - if (data1_len != data2_len || data1_len != 8) { - ntfs_log_error("data1_len or/and data2_len not equal to 8.\n"); - return NTFS_COLLATION_ERROR; - } - p1 = (const u32*)data1; - p2 = (const u32*)data2; - d1 = le32_to_cpup(p1); - d2 = le32_to_cpup(p2); - if (d1 < d2) - rc = -1; - else { - if (d1 > d2) - rc = 1; - else { - p1++; - p2++; - d1 = le32_to_cpup(p1); - d2 = le32_to_cpup(p2); - if (d1 < d2) - rc = -1; - else { - if (d1 > d2) - rc = 1; - else - rc = 0; - } - } - } - ntfs_log_trace("Done, returning %i.\n", rc); - return rc; + ntfs_log_trace("Entering.\n"); + if (data1_len != data2_len || data1_len != 8) { + ntfs_log_error("data1_len or/and data2_len not equal to 8.\n"); + return NTFS_COLLATION_ERROR; + } + p1 = (const u32*)data1; + p2 = (const u32*)data2; + d1 = le32_to_cpup(p1); + d2 = le32_to_cpup(p2); + if (d1 < d2) + rc = -1; + else { + if (d1 > d2) + rc = 1; + else { + p1++; + p2++; + d1 = le32_to_cpup(p1); + d2 = le32_to_cpup(p2); + if (d1 < d2) + rc = -1; + else { + if (d1 > d2) + rc = 1; + else + rc = 0; + } + } + } + ntfs_log_trace("Done, returning %i.\n", rc); + return rc; } /** @@ -220,35 +225,36 @@ static int ntfs_collate_ntofs_security_hash(ntfs_volume *vol __attribute__((unus * Returns: */ static int ntfs_collate_file_name(ntfs_volume *vol, - const void *data1, const int data1_len __attribute__((unused)), - const void *data2, const int data2_len __attribute__((unused))) { - int rc; + const void *data1, const int data1_len __attribute__((unused)), + const void *data2, const int data2_len __attribute__((unused))) +{ + int rc; - ntfs_log_trace("Entering.\n"); - rc = ntfs_file_values_compare(data1, data2, NTFS_COLLATION_ERROR, - IGNORE_CASE, vol->upcase, vol->upcase_len); - if (!rc) - rc = ntfs_file_values_compare(data1, data2, - NTFS_COLLATION_ERROR, CASE_SENSITIVE, - vol->upcase, vol->upcase_len); - ntfs_log_trace("Done, returning %i.\n", rc); - return rc; + ntfs_log_trace("Entering.\n"); + rc = ntfs_file_values_compare(data1, data2, NTFS_COLLATION_ERROR, + IGNORE_CASE, vol->upcase, vol->upcase_len); + if (!rc) + rc = ntfs_file_values_compare(data1, data2, + NTFS_COLLATION_ERROR, CASE_SENSITIVE, + vol->upcase, vol->upcase_len); + ntfs_log_trace("Done, returning %i.\n", rc); + return rc; } typedef int (*ntfs_collate_func_t)(ntfs_volume *, const void *, const int, - const void *, const int); + const void *, const int); static ntfs_collate_func_t ntfs_do_collate0x0[3] = { - ntfs_collate_binary, - ntfs_collate_file_name, - NULL/*ntfs_collate_unicode_string*/, + ntfs_collate_binary, + ntfs_collate_file_name, + NULL/*ntfs_collate_unicode_string*/, }; static ntfs_collate_func_t ntfs_do_collate0x1[4] = { - ntfs_collate_ntofs_ulong, - NULL/*ntfs_collate_ntofs_sid*/, - ntfs_collate_ntofs_security_hash, - ntfs_collate_ntofs_ulongs + ntfs_collate_ntofs_ulong, + NULL/*ntfs_collate_ntofs_sid*/, + ntfs_collate_ntofs_security_hash, + ntfs_collate_ntofs_ulongs }; /** @@ -270,40 +276,41 @@ static ntfs_collate_func_t ntfs_do_collate0x1[4] = { * Return NTFS_COLLATION_ERROR if error occurred. */ int ntfs_collate(ntfs_volume *vol, COLLATION_RULES cr, - const void *data1, const int data1_len, - const void *data2, const int data2_len) { - int i; + const void *data1, const int data1_len, + const void *data2, const int data2_len) +{ + int i; - ntfs_log_trace("Entering.\n"); - if (!vol || !data1 || !data2 || data1_len < 0 || data2_len < 0) { - ntfs_log_error("Invalid arguments passed.\n"); - return NTFS_COLLATION_ERROR; - } - /* - * FIXME: At the moment we only support COLLATION_BINARY, - * COLLATION_NTOFS_ULONG and COLLATION_FILE_NAME so we return error - * for everything else. - * JPA added COLLATION_NTOFS_SECURITY_HASH - * JPA added COLLATION_NTOFS_ULONGS - */ - if (cr != COLLATION_BINARY && cr != COLLATION_NTOFS_ULONG - && cr != COLLATION_FILE_NAME - && cr != COLLATION_NTOFS_SECURITY_HASH - && cr != COLLATION_NTOFS_ULONGS) - goto err; - i = le32_to_cpu(cr); - if (i < 0) - goto err; - if (i <= 0x02) - return ntfs_do_collate0x0[i](vol, data1, data1_len, - data2, data2_len); - if (i < 0x10) - goto err; - i -= 0x10; - if (i <= 3) - return ntfs_do_collate0x1[i](vol, data1, data1_len, - data2, data2_len); + ntfs_log_trace("Entering.\n"); + if (!vol || !data1 || !data2 || data1_len < 0 || data2_len < 0) { + ntfs_log_error("Invalid arguments passed.\n"); + return NTFS_COLLATION_ERROR; + } + /* + * FIXME: At the moment we only support COLLATION_BINARY, + * COLLATION_NTOFS_ULONG and COLLATION_FILE_NAME so we return error + * for everything else. + * JPA added COLLATION_NTOFS_SECURITY_HASH + * JPA added COLLATION_NTOFS_ULONGS + */ + if (cr != COLLATION_BINARY && cr != COLLATION_NTOFS_ULONG + && cr != COLLATION_FILE_NAME + && cr != COLLATION_NTOFS_SECURITY_HASH + && cr != COLLATION_NTOFS_ULONGS) + goto err; + i = le32_to_cpu(cr); + if (i < 0) + goto err; + if (i <= 0x02) + return ntfs_do_collate0x0[i](vol, data1, data1_len, + data2, data2_len); + if (i < 0x10) + goto err; + i -= 0x10; + if (i <= 3) + return ntfs_do_collate0x1[i](vol, data1, data1_len, + data2, data2_len); err: - ntfs_log_debug("Unknown collation rule.\n"); - return NTFS_COLLATION_ERROR; + ntfs_log_debug("Unknown collation rule.\n"); + return NTFS_COLLATION_ERROR; } diff --git a/source/libntfs/collate.h b/source/libntfs/collate.h index 239e5d6f..9c0ec9bc 100644 --- a/source/libntfs/collate.h +++ b/source/libntfs/collate.h @@ -31,7 +31,7 @@ extern BOOL ntfs_is_collation_rule_supported(COLLATION_RULES cr); extern int ntfs_collate(ntfs_volume *vol, COLLATION_RULES cr, - const void *data1, const int data1_len, - const void *data2, const int data2_len); + const void *data1, const int data1_len, + const void *data2, const int data2_len); #endif /* _NTFS_COLLATE_H */ diff --git a/source/libntfs/compat.c b/source/libntfs/compat.c index 4ba79ae8..e9b3d5df 100644 --- a/source/libntfs/compat.c +++ b/source/libntfs/compat.c @@ -35,32 +35,33 @@ * * Returns: */ -int ffs(int x) { - int r = 1; +int ffs(int x) +{ + int r = 1; - if (!x) - return 0; - if (!(x & 0xffff)) { - x >>= 16; - r += 16; - } - if (!(x & 0xff)) { - x >>= 8; - r += 8; - } - if (!(x & 0xf)) { - x >>= 4; - r += 4; - } - if (!(x & 3)) { - x >>= 2; - r += 2; - } - if (!(x & 1)) { - x >>= 1; - r += 1; - } - return r; + if (!x) + return 0; + if (!(x & 0xffff)) { + x >>= 16; + r += 16; + } + if (!(x & 0xff)) { + x >>= 8; + r += 8; + } + if (!(x & 0xf)) { + x >>= 4; + r += 4; + } + if (!(x & 3)) { + x >>= 2; + r += 2; + } + if (!(x & 1)) { + x >>= 1; + r += 1; + } + return r; } #endif /* HAVE_FFS */ @@ -120,33 +121,33 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.7 2009/03/27 09:09:59 jpa #endif int daemon(int nochdir, int noclose) { - int fd; + int fd; - switch (fork()) { - case -1: - return (-1); - case 0: - break; - default: - _exit(0); - } + switch (fork()) { + case -1: + return (-1); + case 0: + break; + default: + _exit(0); + } - if (setsid() == -1) - return (-1); + if (setsid() == -1) + return (-1); - if (!nochdir) - (void)chdir("/"); + if (!nochdir) + (void)chdir("/"); - if (!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1) { - (void)dup2(fd, 0); - (void)dup2(fd, 1); - (void)dup2(fd, 2); - if (fd > 2) - (void)close (fd); - } - return (0); + if (!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1) { + (void)dup2(fd, 0); + (void)dup2(fd, 1); + (void)dup2(fd, 2); + if (fd > 2) + (void)close (fd); + } + return (0); } -/* +/* * End: src/lib/libresolv2/common/bsd/daemon.c *************************************************************/ #endif /* HAVE_DAEMON */ @@ -208,7 +209,7 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.7 2009/03/27 09:09:59 jpa /* * Get next token from string *stringp, where tokens are possibly-empty - * strings separated by characters from delim. + * strings separated by characters from delim. * * Writes NULs into the string at *stringp to end tokens. * delim need not remain constant from call to call. @@ -218,31 +219,31 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.7 2009/03/27 09:09:59 jpa * If *stringp is NULL, strsep returns NULL. */ char *strsep(char **stringp, const char *delim) { - char *s; - const char *spanp; - int c, sc; - char *tok; + char *s; + const char *spanp; + int c, sc; + char *tok; - if ((s = *stringp) == NULL) - return (NULL); - for (tok = s;;) { - c = *s++; - spanp = delim; - do { - if ((sc = *spanp++) == c) { - if (c == 0) - s = NULL; - else - s[-1] = 0; - *stringp = s; - return (tok); - } - } while (sc != 0); - } - /* NOTREACHED */ + if ((s = *stringp) == NULL) + return (NULL); + for (tok = s;;) { + c = *s++; + spanp = delim; + do { + if ((sc = *spanp++) == c) { + if (c == 0) + s = NULL; + else + s[-1] = 0; + *stringp = s; + return (tok); + } + } while (sc != 0); + } + /* NOTREACHED */ } -/* +/* * End: src/lib/libresolv2/common/bsd/strsep.c *************************************************************/ #endif /* HAVE_STRSEP */ diff --git a/source/libntfs/compat.h b/source/libntfs/compat.h index fc5926a7..957752a0 100644 --- a/source/libntfs/compat.h +++ b/source/libntfs/compat.h @@ -67,7 +67,7 @@ extern char *strsep(char **stringp, const char *delim); #include "mem_allocate.h" -#define XATTR_CREATE 1 +#define XATTR_CREATE 1 #define XATTR_REPLACE 2 #define MINORBITS 20 @@ -75,7 +75,7 @@ extern char *strsep(char **stringp, const char *delim); #define major(dev) ((unsigned int) ((dev) >> MINORBITS)) #define minor(dev) ((unsigned int) ((dev) & MINORMASK)) -#define mkdev(ma,mi) (((ma) << MINORBITS) | (mi)) +#define mkdev(ma,mi) (((ma) << MINORBITS) | (mi)) #define random rand #endif /* defined GEKKO */ diff --git a/source/libntfs/compress.c b/source/libntfs/compress.c index fee24f99..4db1826d 100644 --- a/source/libntfs/compress.c +++ b/source/libntfs/compress.c @@ -28,7 +28,7 @@ * this was put into public domain in 1988 by Haruhiko OKUMURA). * * LZHUF.C English version 1.0 - * Based on Japanese version 29-NOV-1988 + * Based on Japanese version 29-NOV-1988 * LZSS coded by Haruhiko OKUMURA * Adaptive Huffman Coding coded by Haruyasu YOSHIZAKI * Edited and translated to English by Kenji RIKITAKE @@ -66,42 +66,43 @@ * enum ntfs_compression_constants - constants used in the compression code */ typedef enum { - /* Token types and access mask. */ - NTFS_SYMBOL_TOKEN = 0, - NTFS_PHRASE_TOKEN = 1, - NTFS_TOKEN_MASK = 1, + /* Token types and access mask. */ + NTFS_SYMBOL_TOKEN = 0, + NTFS_PHRASE_TOKEN = 1, + NTFS_TOKEN_MASK = 1, - /* Compression sub-block constants. */ - NTFS_SB_SIZE_MASK = 0x0fff, - NTFS_SB_SIZE = 0x1000, - NTFS_SB_IS_COMPRESSED = 0x8000, + /* Compression sub-block constants. */ + NTFS_SB_SIZE_MASK = 0x0fff, + NTFS_SB_SIZE = 0x1000, + NTFS_SB_IS_COMPRESSED = 0x8000, } ntfs_compression_constants; #define THRESHOLD 3 /* minimal match length for compression */ #define NIL NTFS_SB_SIZE /* End of tree's node */ struct COMPRESS_CONTEXT { - const unsigned char *inbuf; - unsigned int len; - unsigned int nbt; - int match_position; - unsigned int match_length; - u16 lson[NTFS_SB_SIZE + 1]; - u16 rson[NTFS_SB_SIZE + 257]; - u16 dad[NTFS_SB_SIZE + 1]; + const unsigned char *inbuf; + unsigned int len; + unsigned int nbt; + int match_position; + unsigned int match_length; + u16 lson[NTFS_SB_SIZE + 1]; + u16 rson[NTFS_SB_SIZE + 257]; + u16 dad[NTFS_SB_SIZE + 1]; } ; /* * Initialize the match tree */ -static void ntfs_init_compress_tree(struct COMPRESS_CONTEXT *pctx) { - int i; +static void ntfs_init_compress_tree(struct COMPRESS_CONTEXT *pctx) +{ + int i; - for (i = NTFS_SB_SIZE + 1; i <= NTFS_SB_SIZE + 256; i++) - pctx->rson[i] = NIL; /* root */ - for (i = 0; i < NTFS_SB_SIZE; i++) - pctx->dad[i] = NIL; /* node */ + for (i = NTFS_SB_SIZE + 1; i <= NTFS_SB_SIZE + 256; i++) + pctx->rson[i] = NIL; /* root */ + for (i = 0; i < NTFS_SB_SIZE; i++) + pctx->dad[i] = NIL; /* node */ } /* @@ -110,80 +111,81 @@ static void ntfs_init_compress_tree(struct COMPRESS_CONTEXT *pctx) { */ static void ntfs_new_node (struct COMPRESS_CONTEXT *pctx, - unsigned int r) { - unsigned int pp; - BOOL less; - BOOL done; - const unsigned char *key; - int c; - unsigned int mxi; - unsigned int mxl; + unsigned int r) +{ + unsigned int pp; + BOOL less; + BOOL done; + const unsigned char *key; + int c; + unsigned int mxi; + unsigned int mxl; - mxl = (1 << (16 - pctx->nbt)) + 2; - less = FALSE; - done = FALSE; - key = &pctx->inbuf[r]; - pp = NTFS_SB_SIZE + 1 + key[0]; - pctx->rson[r] = pctx->lson[r] = NIL; - pctx->match_length = 0; - do { - if (!less) { - if (pctx->rson[pp] != NIL) - pp = pctx->rson[pp]; - else { - pctx->rson[pp] = r; - pctx->dad[r] = pp; - done = TRUE; - } - } else { - if (pctx->lson[pp] != NIL) - pp = pctx->lson[pp]; - else { - pctx->lson[pp] = r; - pctx->dad[r] = pp; - done = TRUE; - } - } - if (!done) { - register unsigned int i; - register const unsigned char *p1,*p2; + mxl = (1 << (16 - pctx->nbt)) + 2; + less = FALSE; + done = FALSE; + key = &pctx->inbuf[r]; + pp = NTFS_SB_SIZE + 1 + key[0]; + pctx->rson[r] = pctx->lson[r] = NIL; + pctx->match_length = 0; + do { + if (!less) { + if (pctx->rson[pp] != NIL) + pp = pctx->rson[pp]; + else { + pctx->rson[pp] = r; + pctx->dad[r] = pp; + done = TRUE; + } + } else { + if (pctx->lson[pp] != NIL) + pp = pctx->lson[pp]; + else { + pctx->lson[pp] = r; + pctx->dad[r] = pp; + done = TRUE; + } + } + if (!done) { + register unsigned int i; + register const unsigned char *p1,*p2; - i = 1; - p1 = key; - p2 = &pctx->inbuf[pp]; - mxi = NTFS_SB_SIZE - r; - do { - } while ((p1[i] == p2[i]) && (++i < mxi)); - less = (i < mxi) && (p1[i] < p2[i]); - if (i >= THRESHOLD) { - if (i > pctx->match_length) { - pctx->match_position = - r - pp + 2*NTFS_SB_SIZE - 1; - if ((pctx->match_length = i) > mxl) { - i = pctx->rson[pp]; - pctx->rson[r] = i; - pctx->dad[i] = r; - i = pctx->lson[pp]; - pctx->lson[r] = i; - pctx->dad[i] = r; - i = pctx->dad[pp]; - pctx->dad[r] = i; - if (pctx->rson[i] == pp) - pctx->rson[i] = r; - else - pctx->lson[i] = r; - pctx->dad[pp] = NIL; /* remove pp */ - done = TRUE; - pctx->match_length = mxl; - } - } else - if ((i == pctx->match_length) - && ((c = (r - pp + 2*NTFS_SB_SIZE - 1)) - < pctx->match_position)) - pctx->match_position = c; - } - } - } while (!done); + i = 1; + p1 = key; + p2 = &pctx->inbuf[pp]; + mxi = NTFS_SB_SIZE - r; + do { + } while ((p1[i] == p2[i]) && (++i < mxi)); + less = (i < mxi) && (p1[i] < p2[i]); + if (i >= THRESHOLD) { + if (i > pctx->match_length) { + pctx->match_position = + r - pp + 2*NTFS_SB_SIZE - 1; + if ((pctx->match_length = i) > mxl) { + i = pctx->rson[pp]; + pctx->rson[r] = i; + pctx->dad[i] = r; + i = pctx->lson[pp]; + pctx->lson[r] = i; + pctx->dad[i] = r; + i = pctx->dad[pp]; + pctx->dad[r] = i; + if (pctx->rson[i] == pp) + pctx->rson[i] = r; + else + pctx->lson[i] = r; + pctx->dad[pp] = NIL; /* remove pp */ + done = TRUE; + pctx->match_length = mxl; + } + } else + if ((i == pctx->match_length) + && ((c = (r - pp + 2*NTFS_SB_SIZE - 1)) + < pctx->match_position)) + pctx->match_position = c; + } + } + } while (!done); } /* @@ -194,47 +196,48 @@ static void ntfs_new_node (struct COMPRESS_CONTEXT *pctx, * or zero if there was a bug */ -static unsigned int ntfs_nextmatch(struct COMPRESS_CONTEXT *pctx, unsigned int rr, int dd) { - unsigned int bestlen = 0; +static unsigned int ntfs_nextmatch(struct COMPRESS_CONTEXT *pctx, unsigned int rr, int dd) +{ + unsigned int bestlen = 0; - do { - rr++; - if (pctx->match_length > 0) - pctx->match_length--; - if (!pctx->len) { - ntfs_log_error("compress bug : void run\n"); - goto bug; - } - if (--pctx->len) { - if (rr >= NTFS_SB_SIZE) { - ntfs_log_error("compress bug : buffer overflow\n"); - goto bug; - } - if (((rr + bestlen) < NTFS_SB_SIZE)) { - while ((unsigned int)(1 << pctx->nbt) <= (rr - 1)) - pctx->nbt++; - ntfs_new_node(pctx,rr); - if (pctx->match_length > bestlen) - bestlen = pctx->match_length; - } else - if (dd > 0) { - rr += dd; - if ((int)pctx->match_length > dd) - pctx->match_length -= dd; - else - pctx->match_length = 0; - if ((int)pctx->len < dd) { - ntfs_log_error("compress bug : run overflows\n"); - goto bug; - } - pctx->len -= dd; - dd = 0; - } - } - } while (dd-- > 0); - return (rr); + do { + rr++; + if (pctx->match_length > 0) + pctx->match_length--; + if (!pctx->len) { + ntfs_log_error("compress bug : void run\n"); + goto bug; + } + if (--pctx->len) { + if (rr >= NTFS_SB_SIZE) { + ntfs_log_error("compress bug : buffer overflow\n"); + goto bug; + } + if (((rr + bestlen) < NTFS_SB_SIZE)) { + while ((unsigned int)(1 << pctx->nbt) <= (rr - 1)) + pctx->nbt++; + ntfs_new_node(pctx,rr); + if (pctx->match_length > bestlen) + bestlen = pctx->match_length; + } else + if (dd > 0) { + rr += dd; + if ((int)pctx->match_length > dd) + pctx->match_length -= dd; + else + pctx->match_length = 0; + if ((int)pctx->len < dd) { + ntfs_log_error("compress bug : run overflows\n"); + goto bug; + } + pctx->len -= dd; + dd = 0; + } + } + } while (dd-- > 0); + return (rr); bug : - return (0); + return (0); } /* @@ -244,90 +247,91 @@ bug : * or zero if there was an error */ -static unsigned int ntfs_compress_block(const char *inbuf, unsigned int size, char *outbuf) { - struct COMPRESS_CONTEXT *pctx; - char *ptag; - int dd; - unsigned int rr; - unsigned int last_match_length; - unsigned int q; - unsigned int xout; - unsigned int ntag; +static unsigned int ntfs_compress_block(const char *inbuf, unsigned int size, char *outbuf) +{ + struct COMPRESS_CONTEXT *pctx; + char *ptag; + int dd; + unsigned int rr; + unsigned int last_match_length; + unsigned int q; + unsigned int xout; + unsigned int ntag; - pctx = (struct COMPRESS_CONTEXT*)malloc(sizeof(struct COMPRESS_CONTEXT)); - if (pctx) { - pctx->inbuf = (const unsigned char*)inbuf; - ntfs_init_compress_tree(pctx); - xout = 2; - ntag = 0; - ptag = &outbuf[xout++]; - *ptag = 0; - rr = 0; - pctx->nbt = 4; - pctx->len = size; - pctx->match_length = 0; - ntfs_new_node(pctx,0); - do { - if (pctx->match_length > pctx->len) - pctx->match_length = pctx->len; - if (pctx->match_length < THRESHOLD) { - pctx->match_length = 1; - if (ntag >= 8) { - ntag = 0; - ptag = &outbuf[xout++]; - *ptag = 0; - } - outbuf[xout++] = inbuf[rr]; - ntag++; - } else { - while ((unsigned int)(1 << pctx->nbt) <= (rr - 1)) - pctx->nbt++; - q = (pctx->match_position << (16 - pctx->nbt)) - + pctx->match_length - THRESHOLD; - if (ntag >= 8) { - ntag = 0; - ptag = &outbuf[xout++]; - *ptag = 0; - } - *ptag |= 1 << ntag++; - outbuf[xout++] = q & 255; - outbuf[xout++] = (q >> 8) & 255; - } - last_match_length = pctx->match_length; - dd = last_match_length; - if (dd-- > 0) { - rr = ntfs_nextmatch(pctx,rr,dd); - if (!rr) - goto bug; - } - /* - * stop if input is exhausted or output has exceeded - * the maximum size. Two extra bytes have to be - * reserved in output buffer, as 3 bytes may be - * output in a loop. - */ - } while ((pctx->len > 0) - && (rr < size) && (xout < (NTFS_SB_SIZE + 2))); - /* uncompressed must be full size, so accept if better */ - if (xout < (NTFS_SB_SIZE + 2)) { - outbuf[0] = (xout - 3) & 255; - outbuf[1] = 0xb0 + (((xout - 3) >> 8) & 15); - } else { - memcpy(&outbuf[2],inbuf,size); - if (size < NTFS_SB_SIZE) - memset(&outbuf[size+2],0,NTFS_SB_SIZE - size); - outbuf[0] = 0xff; - outbuf[1] = 0x3f; - xout = NTFS_SB_SIZE + 2; - } - free(pctx); - } else { - xout = 0; - errno = ENOMEM; - } - return (xout); /* 0 for an error, > size if cannot compress */ + pctx = (struct COMPRESS_CONTEXT*)malloc(sizeof(struct COMPRESS_CONTEXT)); + if (pctx) { + pctx->inbuf = (const unsigned char*)inbuf; + ntfs_init_compress_tree(pctx); + xout = 2; + ntag = 0; + ptag = &outbuf[xout++]; + *ptag = 0; + rr = 0; + pctx->nbt = 4; + pctx->len = size; + pctx->match_length = 0; + ntfs_new_node(pctx,0); + do { + if (pctx->match_length > pctx->len) + pctx->match_length = pctx->len; + if (pctx->match_length < THRESHOLD) { + pctx->match_length = 1; + if (ntag >= 8) { + ntag = 0; + ptag = &outbuf[xout++]; + *ptag = 0; + } + outbuf[xout++] = inbuf[rr]; + ntag++; + } else { + while ((unsigned int)(1 << pctx->nbt) <= (rr - 1)) + pctx->nbt++; + q = (pctx->match_position << (16 - pctx->nbt)) + + pctx->match_length - THRESHOLD; + if (ntag >= 8) { + ntag = 0; + ptag = &outbuf[xout++]; + *ptag = 0; + } + *ptag |= 1 << ntag++; + outbuf[xout++] = q & 255; + outbuf[xout++] = (q >> 8) & 255; + } + last_match_length = pctx->match_length; + dd = last_match_length; + if (dd-- > 0) { + rr = ntfs_nextmatch(pctx,rr,dd); + if (!rr) + goto bug; + } + /* + * stop if input is exhausted or output has exceeded + * the maximum size. Two extra bytes have to be + * reserved in output buffer, as 3 bytes may be + * output in a loop. + */ + } while ((pctx->len > 0) + && (rr < size) && (xout < (NTFS_SB_SIZE + 2))); + /* uncompressed must be full size, so accept if better */ + if (xout < (NTFS_SB_SIZE + 2)) { + outbuf[0] = (xout - 3) & 255; + outbuf[1] = 0xb0 + (((xout - 3) >> 8) & 15); + } else { + memcpy(&outbuf[2],inbuf,size); + if (size < NTFS_SB_SIZE) + memset(&outbuf[size+2],0,NTFS_SB_SIZE - size); + outbuf[0] = 0xff; + outbuf[1] = 0x3f; + xout = NTFS_SB_SIZE + 2; + } + free(pctx); + } else { + xout = 0; + errno = ENOMEM; + } + return (xout); /* 0 for an error, > size if cannot compress */ bug : - return (0); + return (0); } /** @@ -346,171 +350,172 @@ bug : * Return 0 if success or -EOVERFLOW on error in the compressed stream. */ static int ntfs_decompress(u8 *dest, const u32 dest_size, - u8 *const cb_start, const u32 cb_size) { - /* - * Pointers into the compressed data, i.e. the compression block (cb), - * and the therein contained sub-blocks (sb). - */ - u8 *cb_end = cb_start + cb_size; /* End of cb. */ - u8 *cb = cb_start; /* Current position in cb. */ - u8 *cb_sb_start = cb; /* Beginning of the current sb in the cb. */ - u8 *cb_sb_end; /* End of current sb / beginning of next sb. */ - /* Variables for uncompressed data / destination. */ - u8 *dest_end = dest + dest_size; /* End of dest buffer. */ - u8 *dest_sb_start; /* Start of current sub-block in dest. */ - u8 *dest_sb_end; /* End of current sb in dest. */ - /* Variables for tag and token parsing. */ - u8 tag; /* Current tag. */ - int token; /* Loop counter for the eight tokens in tag. */ + u8 *const cb_start, const u32 cb_size) +{ + /* + * Pointers into the compressed data, i.e. the compression block (cb), + * and the therein contained sub-blocks (sb). + */ + u8 *cb_end = cb_start + cb_size; /* End of cb. */ + u8 *cb = cb_start; /* Current position in cb. */ + u8 *cb_sb_start = cb; /* Beginning of the current sb in the cb. */ + u8 *cb_sb_end; /* End of current sb / beginning of next sb. */ + /* Variables for uncompressed data / destination. */ + u8 *dest_end = dest + dest_size; /* End of dest buffer. */ + u8 *dest_sb_start; /* Start of current sub-block in dest. */ + u8 *dest_sb_end; /* End of current sb in dest. */ + /* Variables for tag and token parsing. */ + u8 tag; /* Current tag. */ + int token; /* Loop counter for the eight tokens in tag. */ - ntfs_log_trace("Entering, cb_size = 0x%x.\n", (unsigned)cb_size); + ntfs_log_trace("Entering, cb_size = 0x%x.\n", (unsigned)cb_size); do_next_sb: - ntfs_log_debug("Beginning sub-block at offset = %d in the cb.\n", - (int)(cb - cb_start)); - /* - * Have we reached the end of the compression block or the end of the - * decompressed data? The latter can happen for example if the current - * position in the compression block is one byte before its end so the - * first two checks do not detect it. - */ - if (cb == cb_end || !le16_to_cpup((le16*)cb) || dest == dest_end) { - ntfs_log_debug("Completed. Returning success (0).\n"); - return 0; - } - /* Setup offset for the current sub-block destination. */ - dest_sb_start = dest; - dest_sb_end = dest + NTFS_SB_SIZE; - /* Check that we are still within allowed boundaries. */ - if (dest_sb_end > dest_end) - goto return_overflow; - /* Does the minimum size of a compressed sb overflow valid range? */ - if (cb + 6 > cb_end) - goto return_overflow; - /* Setup the current sub-block source pointers and validate range. */ - cb_sb_start = cb; - cb_sb_end = cb_sb_start + (le16_to_cpup((le16*)cb) & NTFS_SB_SIZE_MASK) - + 3; - if (cb_sb_end > cb_end) - goto return_overflow; - /* Now, we are ready to process the current sub-block (sb). */ - if (!(le16_to_cpup((le16*)cb) & NTFS_SB_IS_COMPRESSED)) { - ntfs_log_debug("Found uncompressed sub-block.\n"); - /* This sb is not compressed, just copy it into destination. */ - /* Advance source position to first data byte. */ - cb += 2; - /* An uncompressed sb must be full size. */ - if (cb_sb_end - cb != NTFS_SB_SIZE) - goto return_overflow; - /* Copy the block and advance the source position. */ - memcpy(dest, cb, NTFS_SB_SIZE); - cb += NTFS_SB_SIZE; - /* Advance destination position to next sub-block. */ - dest += NTFS_SB_SIZE; - goto do_next_sb; - } - ntfs_log_debug("Found compressed sub-block.\n"); - /* This sb is compressed, decompress it into destination. */ - /* Forward to the first tag in the sub-block. */ - cb += 2; + ntfs_log_debug("Beginning sub-block at offset = %d in the cb.\n", + (int)(cb - cb_start)); + /* + * Have we reached the end of the compression block or the end of the + * decompressed data? The latter can happen for example if the current + * position in the compression block is one byte before its end so the + * first two checks do not detect it. + */ + if (cb == cb_end || !le16_to_cpup((le16*)cb) || dest == dest_end) { + ntfs_log_debug("Completed. Returning success (0).\n"); + return 0; + } + /* Setup offset for the current sub-block destination. */ + dest_sb_start = dest; + dest_sb_end = dest + NTFS_SB_SIZE; + /* Check that we are still within allowed boundaries. */ + if (dest_sb_end > dest_end) + goto return_overflow; + /* Does the minimum size of a compressed sb overflow valid range? */ + if (cb + 6 > cb_end) + goto return_overflow; + /* Setup the current sub-block source pointers and validate range. */ + cb_sb_start = cb; + cb_sb_end = cb_sb_start + (le16_to_cpup((le16*)cb) & NTFS_SB_SIZE_MASK) + + 3; + if (cb_sb_end > cb_end) + goto return_overflow; + /* Now, we are ready to process the current sub-block (sb). */ + if (!(le16_to_cpup((le16*)cb) & NTFS_SB_IS_COMPRESSED)) { + ntfs_log_debug("Found uncompressed sub-block.\n"); + /* This sb is not compressed, just copy it into destination. */ + /* Advance source position to first data byte. */ + cb += 2; + /* An uncompressed sb must be full size. */ + if (cb_sb_end - cb != NTFS_SB_SIZE) + goto return_overflow; + /* Copy the block and advance the source position. */ + memcpy(dest, cb, NTFS_SB_SIZE); + cb += NTFS_SB_SIZE; + /* Advance destination position to next sub-block. */ + dest += NTFS_SB_SIZE; + goto do_next_sb; + } + ntfs_log_debug("Found compressed sub-block.\n"); + /* This sb is compressed, decompress it into destination. */ + /* Forward to the first tag in the sub-block. */ + cb += 2; do_next_tag: - if (cb == cb_sb_end) { - /* Check if the decompressed sub-block was not full-length. */ - if (dest < dest_sb_end) { - int nr_bytes = dest_sb_end - dest; + if (cb == cb_sb_end) { + /* Check if the decompressed sub-block was not full-length. */ + if (dest < dest_sb_end) { + int nr_bytes = dest_sb_end - dest; - ntfs_log_debug("Filling incomplete sub-block with zeroes.\n"); - /* Zero remainder and update destination position. */ - memset(dest, 0, nr_bytes); - dest += nr_bytes; - } - /* We have finished the current sub-block. */ - goto do_next_sb; - } - /* Check we are still in range. */ - if (cb > cb_sb_end || dest > dest_sb_end) - goto return_overflow; - /* Get the next tag and advance to first token. */ - tag = *cb++; - /* Parse the eight tokens described by the tag. */ - for (token = 0; token < 8; token++, tag >>= 1) { - u16 lg, pt, length, max_non_overlap; - register u16 i; - u8 *dest_back_addr; + ntfs_log_debug("Filling incomplete sub-block with zeroes.\n"); + /* Zero remainder and update destination position. */ + memset(dest, 0, nr_bytes); + dest += nr_bytes; + } + /* We have finished the current sub-block. */ + goto do_next_sb; + } + /* Check we are still in range. */ + if (cb > cb_sb_end || dest > dest_sb_end) + goto return_overflow; + /* Get the next tag and advance to first token. */ + tag = *cb++; + /* Parse the eight tokens described by the tag. */ + for (token = 0; token < 8; token++, tag >>= 1) { + u16 lg, pt, length, max_non_overlap; + register u16 i; + u8 *dest_back_addr; - /* Check if we are done / still in range. */ - if (cb >= cb_sb_end || dest > dest_sb_end) - break; - /* Determine token type and parse appropriately.*/ - if ((tag & NTFS_TOKEN_MASK) == NTFS_SYMBOL_TOKEN) { - /* - * We have a symbol token, copy the symbol across, and - * advance the source and destination positions. - */ - *dest++ = *cb++; - /* Continue with the next token. */ - continue; - } - /* - * We have a phrase token. Make sure it is not the first tag in - * the sb as this is illegal and would confuse the code below. - */ - if (dest == dest_sb_start) - goto return_overflow; - /* - * Determine the number of bytes to go back (p) and the number - * of bytes to copy (l). We use an optimized algorithm in which - * we first calculate log2(current destination position in sb), - * which allows determination of l and p in O(1) rather than - * O(n). We just need an arch-optimized log2() function now. - */ - lg = 0; - for (i = dest - dest_sb_start - 1; i >= 0x10; i >>= 1) - lg++; - /* Get the phrase token into i. */ - pt = le16_to_cpup((le16*)cb); - /* - * Calculate starting position of the byte sequence in - * the destination using the fact that p = (pt >> (12 - lg)) + 1 - * and make sure we don't go too far back. - */ - dest_back_addr = dest - (pt >> (12 - lg)) - 1; - if (dest_back_addr < dest_sb_start) - goto return_overflow; - /* Now calculate the length of the byte sequence. */ - length = (pt & (0xfff >> lg)) + 3; - /* Verify destination is in range. */ - if (dest + length > dest_sb_end) - goto return_overflow; - /* The number of non-overlapping bytes. */ - max_non_overlap = dest - dest_back_addr; - if (length <= max_non_overlap) { - /* The byte sequence doesn't overlap, just copy it. */ - memcpy(dest, dest_back_addr, length); - /* Advance destination pointer. */ - dest += length; - } else { - /* - * The byte sequence does overlap, copy non-overlapping - * part and then do a slow byte by byte copy for the - * overlapping part. Also, advance the destination - * pointer. - */ - memcpy(dest, dest_back_addr, max_non_overlap); - dest += max_non_overlap; - dest_back_addr += max_non_overlap; - length -= max_non_overlap; - while (length--) - *dest++ = *dest_back_addr++; - } - /* Advance source position and continue with the next token. */ - cb += 2; - } - /* No tokens left in the current tag. Continue with the next tag. */ - goto do_next_tag; + /* Check if we are done / still in range. */ + if (cb >= cb_sb_end || dest > dest_sb_end) + break; + /* Determine token type and parse appropriately.*/ + if ((tag & NTFS_TOKEN_MASK) == NTFS_SYMBOL_TOKEN) { + /* + * We have a symbol token, copy the symbol across, and + * advance the source and destination positions. + */ + *dest++ = *cb++; + /* Continue with the next token. */ + continue; + } + /* + * We have a phrase token. Make sure it is not the first tag in + * the sb as this is illegal and would confuse the code below. + */ + if (dest == dest_sb_start) + goto return_overflow; + /* + * Determine the number of bytes to go back (p) and the number + * of bytes to copy (l). We use an optimized algorithm in which + * we first calculate log2(current destination position in sb), + * which allows determination of l and p in O(1) rather than + * O(n). We just need an arch-optimized log2() function now. + */ + lg = 0; + for (i = dest - dest_sb_start - 1; i >= 0x10; i >>= 1) + lg++; + /* Get the phrase token into i. */ + pt = le16_to_cpup((le16*)cb); + /* + * Calculate starting position of the byte sequence in + * the destination using the fact that p = (pt >> (12 - lg)) + 1 + * and make sure we don't go too far back. + */ + dest_back_addr = dest - (pt >> (12 - lg)) - 1; + if (dest_back_addr < dest_sb_start) + goto return_overflow; + /* Now calculate the length of the byte sequence. */ + length = (pt & (0xfff >> lg)) + 3; + /* Verify destination is in range. */ + if (dest + length > dest_sb_end) + goto return_overflow; + /* The number of non-overlapping bytes. */ + max_non_overlap = dest - dest_back_addr; + if (length <= max_non_overlap) { + /* The byte sequence doesn't overlap, just copy it. */ + memcpy(dest, dest_back_addr, length); + /* Advance destination pointer. */ + dest += length; + } else { + /* + * The byte sequence does overlap, copy non-overlapping + * part and then do a slow byte by byte copy for the + * overlapping part. Also, advance the destination + * pointer. + */ + memcpy(dest, dest_back_addr, max_non_overlap); + dest += max_non_overlap; + dest_back_addr += max_non_overlap; + length -= max_non_overlap; + while (length--) + *dest++ = *dest_back_addr++; + } + /* Advance source position and continue with the next token. */ + cb += 2; + } + /* No tokens left in the current tag. Continue with the next tag. */ + goto do_next_tag; return_overflow: - errno = EOVERFLOW; - ntfs_log_perror("Failed to decompress file"); - return -1; + errno = EOVERFLOW; + ntfs_log_perror("Failed to decompress file"); + return -1; } /** @@ -528,41 +533,42 @@ return_overflow: * code. Might be a bit confusing to debug but there really should never be * errors coming from here. */ -static BOOL ntfs_is_cb_compressed(ntfs_attr *na, runlist_element *rl, - VCN cb_start_vcn, int cb_clusters) { - /* - * The simplest case: the run starting at @cb_start_vcn contains - * @cb_clusters clusters which are all not sparse, thus the cb is not - * compressed. - */ +static BOOL ntfs_is_cb_compressed(ntfs_attr *na, runlist_element *rl, + VCN cb_start_vcn, int cb_clusters) +{ + /* + * The simplest case: the run starting at @cb_start_vcn contains + * @cb_clusters clusters which are all not sparse, thus the cb is not + * compressed. + */ restart: - cb_clusters -= rl->length - (cb_start_vcn - rl->vcn); - while (cb_clusters > 0) { - /* Go to the next run. */ - rl++; - /* Map the next runlist fragment if it is not mapped. */ - if (rl->lcn < LCN_HOLE || !rl->length) { - cb_start_vcn = rl->vcn; - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl || rl->lcn < LCN_HOLE || !rl->length) - return TRUE; - /* - * If the runs were merged need to deal with the - * resulting partial run so simply restart. - */ - if (rl->vcn < cb_start_vcn) - goto restart; - } - /* If the current run is sparse, the cb is compressed. */ - if (rl->lcn == LCN_HOLE) - return TRUE; - /* If the whole cb is not sparse, it is not compressed. */ - if (rl->length >= cb_clusters) - return FALSE; - cb_clusters -= rl->length; - }; - /* All cb_clusters were not sparse thus the cb is not compressed. */ - return FALSE; + cb_clusters -= rl->length - (cb_start_vcn - rl->vcn); + while (cb_clusters > 0) { + /* Go to the next run. */ + rl++; + /* Map the next runlist fragment if it is not mapped. */ + if (rl->lcn < LCN_HOLE || !rl->length) { + cb_start_vcn = rl->vcn; + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl || rl->lcn < LCN_HOLE || !rl->length) + return TRUE; + /* + * If the runs were merged need to deal with the + * resulting partial run so simply restart. + */ + if (rl->vcn < cb_start_vcn) + goto restart; + } + /* If the current run is sparse, the cb is compressed. */ + if (rl->lcn == LCN_HOLE) + return TRUE; + /* If the whole cb is not sparse, it is not compressed. */ + if (rl->length >= cb_clusters) + return FALSE; + cb_clusters -= rl->length; + }; + /* All cb_clusters were not sparse thus the cb is not compressed. */ + return FALSE; } /** @@ -586,244 +592,245 @@ restart: * to the return code of ntfs_pread(), or to EINVAL in case of invalid * arguments. */ -s64 ntfs_compressed_attr_pread(ntfs_attr *na, s64 pos, s64 count, void *b) { - s64 br, to_read, ofs, total, total2; - u64 cb_size_mask; - VCN start_vcn, vcn, end_vcn; - ntfs_volume *vol; - runlist_element *rl; - u8 *dest, *cb, *cb_pos, *cb_end; - u32 cb_size; - int err; - ATTR_FLAGS data_flags; - FILE_ATTR_FLAGS compression; - unsigned int nr_cbs, cb_clusters; +s64 ntfs_compressed_attr_pread(ntfs_attr *na, s64 pos, s64 count, void *b) +{ + s64 br, to_read, ofs, total, total2; + u64 cb_size_mask; + VCN start_vcn, vcn, end_vcn; + ntfs_volume *vol; + runlist_element *rl; + u8 *dest, *cb, *cb_pos, *cb_end; + u32 cb_size; + int err; + ATTR_FLAGS data_flags; + FILE_ATTR_FLAGS compression; + unsigned int nr_cbs, cb_clusters; - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, pos 0x%llx, count 0x%llx.\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)pos, (long long)count); - data_flags = na->data_flags; - compression = na->ni->flags & FILE_ATTR_COMPRESSED; - if (!na || !na->ni || !na->ni->vol || !b - || ((data_flags & ATTR_COMPRESSION_MASK) - != ATTR_IS_COMPRESSED) - || pos < 0 || count < 0) { - errno = EINVAL; - return -1; - } - /* - * Encrypted attributes are not supported. We return access denied, - * which is what Windows NT4 does, too. - */ - if (NAttrEncrypted(na)) { - errno = EACCES; - return -1; - } - if (!count) - return 0; - /* Truncate reads beyond end of attribute. */ - if (pos + count > na->data_size) { - if (pos >= na->data_size) { - return 0; - } - count = na->data_size - pos; - } - /* If it is a resident attribute, simply use ntfs_attr_pread(). */ - if (!NAttrNonResident(na)) - return ntfs_attr_pread(na, pos, count, b); - total = total2 = 0; - /* Zero out reads beyond initialized size. */ - if (pos + count > na->initialized_size) { - if (pos >= na->initialized_size) { - memset(b, 0, count); - return count; - } - total2 = pos + count - na->initialized_size; - count -= total2; - memset((u8*)b + count, 0, total2); - } - vol = na->ni->vol; - cb_size = na->compression_block_size; - cb_size_mask = cb_size - 1UL; - cb_clusters = na->compression_block_clusters; - - /* Need a temporary buffer for each loaded compression block. */ - cb = (u8*)ntfs_malloc(cb_size); - if (!cb) - return -1; - - /* Need a temporary buffer for each uncompressed block. */ - dest = (u8*)ntfs_malloc(cb_size); - if (!dest) { - free(cb); - return -1; - } - /* - * The first vcn in the first compression block (cb) which we need to - * decompress. - */ - start_vcn = (pos & ~cb_size_mask) >> vol->cluster_size_bits; - /* Offset in the uncompressed cb at which to start reading data. */ - ofs = pos & cb_size_mask; - /* - * The first vcn in the cb after the last cb which we need to - * decompress. - */ - end_vcn = ((pos + count + cb_size - 1) & ~cb_size_mask) >> - vol->cluster_size_bits; - /* Number of compression blocks (cbs) in the wanted vcn range. */ - nr_cbs = (end_vcn - start_vcn) << vol->cluster_size_bits >> - na->compression_block_size_bits; - cb_end = cb + cb_size; + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x, pos 0x%llx, count 0x%llx.\n", + (unsigned long long)na->ni->mft_no, na->type, + (long long)pos, (long long)count); + data_flags = na->data_flags; + compression = na->ni->flags & FILE_ATTR_COMPRESSED; + if (!na || !na->ni || !na->ni->vol || !b + || ((data_flags & ATTR_COMPRESSION_MASK) + != ATTR_IS_COMPRESSED) + || pos < 0 || count < 0) { + errno = EINVAL; + return -1; + } + /* + * Encrypted attributes are not supported. We return access denied, + * which is what Windows NT4 does, too. + */ + if (NAttrEncrypted(na)) { + errno = EACCES; + return -1; + } + if (!count) + return 0; + /* Truncate reads beyond end of attribute. */ + if (pos + count > na->data_size) { + if (pos >= na->data_size) { + return 0; + } + count = na->data_size - pos; + } + /* If it is a resident attribute, simply use ntfs_attr_pread(). */ + if (!NAttrNonResident(na)) + return ntfs_attr_pread(na, pos, count, b); + total = total2 = 0; + /* Zero out reads beyond initialized size. */ + if (pos + count > na->initialized_size) { + if (pos >= na->initialized_size) { + memset(b, 0, count); + return count; + } + total2 = pos + count - na->initialized_size; + count -= total2; + memset((u8*)b + count, 0, total2); + } + vol = na->ni->vol; + cb_size = na->compression_block_size; + cb_size_mask = cb_size - 1UL; + cb_clusters = na->compression_block_clusters; + + /* Need a temporary buffer for each loaded compression block. */ + cb = (u8*)ntfs_malloc(cb_size); + if (!cb) + return -1; + + /* Need a temporary buffer for each uncompressed block. */ + dest = (u8*)ntfs_malloc(cb_size); + if (!dest) { + free(cb); + return -1; + } + /* + * The first vcn in the first compression block (cb) which we need to + * decompress. + */ + start_vcn = (pos & ~cb_size_mask) >> vol->cluster_size_bits; + /* Offset in the uncompressed cb at which to start reading data. */ + ofs = pos & cb_size_mask; + /* + * The first vcn in the cb after the last cb which we need to + * decompress. + */ + end_vcn = ((pos + count + cb_size - 1) & ~cb_size_mask) >> + vol->cluster_size_bits; + /* Number of compression blocks (cbs) in the wanted vcn range. */ + nr_cbs = (end_vcn - start_vcn) << vol->cluster_size_bits >> + na->compression_block_size_bits; + cb_end = cb + cb_size; do_next_cb: - nr_cbs--; - cb_pos = cb; - vcn = start_vcn; - start_vcn += cb_clusters; + nr_cbs--; + cb_pos = cb; + vcn = start_vcn; + start_vcn += cb_clusters; - /* Check whether the compression block is sparse. */ - rl = ntfs_attr_find_vcn(na, vcn); - if (!rl || rl->lcn < LCN_HOLE) { - free(cb); - free(dest); - if (total) - return total; - /* FIXME: Do we want EIO or the error code? (AIA) */ - errno = EIO; - return -1; - } - if (rl->lcn == LCN_HOLE) { - /* Sparse cb, zero out destination range overlapping the cb. */ - ntfs_log_debug("Found sparse compression block.\n"); - to_read = min(count, cb_size - ofs); - memset(b, 0, to_read); - ofs = 0; - total += to_read; - count -= to_read; - b = (u8*)b + to_read; - } else if (!ntfs_is_cb_compressed(na, rl, vcn, cb_clusters)) { - s64 tdata_size, tinitialized_size; - /* - * Uncompressed cb, read it straight into the destination range - * overlapping the cb. - */ - ntfs_log_debug("Found uncompressed compression block.\n"); - /* - * Read the uncompressed data into the destination buffer. - * NOTE: We cheat a little bit here by marking the attribute as - * not compressed in the ntfs_attr structure so that we can - * read the data by simply using ntfs_attr_pread(). (-8 - * NOTE: we have to modify data_size and initialized_size - * temporarily as well... - */ - to_read = min(count, cb_size - ofs); - ofs += vcn << vol->cluster_size_bits; - NAttrClearCompressed(na); - na->data_flags &= ~ATTR_COMPRESSION_MASK; - tdata_size = na->data_size; - tinitialized_size = na->initialized_size; - na->data_size = na->initialized_size = na->allocated_size; - do { - br = ntfs_attr_pread(na, ofs, to_read, b); - if (br < 0) { - err = errno; - na->data_size = tdata_size; - na->initialized_size = tinitialized_size; - na->ni->flags |= compression; - na->data_flags = data_flags; - free(cb); - free(dest); - if (total) - return total; - errno = err; - return br; - } - total += br; - count -= br; - b = (u8*)b + br; - to_read -= br; - ofs += br; - } while (to_read > 0); - na->data_size = tdata_size; - na->initialized_size = tinitialized_size; - na->ni->flags |= compression; - na->data_flags = data_flags; - ofs = 0; - } else { - s64 tdata_size, tinitialized_size; + /* Check whether the compression block is sparse. */ + rl = ntfs_attr_find_vcn(na, vcn); + if (!rl || rl->lcn < LCN_HOLE) { + free(cb); + free(dest); + if (total) + return total; + /* FIXME: Do we want EIO or the error code? (AIA) */ + errno = EIO; + return -1; + } + if (rl->lcn == LCN_HOLE) { + /* Sparse cb, zero out destination range overlapping the cb. */ + ntfs_log_debug("Found sparse compression block.\n"); + to_read = min(count, cb_size - ofs); + memset(b, 0, to_read); + ofs = 0; + total += to_read; + count -= to_read; + b = (u8*)b + to_read; + } else if (!ntfs_is_cb_compressed(na, rl, vcn, cb_clusters)) { + s64 tdata_size, tinitialized_size; + /* + * Uncompressed cb, read it straight into the destination range + * overlapping the cb. + */ + ntfs_log_debug("Found uncompressed compression block.\n"); + /* + * Read the uncompressed data into the destination buffer. + * NOTE: We cheat a little bit here by marking the attribute as + * not compressed in the ntfs_attr structure so that we can + * read the data by simply using ntfs_attr_pread(). (-8 + * NOTE: we have to modify data_size and initialized_size + * temporarily as well... + */ + to_read = min(count, cb_size - ofs); + ofs += vcn << vol->cluster_size_bits; + NAttrClearCompressed(na); + na->data_flags &= ~ATTR_COMPRESSION_MASK; + tdata_size = na->data_size; + tinitialized_size = na->initialized_size; + na->data_size = na->initialized_size = na->allocated_size; + do { + br = ntfs_attr_pread(na, ofs, to_read, b); + if (br < 0) { + err = errno; + na->data_size = tdata_size; + na->initialized_size = tinitialized_size; + na->ni->flags |= compression; + na->data_flags = data_flags; + free(cb); + free(dest); + if (total) + return total; + errno = err; + return br; + } + total += br; + count -= br; + b = (u8*)b + br; + to_read -= br; + ofs += br; + } while (to_read > 0); + na->data_size = tdata_size; + na->initialized_size = tinitialized_size; + na->ni->flags |= compression; + na->data_flags = data_flags; + ofs = 0; + } else { + s64 tdata_size, tinitialized_size; - /* - * Compressed cb, decompress it into the temporary buffer, then - * copy the data to the destination range overlapping the cb. - */ - ntfs_log_debug("Found compressed compression block.\n"); - /* - * Read the compressed data into the temporary buffer. - * NOTE: We cheat a little bit here by marking the attribute as - * not compressed in the ntfs_attr structure so that we can - * read the raw, compressed data by simply using - * ntfs_attr_pread(). (-8 - * NOTE: We have to modify data_size and initialized_size - * temporarily as well... - */ - to_read = cb_size; - NAttrClearCompressed(na); - na->data_flags &= ~ATTR_COMPRESSION_MASK; - tdata_size = na->data_size; - tinitialized_size = na->initialized_size; - na->data_size = na->initialized_size = na->allocated_size; - do { - br = ntfs_attr_pread(na, - (vcn << vol->cluster_size_bits) + - (cb_pos - cb), to_read, cb_pos); - if (br < 0) { - err = errno; - na->data_size = tdata_size; - na->initialized_size = tinitialized_size; - na->ni->flags |= compression; - na->data_flags = data_flags; - free(cb); - free(dest); - if (total) - return total; - errno = err; - return br; - } - cb_pos += br; - to_read -= br; - } while (to_read > 0); - na->data_size = tdata_size; - na->initialized_size = tinitialized_size; - na->ni->flags |= compression; - na->data_flags = data_flags; - /* Just a precaution. */ - if (cb_pos + 2 <= cb_end) - *(u16*)cb_pos = 0; - ntfs_log_debug("Successfully read the compression block.\n"); - if (ntfs_decompress(dest, cb_size, cb, cb_size) < 0) { - err = errno; - free(cb); - free(dest); - if (total) - return total; - errno = err; - return -1; - } - to_read = min(count, cb_size - ofs); - memcpy(b, dest + ofs, to_read); - total += to_read; - count -= to_read; - b = (u8*)b + to_read; - ofs = 0; - } - /* Do we have more work to do? */ - if (nr_cbs) - goto do_next_cb; - /* We no longer need the buffers. */ - free(cb); - free(dest); - /* Return number of bytes read. */ - return total + total2; + /* + * Compressed cb, decompress it into the temporary buffer, then + * copy the data to the destination range overlapping the cb. + */ + ntfs_log_debug("Found compressed compression block.\n"); + /* + * Read the compressed data into the temporary buffer. + * NOTE: We cheat a little bit here by marking the attribute as + * not compressed in the ntfs_attr structure so that we can + * read the raw, compressed data by simply using + * ntfs_attr_pread(). (-8 + * NOTE: We have to modify data_size and initialized_size + * temporarily as well... + */ + to_read = cb_size; + NAttrClearCompressed(na); + na->data_flags &= ~ATTR_COMPRESSION_MASK; + tdata_size = na->data_size; + tinitialized_size = na->initialized_size; + na->data_size = na->initialized_size = na->allocated_size; + do { + br = ntfs_attr_pread(na, + (vcn << vol->cluster_size_bits) + + (cb_pos - cb), to_read, cb_pos); + if (br < 0) { + err = errno; + na->data_size = tdata_size; + na->initialized_size = tinitialized_size; + na->ni->flags |= compression; + na->data_flags = data_flags; + free(cb); + free(dest); + if (total) + return total; + errno = err; + return br; + } + cb_pos += br; + to_read -= br; + } while (to_read > 0); + na->data_size = tdata_size; + na->initialized_size = tinitialized_size; + na->ni->flags |= compression; + na->data_flags = data_flags; + /* Just a precaution. */ + if (cb_pos + 2 <= cb_end) + *(u16*)cb_pos = 0; + ntfs_log_debug("Successfully read the compression block.\n"); + if (ntfs_decompress(dest, cb_size, cb, cb_size) < 0) { + err = errno; + free(cb); + free(dest); + if (total) + return total; + errno = err; + return -1; + } + to_read = min(count, cb_size - ofs); + memcpy(b, dest + ofs, to_read); + total += to_read; + count -= to_read; + b = (u8*)b + to_read; + ofs = 0; + } + /* Do we have more work to do? */ + if (nr_cbs) + goto do_next_cb; + /* We no longer need the buffers. */ + free(cb); + free(dest); + /* Return number of bytes read. */ + return total + total2; } /* @@ -833,38 +840,39 @@ do_next_cb: */ static u32 read_clusters(ntfs_volume *vol, const runlist_element *rl, - s64 offs, u32 to_read, char *inbuf) { - u32 count; - int xgot; - u32 got; - s64 xpos; - BOOL first; - char *xinbuf; - const runlist_element *xrl; + s64 offs, u32 to_read, char *inbuf) +{ + u32 count; + int xgot; + u32 got; + s64 xpos; + BOOL first; + char *xinbuf; + const runlist_element *xrl; - got = 0; - xrl = rl; - xinbuf = inbuf; - first = TRUE; - do { - count = xrl->length << vol->cluster_size_bits; - xpos = xrl->lcn << vol->cluster_size_bits; - if (first) { - count -= offs; - xpos += offs; - } - if ((to_read - got) < count) - count = to_read - got; - xgot = ntfs_pread(vol->dev, xpos, count, xinbuf); - if (xgot == (int)count) { - got += count; - xpos += count; - xinbuf += count; - xrl++; - } - first = FALSE; - } while ((xgot == (int)count) && (got < to_read)); - return (got); + got = 0; + xrl = rl; + xinbuf = inbuf; + first = TRUE; + do { + count = xrl->length << vol->cluster_size_bits; + xpos = xrl->lcn << vol->cluster_size_bits; + if (first) { + count -= offs; + xpos += offs; + } + if ((to_read - got) < count) + count = to_read - got; + xgot = ntfs_pread(vol->dev, xpos, count, xinbuf); + if (xgot == (int)count) { + got += count; + xpos += count; + xinbuf += count; + xrl++; + } + first = FALSE; + } while ((xgot == (int)count) && (got < to_read)); + return (got); } /* @@ -874,37 +882,38 @@ static u32 read_clusters(ntfs_volume *vol, const runlist_element *rl, */ static int write_clusters(ntfs_volume *vol, const runlist_element *rl, - s64 offs, int to_write, const char *outbuf) { - int count; - int put, xput; - s64 xpos; - BOOL first; - const char *xoutbuf; - const runlist_element *xrl; + s64 offs, int to_write, const char *outbuf) +{ + int count; + int put, xput; + s64 xpos; + BOOL first; + const char *xoutbuf; + const runlist_element *xrl; - put = 0; - xrl = rl; - xoutbuf = outbuf; - first = TRUE; - do { - count = xrl->length << vol->cluster_size_bits; - xpos = xrl->lcn << vol->cluster_size_bits; - if (first) { - count -= offs; - xpos += offs; - } - if ((to_write - put) < count) - count = to_write - put; - xput = ntfs_pwrite(vol->dev, xpos, count, xoutbuf); - if (xput == count) { - put += count; - xpos += count; - xoutbuf += count; - xrl++; - } - first = FALSE; - } while ((xput == count) && (put < to_write)); - return (put); + put = 0; + xrl = rl; + xoutbuf = outbuf; + first = TRUE; + do { + count = xrl->length << vol->cluster_size_bits; + xpos = xrl->lcn << vol->cluster_size_bits; + if (first) { + count -= offs; + xpos += offs; + } + if ((to_write - put) < count) + count = to_write - put; + xput = ntfs_pwrite(vol->dev, xpos, count, xoutbuf); + if (xput == count) { + put += count; + xpos += count; + xoutbuf += count; + xrl++; + } + first = FALSE; + } while ((xput == count) && (put < to_write)); + return (put); } @@ -918,91 +927,92 @@ static int write_clusters(ntfs_volume *vol, const runlist_element *rl, */ static int ntfs_comp_set(ntfs_attr *na, runlist_element *rl, - s64 offs, unsigned int insz, const char *inbuf) { - ntfs_volume *vol; - char *outbuf; - char *pbuf; - unsigned int compsz; - int written; - int rounded; - unsigned int clsz; - unsigned int p; - unsigned int sz; - unsigned int bsz; - BOOL fail; - BOOL allzeroes; - /* a single compressed zero */ - static char onezero[] = { 0x01, 0xb0, 0x00, 0x00 } ; - /* a couple of compressed zeroes */ - static char twozeroes[] = { 0x02, 0xb0, 0x00, 0x00, 0x00 } ; - /* more compressed zeroes, to be followed by some count */ - static char morezeroes[] = { 0x03, 0xb0, 0x02, 0x00 } ; + s64 offs, unsigned int insz, const char *inbuf) +{ + ntfs_volume *vol; + char *outbuf; + char *pbuf; + unsigned int compsz; + int written; + int rounded; + unsigned int clsz; + unsigned int p; + unsigned int sz; + unsigned int bsz; + BOOL fail; + BOOL allzeroes; + /* a single compressed zero */ + static char onezero[] = { 0x01, 0xb0, 0x00, 0x00 } ; + /* a couple of compressed zeroes */ + static char twozeroes[] = { 0x02, 0xb0, 0x00, 0x00, 0x00 } ; + /* more compressed zeroes, to be followed by some count */ + static char morezeroes[] = { 0x03, 0xb0, 0x02, 0x00 } ; - vol = na->ni->vol; - written = -1; /* default return */ - clsz = 1 << vol->cluster_size_bits; - /* may need 2 extra bytes per block and 2 more bytes */ - outbuf = (char*)ntfs_malloc(na->compression_block_size - + 2*(na->compression_block_size/NTFS_SB_SIZE) - + 2); - if (outbuf) { - fail = FALSE; - compsz = 0; - allzeroes = TRUE; - for (p=0; (p na->compression_block_size)) - fail = TRUE; - else { - if (allzeroes) { - /* check whether this is all zeroes */ - switch (sz) { - case 4 : - allzeroes = !memcmp( - pbuf,onezero,4); - break; - case 5 : - allzeroes = !memcmp( - pbuf,twozeroes,5); - break; - case 6 : - allzeroes = !memcmp( - pbuf,morezeroes,4); - break; - default : - allzeroes = FALSE; - break; - } - } - compsz += sz; - } - } - if (!fail && !allzeroes) { - /* add a couple of null bytes, space has been checked */ - outbuf[compsz++] = 0; - outbuf[compsz++] = 0; - /* write a full cluster, to avoid partial reading */ - rounded = ((compsz - 1) | (clsz - 1)) + 1; - written = write_clusters(vol, rl, offs, rounded, outbuf); - if (written != rounded) { + vol = na->ni->vol; + written = -1; /* default return */ + clsz = 1 << vol->cluster_size_bits; + /* may need 2 extra bytes per block and 2 more bytes */ + outbuf = (char*)ntfs_malloc(na->compression_block_size + + 2*(na->compression_block_size/NTFS_SB_SIZE) + + 2); + if (outbuf) { + fail = FALSE; + compsz = 0; + allzeroes = TRUE; + for (p=0; (p na->compression_block_size)) + fail = TRUE; + else { + if (allzeroes) { + /* check whether this is all zeroes */ + switch (sz) { + case 4 : + allzeroes = !memcmp( + pbuf,onezero,4); + break; + case 5 : + allzeroes = !memcmp( + pbuf,twozeroes,5); + break; + case 6 : + allzeroes = !memcmp( + pbuf,morezeroes,4); + break; + default : + allzeroes = FALSE; + break; + } + } + compsz += sz; + } + } + if (!fail && !allzeroes) { + /* add a couple of null bytes, space has been checked */ + outbuf[compsz++] = 0; + outbuf[compsz++] = 0; + /* write a full cluster, to avoid partial reading */ + rounded = ((compsz - 1) | (clsz - 1)) + 1; + written = write_clusters(vol, rl, offs, rounded, outbuf); + if (written != rounded) { // previously written text has been spoilt, should return a specific error - ntfs_log_error("error writing compressed data\n"); - errno = EIO; - written = -2; - } - } else - if (!fail) - written = 0; - free(outbuf); - } - return (written); + ntfs_log_error("error writing compressed data\n"); + errno = EIO; + written = -2; + } + } else + if (!fail) + written = 0; + free(outbuf); + } + return (written); } /* @@ -1017,100 +1027,101 @@ static int ntfs_comp_set(ntfs_attr *na, runlist_element *rl, */ static int ntfs_compress_free(ntfs_attr *na, runlist_element *rl, - s64 used, s64 reserved) { - int freecnt; - int usedcnt; - int res; - s64 freelcn; - s64 freevcn; - int freelength; - BOOL mergeholes; - BOOL beginhole; - ntfs_volume *vol; - runlist_element *freerl; + s64 used, s64 reserved) +{ + int freecnt; + int usedcnt; + int res; + s64 freelcn; + s64 freevcn; + int freelength; + BOOL mergeholes; + BOOL beginhole; + ntfs_volume *vol; + runlist_element *freerl; - res = -1; /* default return */ - vol = na->ni->vol; - freecnt = (reserved - used) >> vol->cluster_size_bits; - usedcnt = (reserved >> vol->cluster_size_bits) - freecnt; - /* skip entries fully used, if any */ - while (rl->length && (rl->length < usedcnt)) { - usedcnt -= rl->length; - rl++; - } - if (rl->length) { - /* - * Splitting the current allocation block requires - * an extra runlist element to create the hole. - * The required entry has been prereserved when - * mapping the runlist. - */ - freelcn = rl->lcn + usedcnt; - freevcn = rl->vcn + usedcnt; - freelength = rl->length - usedcnt; - /* new count of allocated clusters */ - rl->length = usedcnt; /* warning : can be zero */ - if (!((freevcn + freecnt) - & (na->compression_block_clusters - 1))) { - beginhole = !usedcnt && !rl->vcn; - mergeholes = !usedcnt - && rl[0].vcn - && (rl[-1].lcn == LCN_HOLE); - if (mergeholes) { - freerl = rl; - freerl->length = freecnt; - } else - freerl = ++rl; - if ((freelength > 0) - && !mergeholes - && (usedcnt || beginhole)) { - /* - * move the unused part to the end. Doing so, - * the vcn will be out of order. This does - * not harm, the vcn are meaningless now, and - * only the lcn are meaningful for freeing. - */ - /* locate current end */ - while (rl->length) - rl++; - /* new terminator relocated */ - rl[1].vcn = rl->vcn; - rl[1].lcn = LCN_ENOENT; - rl[1].length = 0; - /* hole, currently allocated */ - rl->vcn = freevcn; - rl->lcn = freelcn; - rl->length = freelength; - } - /* free the hole */ - res = ntfs_cluster_free_from_rl(vol,freerl); - if (!res) { - if (mergeholes) { - /* merge with adjacent hole */ - freerl--; - freerl->length += freecnt; - } else { - if (beginhole) - freerl--; - /* mark hole as free */ - freerl->lcn = LCN_HOLE; - freerl->vcn = freevcn; - freerl->length = freecnt; - } - /* and set up the new end */ - freerl[1].lcn = LCN_ENOENT; - freerl[1].vcn = freevcn + freecnt; - freerl[1].length = 0; - } - } else { - ntfs_log_error("Bad end of a compression block set\n"); - errno = EIO; - } - } else { - ntfs_log_error("No cluster to free after compression\n"); - errno = EIO; - } - return (res); + res = -1; /* default return */ + vol = na->ni->vol; + freecnt = (reserved - used) >> vol->cluster_size_bits; + usedcnt = (reserved >> vol->cluster_size_bits) - freecnt; + /* skip entries fully used, if any */ + while (rl->length && (rl->length < usedcnt)) { + usedcnt -= rl->length; + rl++; + } + if (rl->length) { + /* + * Splitting the current allocation block requires + * an extra runlist element to create the hole. + * The required entry has been prereserved when + * mapping the runlist. + */ + freelcn = rl->lcn + usedcnt; + freevcn = rl->vcn + usedcnt; + freelength = rl->length - usedcnt; + /* new count of allocated clusters */ + rl->length = usedcnt; /* warning : can be zero */ + if (!((freevcn + freecnt) + & (na->compression_block_clusters - 1))) { + beginhole = !usedcnt && !rl->vcn; + mergeholes = !usedcnt + && rl[0].vcn + && (rl[-1].lcn == LCN_HOLE); + if (mergeholes) { + freerl = rl; + freerl->length = freecnt; + } else + freerl = ++rl; + if ((freelength > 0) + && !mergeholes + && (usedcnt || beginhole)) { + /* + * move the unused part to the end. Doing so, + * the vcn will be out of order. This does + * not harm, the vcn are meaningless now, and + * only the lcn are meaningful for freeing. + */ + /* locate current end */ + while (rl->length) + rl++; + /* new terminator relocated */ + rl[1].vcn = rl->vcn; + rl[1].lcn = LCN_ENOENT; + rl[1].length = 0; + /* hole, currently allocated */ + rl->vcn = freevcn; + rl->lcn = freelcn; + rl->length = freelength; + } + /* free the hole */ + res = ntfs_cluster_free_from_rl(vol,freerl); + if (!res) { + if (mergeholes) { + /* merge with adjacent hole */ + freerl--; + freerl->length += freecnt; + } else { + if (beginhole) + freerl--; + /* mark hole as free */ + freerl->lcn = LCN_HOLE; + freerl->vcn = freevcn; + freerl->length = freecnt; + } + /* and set up the new end */ + freerl[1].lcn = LCN_ENOENT; + freerl[1].vcn = freevcn + freecnt; + freerl[1].length = 0; + } + } else { + ntfs_log_error("Bad end of a compression block set\n"); + errno = EIO; + } + } else { + ntfs_log_error("No cluster to free after compression\n"); + errno = EIO; + } + return (res); } /* @@ -1119,35 +1130,36 @@ static int ntfs_compress_free(ntfs_attr *na, runlist_element *rl, */ static int ntfs_read_append(ntfs_attr *na, const runlist_element *rl, - s64 offs, u32 compsz, int pos, - char *outbuf, s64 to_write, const void *b) { - int fail = 1; - char *compbuf; - u32 decompsz; - u32 got; + s64 offs, u32 compsz, int pos, + char *outbuf, s64 to_write, const void *b) +{ + int fail = 1; + char *compbuf; + u32 decompsz; + u32 got; - if (compsz == na->compression_block_size) { - /* if the full block was requested, it was a hole */ - memset(outbuf,0,compsz); - memcpy(&outbuf[pos],b,to_write); - fail = 0; - } else { - compbuf = (char*)ntfs_malloc(compsz); - if (compbuf) { - /* must align to full block for decompression */ - decompsz = ((pos - 1) | (NTFS_SB_SIZE - 1)) + 1; - got = read_clusters(na->ni->vol, rl, offs, - compsz, compbuf); - if ((got == compsz) - && !ntfs_decompress((u8*)outbuf,decompsz, - (u8*)compbuf,compsz)) { - memcpy(&outbuf[pos],b,to_write); - fail = 0; - } - free(compbuf); - } - } - return (fail); + if (compsz == na->compression_block_size) { + /* if the full block was requested, it was a hole */ + memset(outbuf,0,compsz); + memcpy(&outbuf[pos],b,to_write); + fail = 0; + } else { + compbuf = (char*)ntfs_malloc(compsz); + if (compbuf) { + /* must align to full block for decompression */ + decompsz = ((pos - 1) | (NTFS_SB_SIZE - 1)) + 1; + got = read_clusters(na->ni->vol, rl, offs, + compsz, compbuf); + if ((got == compsz) + && !ntfs_decompress((u8*)outbuf,decompsz, + (u8*)compbuf,compsz)) { + memcpy(&outbuf[pos],b,to_write); + fail = 0; + } + free(compbuf); + } + } + return (fail); } /* @@ -1159,29 +1171,30 @@ static int ntfs_read_append(ntfs_attr *na, const runlist_element *rl, */ static int ntfs_flush(ntfs_attr *na, runlist_element *rl, s64 offs, - const char *outbuf, int count, BOOL compress) { - int rounded; - int written; - int clsz; + const char *outbuf, int count, BOOL compress) +{ + int rounded; + int written; + int clsz; - if (compress) { - written = ntfs_comp_set(na, rl, offs, count, outbuf); - if (written == -1) - compress = FALSE; - if ((written >= 0) - && ntfs_compress_free(na,rl,offs + written, - offs + na->compression_block_size)) - written = -1; - } - if (!compress) { - clsz = 1 << na->ni->vol->cluster_size_bits; - rounded = ((count - 1) | (clsz - 1)) + 1; - written = write_clusters(na->ni->vol, rl, - offs, rounded, outbuf); - if (written != rounded) - written = -1; - } - return (written); + if (compress) { + written = ntfs_comp_set(na, rl, offs, count, outbuf); + if (written == -1) + compress = FALSE; + if ((written >= 0) + && ntfs_compress_free(na,rl,offs + written, + offs + na->compression_block_size)) + written = -1; + } + if (!compress) { + clsz = 1 << na->ni->vol->cluster_size_bits; + rounded = ((count - 1) | (clsz - 1)) + 1; + written = write_clusters(na->ni->vol, rl, + offs, rounded, outbuf); + if (written != rounded) + written = -1; + } + return (written); } /* @@ -1197,150 +1210,151 @@ static int ntfs_flush(ntfs_attr *na, runlist_element *rl, s64 offs, */ s64 ntfs_compressed_pwrite(ntfs_attr *na, runlist_element *wrl, s64 wpos, - s64 offs, s64 to_write, s64 rounded, - const void *b, int compressed_part) { - ntfs_volume *vol; - runlist_element *brl; /* entry containing the beginning of block */ - int compression_length; - s64 written; - s64 to_read; - s64 roffs; - s64 got; - s64 start_vcn; - s64 nextblock; - u32 compsz; - char *inbuf; - char *outbuf; - BOOL fail; - BOOL done; - BOOL compress; + s64 offs, s64 to_write, s64 rounded, + const void *b, int compressed_part) +{ + ntfs_volume *vol; + runlist_element *brl; /* entry containing the beginning of block */ + int compression_length; + s64 written; + s64 to_read; + s64 roffs; + s64 got; + s64 start_vcn; + s64 nextblock; + u32 compsz; + char *inbuf; + char *outbuf; + BOOL fail; + BOOL done; + BOOL compress; - written = 0; /* default return */ - vol = na->ni->vol; - compression_length = na->compression_block_clusters; - compress = FALSE; - done = FALSE; - /* - * Cannot accept writing beyond the current compression set - * because when compression occurs, clusters are freed - * and have to be reallocated. - * (cannot happen with standard fuse 4K buffers) - * Caller has to avoid this situation, or face consequences. - */ - nextblock = ((offs + (wrl->vcn << vol->cluster_size_bits)) - | (na->compression_block_size - 1)) + 1; - if ((offs + to_write + (wrl->vcn << vol->cluster_size_bits)) - >= nextblock) { - /* it is time to compress */ - compress = TRUE; - /* only process what we can */ - to_write = rounded = nextblock - - (offs + (wrl->vcn << vol->cluster_size_bits)); - } - start_vcn = 0; - fail = FALSE; - brl = wrl; - roffs = 0; - /* - * If we are about to compress or we need to decompress - * existing data, we have to process a full set of blocks. - * So relocate the parameters to the beginning of allocation - * containing the first byte of the set of blocks. - */ - if (compress || compressed_part) { - /* find the beginning of block */ - start_vcn = (wrl->vcn + (offs >> vol->cluster_size_bits)) - & -compression_length; - while (brl->vcn && (brl->vcn > start_vcn)) { - /* jumping back a hole means big trouble */ - if (brl->lcn == (LCN)LCN_HOLE) { - ntfs_log_error("jump back over a hole when appending\n"); - fail = TRUE; - errno = EIO; - } - brl--; - offs += brl->length << vol->cluster_size_bits; - } - roffs = (start_vcn - brl->vcn) << vol->cluster_size_bits; - } - if (compressed_part && !fail) { - /* - * The set of compression blocks contains compressed data - * (we are reopening an existing file to append to it) - * Decompress the data and append - */ - compsz = compressed_part << vol->cluster_size_bits; + written = 0; /* default return */ + vol = na->ni->vol; + compression_length = na->compression_block_clusters; + compress = FALSE; + done = FALSE; + /* + * Cannot accept writing beyond the current compression set + * because when compression occurs, clusters are freed + * and have to be reallocated. + * (cannot happen with standard fuse 4K buffers) + * Caller has to avoid this situation, or face consequences. + */ + nextblock = ((offs + (wrl->vcn << vol->cluster_size_bits)) + | (na->compression_block_size - 1)) + 1; + if ((offs + to_write + (wrl->vcn << vol->cluster_size_bits)) + >= nextblock) { + /* it is time to compress */ + compress = TRUE; + /* only process what we can */ + to_write = rounded = nextblock + - (offs + (wrl->vcn << vol->cluster_size_bits)); + } + start_vcn = 0; + fail = FALSE; + brl = wrl; + roffs = 0; + /* + * If we are about to compress or we need to decompress + * existing data, we have to process a full set of blocks. + * So relocate the parameters to the beginning of allocation + * containing the first byte of the set of blocks. + */ + if (compress || compressed_part) { + /* find the beginning of block */ + start_vcn = (wrl->vcn + (offs >> vol->cluster_size_bits)) + & -compression_length; + while (brl->vcn && (brl->vcn > start_vcn)) { + /* jumping back a hole means big trouble */ + if (brl->lcn == (LCN)LCN_HOLE) { + ntfs_log_error("jump back over a hole when appending\n"); + fail = TRUE; + errno = EIO; + } + brl--; + offs += brl->length << vol->cluster_size_bits; + } + roffs = (start_vcn - brl->vcn) << vol->cluster_size_bits; + } + if (compressed_part && !fail) { + /* + * The set of compression blocks contains compressed data + * (we are reopening an existing file to append to it) + * Decompress the data and append + */ + compsz = compressed_part << vol->cluster_size_bits; // improve the needed size - outbuf = (char*)ntfs_malloc(na->compression_block_size); - if (outbuf) { - to_read = offs - roffs; - if (!ntfs_read_append(na, brl, roffs, compsz, - to_read, outbuf, to_write, b)) { - written = ntfs_flush(na, brl, roffs, - outbuf, to_read + to_write, compress); - if (written >= 0) { - written = to_write; - done = TRUE; - } - } - free(outbuf); - } - } else { - if (compress && !fail) { - /* - * we are filling up a block, read the full set of blocks - * and compress it - */ - inbuf = (char*)ntfs_malloc(na->compression_block_size); - if (inbuf) { - to_read = offs - roffs; - if (to_read) - got = read_clusters(vol, brl, roffs, - to_read, inbuf); - else - got = 0; - if (got == to_read) { - memcpy(&inbuf[to_read],b,to_write); - written = ntfs_comp_set(na, brl, roffs, - to_read + to_write, inbuf); - /* - * if compression was not successful, - * only write the part which was requested - */ - if ((written >= 0) - /* free the unused clusters */ - && !ntfs_compress_free(na,brl, - written + roffs, - na->compression_block_size - + roffs)) { - done = TRUE; - written = to_write; - } - } - free(inbuf); - } - } - if (!done) { - /* - * if the compression block is not full, or - * if compression failed for whatever reason, - * write uncompressed - */ - /* check we are not overflowing current allocation */ - if ((wpos + rounded) - > ((wrl->lcn + wrl->length) - << vol->cluster_size_bits)) { - ntfs_log_error("writing on unallocated clusters\n"); - errno = EIO; - } else { - written = ntfs_pwrite(vol->dev, wpos, - rounded, b); - if (written == rounded) - written = to_write; - } - } - } - return (written); + outbuf = (char*)ntfs_malloc(na->compression_block_size); + if (outbuf) { + to_read = offs - roffs; + if (!ntfs_read_append(na, brl, roffs, compsz, + to_read, outbuf, to_write, b)) { + written = ntfs_flush(na, brl, roffs, + outbuf, to_read + to_write, compress); + if (written >= 0) { + written = to_write; + done = TRUE; + } + } + free(outbuf); + } + } else { + if (compress && !fail) { + /* + * we are filling up a block, read the full set of blocks + * and compress it + */ + inbuf = (char*)ntfs_malloc(na->compression_block_size); + if (inbuf) { + to_read = offs - roffs; + if (to_read) + got = read_clusters(vol, brl, roffs, + to_read, inbuf); + else + got = 0; + if (got == to_read) { + memcpy(&inbuf[to_read],b,to_write); + written = ntfs_comp_set(na, brl, roffs, + to_read + to_write, inbuf); + /* + * if compression was not successful, + * only write the part which was requested + */ + if ((written >= 0) + /* free the unused clusters */ + && !ntfs_compress_free(na,brl, + written + roffs, + na->compression_block_size + + roffs)) { + done = TRUE; + written = to_write; + } + } + free(inbuf); + } + } + if (!done) { + /* + * if the compression block is not full, or + * if compression failed for whatever reason, + * write uncompressed + */ + /* check we are not overflowing current allocation */ + if ((wpos + rounded) + > ((wrl->lcn + wrl->length) + << vol->cluster_size_bits)) { + ntfs_log_error("writing on unallocated clusters\n"); + errno = EIO; + } else { + written = ntfs_pwrite(vol->dev, wpos, + rounded, b); + if (written == rounded) + written = to_write; + } + } + } + return (written); } /* @@ -1351,65 +1365,66 @@ s64 ntfs_compressed_pwrite(ntfs_attr *na, runlist_element *wrl, s64 wpos, * Returns zero if closing is successful. */ -int ntfs_compressed_close(ntfs_attr *na, runlist_element *wrl, s64 offs) { - ntfs_volume *vol; - runlist_element *brl; /* entry containing the beginning of block */ - int compression_length; - s64 written; - s64 to_read; - s64 roffs; - s64 got; - s64 start_vcn; - char *inbuf; - BOOL fail; - BOOL done; +int ntfs_compressed_close(ntfs_attr *na, runlist_element *wrl, s64 offs) +{ + ntfs_volume *vol; + runlist_element *brl; /* entry containing the beginning of block */ + int compression_length; + s64 written; + s64 to_read; + s64 roffs; + s64 got; + s64 start_vcn; + char *inbuf; + BOOL fail; + BOOL done; - vol = na->ni->vol; - compression_length = na->compression_block_clusters; - done = FALSE; - /* - * There generally is an uncompressed block at end of file, - * read the full block and compress it - */ - inbuf = (char*)ntfs_malloc(na->compression_block_size); - if (inbuf) { - start_vcn = (wrl->vcn + (offs >> vol->cluster_size_bits)) - & -compression_length; - to_read = offs + ((wrl->vcn - start_vcn) << vol->cluster_size_bits); - brl = wrl; - fail = FALSE; - while (brl->vcn && (brl->vcn > start_vcn)) { - if (brl->lcn == (LCN)LCN_HOLE) { - ntfs_log_error("jump back over a hole when closing\n"); - fail = TRUE; - errno = EIO; - } - brl--; - } - if (!fail) { - /* roffs can be an offset from another uncomp block */ - roffs = (start_vcn - brl->vcn) << vol->cluster_size_bits; - if (to_read) { - got = read_clusters(vol, brl, roffs, to_read, - inbuf); - if (got == to_read) { - written = ntfs_comp_set(na, brl, roffs, - to_read, inbuf); - if ((written >= 0) - /* free the unused clusters */ - && !ntfs_compress_free(na,brl, - written + roffs, - na->compression_block_size + roffs)) { - done = TRUE; - } else - /* if compression failed, leave uncompressed */ - if (written == -1) - done = TRUE; - } - } else - done = TRUE; - free(inbuf); - } - } - return (!done); + vol = na->ni->vol; + compression_length = na->compression_block_clusters; + done = FALSE; + /* + * There generally is an uncompressed block at end of file, + * read the full block and compress it + */ + inbuf = (char*)ntfs_malloc(na->compression_block_size); + if (inbuf) { + start_vcn = (wrl->vcn + (offs >> vol->cluster_size_bits)) + & -compression_length; + to_read = offs + ((wrl->vcn - start_vcn) << vol->cluster_size_bits); + brl = wrl; + fail = FALSE; + while (brl->vcn && (brl->vcn > start_vcn)) { + if (brl->lcn == (LCN)LCN_HOLE) { + ntfs_log_error("jump back over a hole when closing\n"); + fail = TRUE; + errno = EIO; + } + brl--; + } + if (!fail) { + /* roffs can be an offset from another uncomp block */ + roffs = (start_vcn - brl->vcn) << vol->cluster_size_bits; + if (to_read) { + got = read_clusters(vol, brl, roffs, to_read, + inbuf); + if (got == to_read) { + written = ntfs_comp_set(na, brl, roffs, + to_read, inbuf); + if ((written >= 0) + /* free the unused clusters */ + && !ntfs_compress_free(na,brl, + written + roffs, + na->compression_block_size + roffs)) { + done = TRUE; + } else + /* if compression failed, leave uncompressed */ + if (written == -1) + done = TRUE; + } + } else + done = TRUE; + free(inbuf); + } + } + return (!done); } diff --git a/source/libntfs/compress.h b/source/libntfs/compress.h index 01cdba6f..809c3c93 100644 --- a/source/libntfs/compress.h +++ b/source/libntfs/compress.h @@ -1,5 +1,5 @@ /* - * compress.h - Exports for compressed attribute handling. + * compress.h - Exports for compressed attribute handling. * Originated from the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov @@ -27,11 +27,11 @@ #include "attrib.h" extern s64 ntfs_compressed_attr_pread(ntfs_attr *na, s64 pos, s64 count, - void *b); + void *b); extern s64 ntfs_compressed_pwrite(ntfs_attr *na, runlist_element *brl, s64 wpos, - s64 offs, s64 to_write, s64 rounded, - const void *b, int compressed_part); + s64 offs, s64 to_write, s64 rounded, + const void *b, int compressed_part); extern int ntfs_compressed_close(ntfs_attr *na, runlist_element *brl, s64 offs); diff --git a/source/libntfs/debug.c b/source/libntfs/debug.c index ab59a12c..f1934833 100644 --- a/source/libntfs/debug.c +++ b/source/libntfs/debug.c @@ -42,37 +42,37 @@ * * Returns: */ -void ntfs_debug_runlist_dump(const runlist_element *rl) { - int i = 0; - const char *lcn_str[5] = { "LCN_HOLE ", "LCN_RL_NOT_MAPPED", - "LCN_ENOENT ", "LCN_EINVAL ", - "LCN_unknown " - }; +void ntfs_debug_runlist_dump(const runlist_element *rl) +{ + int i = 0; + const char *lcn_str[5] = { "LCN_HOLE ", "LCN_RL_NOT_MAPPED", + "LCN_ENOENT ", "LCN_EINVAL ", + "LCN_unknown " }; - ntfs_log_debug("NTFS-fs DEBUG: Dumping runlist (values in hex):\n"); - if (!rl) { - ntfs_log_debug("Run list not present.\n"); - return; - } - ntfs_log_debug("VCN LCN Run length\n"); - do { - LCN lcn = (rl + i)->lcn; + ntfs_log_debug("NTFS-fs DEBUG: Dumping runlist (values in hex):\n"); + if (!rl) { + ntfs_log_debug("Run list not present.\n"); + return; + } + ntfs_log_debug("VCN LCN Run length\n"); + do { + LCN lcn = (rl + i)->lcn; - if (lcn < (LCN)0) { - int idx = -lcn - 1; + if (lcn < (LCN)0) { + int idx = -lcn - 1; - if (idx > -LCN_EINVAL - 1) - idx = 4; - ntfs_log_debug("%-16lld %s %-16lld%s\n", - (long long)rl[i].vcn, lcn_str[idx], - (long long)rl[i].length, - rl[i].length ? "" : " (runlist end)"); - } else - ntfs_log_debug("%-16lld %-16lld %-16lld%s\n", - (long long)rl[i].vcn, (long long)rl[i].lcn, - (long long)rl[i].length, - rl[i].length ? "" : " (runlist end)"); - } while (rl[i++].length); + if (idx > -LCN_EINVAL - 1) + idx = 4; + ntfs_log_debug("%-16lld %s %-16lld%s\n", + (long long)rl[i].vcn, lcn_str[idx], + (long long)rl[i].length, + rl[i].length ? "" : " (runlist end)"); + } else + ntfs_log_debug("%-16lld %-16lld %-16lld%s\n", + (long long)rl[i].vcn, (long long)rl[i].lcn, + (long long)rl[i].length, + rl[i].length ? "" : " (runlist end)"); + } while (rl[i++].length); } #endif diff --git a/source/libntfs/device.c b/source/libntfs/device.c index 61b76ca3..c77d8f95 100644 --- a/source/libntfs/device.c +++ b/source/libntfs/device.c @@ -104,27 +104,28 @@ * error return NULL with errno set to the error code returned by ntfs_malloc(). */ struct ntfs_device *ntfs_device_alloc(const char *name, const long state, - struct ntfs_device_operations *dops, void *priv_data) { - struct ntfs_device *dev; + struct ntfs_device_operations *dops, void *priv_data) +{ + struct ntfs_device *dev; - if (!name) { - errno = EINVAL; - return NULL; - } + if (!name) { + errno = EINVAL; + return NULL; + } - dev = ntfs_malloc(sizeof(struct ntfs_device)); - if (dev) { - if (!(dev->d_name = strdup(name))) { - int eo = errno; - free(dev); - errno = eo; - return NULL; - } - dev->d_ops = dops; - dev->d_state = state; - dev->d_private = priv_data; - } - return dev; + dev = ntfs_malloc(sizeof(struct ntfs_device)); + if (dev) { + if (!(dev->d_name = strdup(name))) { + int eo = errno; + free(dev); + errno = eo; + return NULL; + } + dev->d_ops = dops; + dev->d_state = state; + dev->d_private = priv_data; + } + return dev; } /** @@ -138,18 +139,19 @@ struct ntfs_device *ntfs_device_alloc(const char *name, const long state, * EINVAL Invalid pointer @dev. * EBUSY Device is still open. Close it before freeing it! */ -int ntfs_device_free(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } - if (NDevOpen(dev)) { - errno = EBUSY; - return -1; - } - free(dev->d_name); - free(dev); - return 0; +int ntfs_device_free(struct ntfs_device *dev) +{ + if (!dev) { + errno = EINVAL; + return -1; + } + if (NDevOpen(dev)) { + errno = EBUSY; + return -1; + } + free(dev->d_name); + free(dev); + return 0; } /** @@ -171,34 +173,35 @@ int ntfs_device_free(struct ntfs_device *dev) { * to the return code of either seek, read, or set to EINVAL in case of * invalid arguments. */ -s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, void *b) { - s64 br, total; - struct ntfs_device_operations *dops; +s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, void *b) +{ + s64 br, total; + struct ntfs_device_operations *dops; - ntfs_log_trace("pos %lld, count %lld\n",(long long)pos,(long long)count); + ntfs_log_trace("pos %lld, count %lld\n",(long long)pos,(long long)count); + + if (!b || count < 0 || pos < 0) { + errno = EINVAL; + return -1; + } + if (!count) + return 0; + + dops = dev->d_ops; - if (!b || count < 0 || pos < 0) { - errno = EINVAL; - return -1; - } - if (!count) - return 0; - - dops = dev->d_ops; - - for (total = 0; count; count -= br, total += br) { - br = dops->pread(dev, (char*)b + total, count, pos + total); - /* If everything ok, continue. */ - if (br > 0) - continue; - /* If EOF or error return number of bytes read. */ - if (!br || total) - return total; - /* Nothing read and error, return error status. */ - return br; - } - /* Finally, return the number of bytes read. */ - return total; + for (total = 0; count; count -= br, total += br) { + br = dops->pread(dev, (char*)b + total, count, pos + total); + /* If everything ok, continue. */ + if (br > 0) + continue; + /* If EOF or error return number of bytes read. */ + if (!br || total) + return total; + /* Nothing read and error, return error status. */ + return br; + } + /* Finally, return the number of bytes read. */ + return total; } /** @@ -221,44 +224,45 @@ s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, void *b) { * to EINVAL in case of invalid arguments. */ s64 ntfs_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const void *b) { - s64 written, total, ret = -1; - struct ntfs_device_operations *dops; + const void *b) +{ + s64 written, total, ret = -1; + struct ntfs_device_operations *dops; - ntfs_log_trace("pos %lld, count %lld\n",(long long)pos,(long long)count); + ntfs_log_trace("pos %lld, count %lld\n",(long long)pos,(long long)count); - if (!b || count < 0 || pos < 0) { - errno = EINVAL; - goto out; - } - if (!count) - return 0; - if (NDevReadOnly(dev)) { - errno = EROFS; - goto out; - } + if (!b || count < 0 || pos < 0) { + errno = EINVAL; + goto out; + } + if (!count) + return 0; + if (NDevReadOnly(dev)) { + errno = EROFS; + goto out; + } + + dops = dev->d_ops; - dops = dev->d_ops; - - NDevSetDirty(dev); - for (total = 0; count; count -= written, total += written) { - written = dops->pwrite(dev, (const char*)b + total, count, - pos + total); - /* If everything ok, continue. */ - if (written > 0) - continue; - /* - * If nothing written or error return number of bytes written. - */ - if (!written || total) - break; - /* Nothing written and error, return error status. */ - total = written; - break; - } - ret = total; -out: - return ret; + NDevSetDirty(dev); + for (total = 0; count; count -= written, total += written) { + written = dops->pwrite(dev, (const char*)b + total, count, + pos + total); + /* If everything ok, continue. */ + if (written > 0) + continue; + /* + * If nothing written or error return number of bytes written. + */ + if (!written || total) + break; + /* Nothing written and error, return error status. */ + total = written; + break; + } + ret = total; +out: + return ret; } /** @@ -291,29 +295,30 @@ out: * the magic being "BAAD". */ s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b) { - s64 br, i; + const u32 bksize, void *b) +{ + s64 br, i; - if (bksize & (bksize - 1) || bksize % NTFS_BLOCK_SIZE) { - errno = EINVAL; - return -1; - } - /* Do the read. */ - br = ntfs_pread(dev, pos, count * bksize, b); - if (br < 0) - return br; - /* - * Apply fixups to successfully read data, disregarding any errors - * returned from the MST fixup function. This is because we want to - * fixup everything possible and we rely on the fact that the "BAAD" - * magic will be detected later on. - */ - count = br / bksize; - for (i = 0; i < count; ++i) - ntfs_mst_post_read_fixup((NTFS_RECORD*) - ((u8*)b + i * bksize), bksize); - /* Finally, return the number of complete blocks read. */ - return count; + if (bksize & (bksize - 1) || bksize % NTFS_BLOCK_SIZE) { + errno = EINVAL; + return -1; + } + /* Do the read. */ + br = ntfs_pread(dev, pos, count * bksize, b); + if (br < 0) + return br; + /* + * Apply fixups to successfully read data, disregarding any errors + * returned from the MST fixup function. This is because we want to + * fixup everything possible and we rely on the fact that the "BAAD" + * magic will be detected later on. + */ + count = br / bksize; + for (i = 0; i < count; ++i) + ntfs_mst_post_read_fixup((NTFS_RECORD*) + ((u8*)b + i * bksize), bksize); + /* Finally, return the number of complete blocks read. */ + return count; } /** @@ -347,38 +352,39 @@ s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, * achieved. */ s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b) { - s64 written, i; + const u32 bksize, void *b) +{ + s64 written, i; - if (count < 0 || bksize % NTFS_BLOCK_SIZE) { - errno = EINVAL; - return -1; - } - if (!count) - return 0; - /* Prepare data for writing. */ - for (i = 0; i < count; ++i) { - int err; + if (count < 0 || bksize % NTFS_BLOCK_SIZE) { + errno = EINVAL; + return -1; + } + if (!count) + return 0; + /* Prepare data for writing. */ + for (i = 0; i < count; ++i) { + int err; - err = ntfs_mst_pre_write_fixup((NTFS_RECORD*) - ((u8*)b + i * bksize), bksize); - if (err < 0) { - /* Abort write at this position. */ - if (!i) - return err; - count = i; - break; - } - } - /* Write the prepared data. */ - written = ntfs_pwrite(dev, pos, count * bksize, b); - /* Quickly deprotect the data again. */ - for (i = 0; i < count; ++i) - ntfs_mst_post_write_fixup((NTFS_RECORD*)((u8*)b + i * bksize)); - if (written <= 0) - return written; - /* Finally, return the number of complete blocks written. */ - return written / bksize; + err = ntfs_mst_pre_write_fixup((NTFS_RECORD*) + ((u8*)b + i * bksize), bksize); + if (err < 0) { + /* Abort write at this position. */ + if (!i) + return err; + count = i; + break; + } + } + /* Write the prepared data. */ + written = ntfs_pwrite(dev, pos, count * bksize, b); + /* Quickly deprotect the data again. */ + for (i = 0; i < count; ++i) + ntfs_mst_post_write_fixup((NTFS_RECORD*)((u8*)b + i * bksize)); + if (written <= 0) + return written; + /* Finally, return the number of complete blocks written. */ + return written / bksize; } /** @@ -393,27 +399,28 @@ s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, * with errno set to the error code. */ s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, const s64 count, - void *b) { - s64 br; + void *b) +{ + s64 br; - if (!vol || lcn < 0 || count < 0) { - errno = EINVAL; - return -1; - } - if (vol->nr_clusters < lcn + count) { - errno = ESPIPE; - ntfs_log_perror("Trying to read outside of volume " - "(%lld < %lld)", (long long)vol->nr_clusters, - (long long)lcn + count); - return -1; - } - br = ntfs_pread(vol->dev, lcn << vol->cluster_size_bits, - count << vol->cluster_size_bits, b); - if (br < 0) { - ntfs_log_perror("Error reading cluster(s)"); - return br; - } - return br >> vol->cluster_size_bits; + if (!vol || lcn < 0 || count < 0) { + errno = EINVAL; + return -1; + } + if (vol->nr_clusters < lcn + count) { + errno = ESPIPE; + ntfs_log_perror("Trying to read outside of volume " + "(%lld < %lld)", (long long)vol->nr_clusters, + (long long)lcn + count); + return -1; + } + br = ntfs_pread(vol->dev, lcn << vol->cluster_size_bits, + count << vol->cluster_size_bits, b); + if (br < 0) { + ntfs_log_perror("Error reading cluster(s)"); + return br; + } + return br >> vol->cluster_size_bits; } /** @@ -428,30 +435,31 @@ s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, const s64 count, * error, with errno set to the error code. */ s64 ntfs_cluster_write(const ntfs_volume *vol, const s64 lcn, - const s64 count, const void *b) { - s64 bw; + const s64 count, const void *b) +{ + s64 bw; - if (!vol || lcn < 0 || count < 0) { - errno = EINVAL; - return -1; - } - if (vol->nr_clusters < lcn + count) { - errno = ESPIPE; - ntfs_log_perror("Trying to write outside of volume " - "(%lld < %lld)", (long long)vol->nr_clusters, - (long long)lcn + count); - return -1; - } - if (!NVolReadOnly(vol)) - bw = ntfs_pwrite(vol->dev, lcn << vol->cluster_size_bits, - count << vol->cluster_size_bits, b); - else - bw = count << vol->cluster_size_bits; - if (bw < 0) { - ntfs_log_perror("Error writing cluster(s)"); - return bw; - } - return bw >> vol->cluster_size_bits; + if (!vol || lcn < 0 || count < 0) { + errno = EINVAL; + return -1; + } + if (vol->nr_clusters < lcn + count) { + errno = ESPIPE; + ntfs_log_perror("Trying to write outside of volume " + "(%lld < %lld)", (long long)vol->nr_clusters, + (long long)lcn + count); + return -1; + } + if (!NVolReadOnly(vol)) + bw = ntfs_pwrite(vol->dev, lcn << vol->cluster_size_bits, + count << vol->cluster_size_bits, b); + else + bw = count << vol->cluster_size_bits; + if (bw < 0) { + ntfs_log_perror("Error writing cluster(s)"); + return bw; + } + return bw >> vol->cluster_size_bits; } /** @@ -464,13 +472,14 @@ s64 ntfs_cluster_write(const ntfs_volume *vol, const s64 lcn, * * Return 0 if it is valid and -1 if it is not valid. */ -static int ntfs_device_offset_valid(struct ntfs_device *dev, s64 ofs) { - char ch; +static int ntfs_device_offset_valid(struct ntfs_device *dev, s64 ofs) +{ + char ch; - if (dev->d_ops->seek(dev, ofs, SEEK_SET) >= 0 && - dev->d_ops->read(dev, &ch, 1) == 1) - return 0; - return -1; + if (dev->d_ops->seek(dev, ofs, SEEK_SET) >= 0 && + dev->d_ops->read(dev, &ch, 1) == 1) + return 0; + return -1; } /** @@ -485,62 +494,63 @@ static int ntfs_device_offset_valid(struct ntfs_device *dev, s64 ofs) { * * On error return -1 with errno set to the error code. */ -s64 ntfs_device_size_get(struct ntfs_device *dev, int block_size) { - s64 high, low; +s64 ntfs_device_size_get(struct ntfs_device *dev, int block_size) +{ + s64 high, low; - if (!dev || block_size <= 0 || (block_size - 1) & block_size) { - errno = EINVAL; - return -1; - } + if (!dev || block_size <= 0 || (block_size - 1) & block_size) { + errno = EINVAL; + return -1; + } #ifdef BLKGETSIZE64 - { u64 size; + { u64 size; - if (dev->d_ops->ioctl(dev, BLKGETSIZE64, &size) >= 0) { - ntfs_log_debug("BLKGETSIZE64 nr bytes = %llu (0x%llx)\n", - (unsigned long long)size, - (unsigned long long)size); - return (s64)size / block_size; - } - } + if (dev->d_ops->ioctl(dev, BLKGETSIZE64, &size) >= 0) { + ntfs_log_debug("BLKGETSIZE64 nr bytes = %llu (0x%llx)\n", + (unsigned long long)size, + (unsigned long long)size); + return (s64)size / block_size; + } + } #endif #ifdef BLKGETSIZE - { unsigned long size; + { unsigned long size; - if (dev->d_ops->ioctl(dev, BLKGETSIZE, &size) >= 0) { - ntfs_log_debug("BLKGETSIZE nr 512 byte blocks = %lu (0x%lx)\n", - size, size); - return (s64)size * 512 / block_size; - } - } + if (dev->d_ops->ioctl(dev, BLKGETSIZE, &size) >= 0) { + ntfs_log_debug("BLKGETSIZE nr 512 byte blocks = %lu (0x%lx)\n", + size, size); + return (s64)size * 512 / block_size; + } + } #endif #ifdef FDGETPRM - { struct floppy_struct this_floppy; + { struct floppy_struct this_floppy; - if (dev->d_ops->ioctl(dev, FDGETPRM, &this_floppy) >= 0) { - ntfs_log_debug("FDGETPRM nr 512 byte blocks = %lu (0x%lx)\n", - (unsigned long)this_floppy.size, - (unsigned long)this_floppy.size); - return (s64)this_floppy.size * 512 / block_size; - } - } + if (dev->d_ops->ioctl(dev, FDGETPRM, &this_floppy) >= 0) { + ntfs_log_debug("FDGETPRM nr 512 byte blocks = %lu (0x%lx)\n", + (unsigned long)this_floppy.size, + (unsigned long)this_floppy.size); + return (s64)this_floppy.size * 512 / block_size; + } + } #endif - /* - * We couldn't figure it out by using a specialized ioctl, - * so do binary search to find the size of the device. - */ - low = 0LL; - for (high = 1024LL; !ntfs_device_offset_valid(dev, high); high <<= 1) - low = high; - while (low < high - 1LL) { - const s64 mid = (low + high) / 2; + /* + * We couldn't figure it out by using a specialized ioctl, + * so do binary search to find the size of the device. + */ + low = 0LL; + for (high = 1024LL; !ntfs_device_offset_valid(dev, high); high <<= 1) + low = high; + while (low < high - 1LL) { + const s64 mid = (low + high) / 2; - if (!ntfs_device_offset_valid(dev, mid)) - low = mid; - else - high = mid; - } - dev->d_ops->seek(dev, 0LL, SEEK_SET); - return (low + 1LL) / block_size; + if (!ntfs_device_offset_valid(dev, mid)) + low = mid; + else + high = mid; + } + dev->d_ops->seek(dev, 0LL, SEEK_SET); + return (low + 1LL) / block_size; } /** @@ -555,24 +565,25 @@ s64 ntfs_device_size_get(struct ntfs_device *dev, int block_size) { * EOPNOTSUPP System does not support HDIO_GETGEO ioctl * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO */ -s64 ntfs_device_partition_start_sector_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } +s64 ntfs_device_partition_start_sector_get(struct ntfs_device *dev) +{ + if (!dev) { + errno = EINVAL; + return -1; + } #ifdef HDIO_GETGEO - { struct hd_geometry geo; + { struct hd_geometry geo; - if (!dev->d_ops->ioctl(dev, HDIO_GETGEO, &geo)) { - ntfs_log_debug("HDIO_GETGEO start_sect = %lu (0x%lx)\n", - geo.start, geo.start); - return geo.start; - } - } + if (!dev->d_ops->ioctl(dev, HDIO_GETGEO, &geo)) { + ntfs_log_debug("HDIO_GETGEO start_sect = %lu (0x%lx)\n", + geo.start, geo.start); + return geo.start; + } + } #else - errno = EOPNOTSUPP; + errno = EOPNOTSUPP; #endif - return -1; + return -1; } /** @@ -587,25 +598,26 @@ s64 ntfs_device_partition_start_sector_get(struct ntfs_device *dev) { * EOPNOTSUPP System does not support HDIO_GETGEO ioctl * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO */ -int ntfs_device_heads_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } +int ntfs_device_heads_get(struct ntfs_device *dev) +{ + if (!dev) { + errno = EINVAL; + return -1; + } #ifdef HDIO_GETGEO - { struct hd_geometry geo; + { struct hd_geometry geo; - if (!dev->d_ops->ioctl(dev, HDIO_GETGEO, &geo)) { - ntfs_log_debug("HDIO_GETGEO heads = %u (0x%x)\n", - (unsigned)geo.heads, - (unsigned)geo.heads); - return geo.heads; - } - } + if (!dev->d_ops->ioctl(dev, HDIO_GETGEO, &geo)) { + ntfs_log_debug("HDIO_GETGEO heads = %u (0x%x)\n", + (unsigned)geo.heads, + (unsigned)geo.heads); + return geo.heads; + } + } #else - errno = EOPNOTSUPP; + errno = EOPNOTSUPP; #endif - return -1; + return -1; } /** @@ -620,25 +632,26 @@ int ntfs_device_heads_get(struct ntfs_device *dev) { * EOPNOTSUPP System does not support HDIO_GETGEO ioctl * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO */ -int ntfs_device_sectors_per_track_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } +int ntfs_device_sectors_per_track_get(struct ntfs_device *dev) +{ + if (!dev) { + errno = EINVAL; + return -1; + } #ifdef HDIO_GETGEO - { struct hd_geometry geo; + { struct hd_geometry geo; - if (!dev->d_ops->ioctl(dev, HDIO_GETGEO, &geo)) { - ntfs_log_debug("HDIO_GETGEO sectors_per_track = %u (0x%x)\n", - (unsigned)geo.sectors, - (unsigned)geo.sectors); - return geo.sectors; - } - } + if (!dev->d_ops->ioctl(dev, HDIO_GETGEO, &geo)) { + ntfs_log_debug("HDIO_GETGEO sectors_per_track = %u (0x%x)\n", + (unsigned)geo.sectors, + (unsigned)geo.sectors); + return geo.sectors; + } + } #else - errno = EOPNOTSUPP; + errno = EOPNOTSUPP; #endif - return -1; + return -1; } /** @@ -653,25 +666,26 @@ int ntfs_device_sectors_per_track_get(struct ntfs_device *dev) { * EOPNOTSUPP System does not support BLKSSZGET ioctl * ENOTTY @dev is a file or a device not supporting BLKSSZGET */ -int ntfs_device_sector_size_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } +int ntfs_device_sector_size_get(struct ntfs_device *dev) +{ + if (!dev) { + errno = EINVAL; + return -1; + } #ifdef BLKSSZGET - { - int sect_size = 0; + { + int sect_size = 0; - if (!dev->d_ops->ioctl(dev, BLKSSZGET, §_size)) { - ntfs_log_debug("BLKSSZGET sector size = %d bytes\n", - sect_size); - return sect_size; - } - } + if (!dev->d_ops->ioctl(dev, BLKSSZGET, §_size)) { + ntfs_log_debug("BLKSSZGET sector size = %d bytes\n", + sect_size); + return sect_size; + } + } #else - errno = EOPNOTSUPP; + errno = EOPNOTSUPP; #endif - return -1; + return -1; } /** @@ -688,28 +702,29 @@ int ntfs_device_sector_size_get(struct ntfs_device *dev) { * ENOTTY @dev is a file or a device not supporting BLKBSZSET */ int ntfs_device_block_size_set(struct ntfs_device *dev, - int block_size __attribute__((unused))) { - if (!dev) { - errno = EINVAL; - return -1; - } + int block_size __attribute__((unused))) +{ + if (!dev) { + errno = EINVAL; + return -1; + } #ifdef BLKBSZSET - { - size_t s_block_size = block_size; - if (!dev->d_ops->ioctl(dev, BLKBSZSET, &s_block_size)) { - ntfs_log_debug("Used BLKBSZSET to set block size to " - "%d bytes.\n", block_size); - return 0; - } - /* If not a block device, pretend it was successful. */ - if (!NDevBlock(dev)) - return 0; - } + { + size_t s_block_size = block_size; + if (!dev->d_ops->ioctl(dev, BLKBSZSET, &s_block_size)) { + ntfs_log_debug("Used BLKBSZSET to set block size to " + "%d bytes.\n", block_size); + return 0; + } + /* If not a block device, pretend it was successful. */ + if (!NDevBlock(dev)) + return 0; + } #else - /* If not a block device, pretend it was successful. */ - if (!NDevBlock(dev)) - return 0; - errno = EOPNOTSUPP; + /* If not a block device, pretend it was successful. */ + if (!NDevBlock(dev)) + return 0; + errno = EOPNOTSUPP; #endif - return -1; + return -1; } diff --git a/source/libntfs/device.h b/source/libntfs/device.h index c3d45838..a19d29c4 100644 --- a/source/libntfs/device.h +++ b/source/libntfs/device.h @@ -37,10 +37,10 @@ * Defined bits for the state field in the ntfs_device structure. */ typedef enum { - ND_Open, /* 1: Device is open. */ - ND_ReadOnly, /* 1: Device is read-only. */ - ND_Dirty, /* 1: Device is dirty, needs sync. */ - ND_Block, /* 1: Device is a block device. */ + ND_Open, /* 1: Device is open. */ + ND_ReadOnly, /* 1: Device is read-only. */ + ND_Dirty, /* 1: Device is dirty, needs sync. */ + ND_Block, /* 1: Device is a block device. */ } ntfs_device_state_bits; #define test_ndev_flag(nd, flag) test_bit(ND_##flag, (nd)->d_state) @@ -70,10 +70,10 @@ typedef enum { * level device underlying the ntfs volume. */ struct ntfs_device { - struct ntfs_device_operations *d_ops; /* Device operations. */ - unsigned long d_state; /* State of the device. */ - char *d_name; /* Name of device. */ - void *d_private; /* Private data used by the + struct ntfs_device_operations *d_ops; /* Device operations. */ + unsigned long d_state; /* State of the device. */ + char *d_name; /* Name of device. */ + void *d_private; /* Private data used by the device operations. */ }; @@ -86,37 +86,37 @@ struct stat; * the low level device described by an ntfs device structure. */ struct ntfs_device_operations { - int (*open)(struct ntfs_device *dev, int flags); - int (*close)(struct ntfs_device *dev); - s64 (*seek)(struct ntfs_device *dev, s64 offset, int whence); - s64 (*read)(struct ntfs_device *dev, void *buf, s64 count); - s64 (*write)(struct ntfs_device *dev, const void *buf, s64 count); - s64 (*pread)(struct ntfs_device *dev, void *buf, s64 count, s64 offset); - s64 (*pwrite)(struct ntfs_device *dev, const void *buf, s64 count, - s64 offset); - int (*sync)(struct ntfs_device *dev); - int (*stat)(struct ntfs_device *dev, struct stat *buf); - int (*ioctl)(struct ntfs_device *dev, int request, void *argp); + int (*open)(struct ntfs_device *dev, int flags); + int (*close)(struct ntfs_device *dev); + s64 (*seek)(struct ntfs_device *dev, s64 offset, int whence); + s64 (*read)(struct ntfs_device *dev, void *buf, s64 count); + s64 (*write)(struct ntfs_device *dev, const void *buf, s64 count); + s64 (*pread)(struct ntfs_device *dev, void *buf, s64 count, s64 offset); + s64 (*pwrite)(struct ntfs_device *dev, const void *buf, s64 count, + s64 offset); + int (*sync)(struct ntfs_device *dev); + int (*stat)(struct ntfs_device *dev, struct stat *buf); + int (*ioctl)(struct ntfs_device *dev, int request, void *argp); }; extern struct ntfs_device *ntfs_device_alloc(const char *name, const long state, - struct ntfs_device_operations *dops, void *priv_data); + struct ntfs_device_operations *dops, void *priv_data); extern int ntfs_device_free(struct ntfs_device *dev); extern s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, - void *b); + void *b); extern s64 ntfs_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const void *b); + const void *b); extern s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b); + const u32 bksize, void *b); extern s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b); + const u32 bksize, void *b); extern s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, - const s64 count, void *b); + const s64 count, void *b); extern s64 ntfs_cluster_write(const ntfs_volume *vol, const s64 lcn, - const s64 count, const void *b); + const s64 count, const void *b); extern s64 ntfs_device_size_get(struct ntfs_device *dev, int block_size); extern s64 ntfs_device_partition_start_sector_get(struct ntfs_device *dev); diff --git a/source/libntfs/device_io.h b/source/libntfs/device_io.h index 4dcd3b93..b8701590 100644 --- a/source/libntfs/device_io.h +++ b/source/libntfs/device_io.h @@ -34,10 +34,10 @@ * struct hd_geometry - */ struct hd_geometry { - unsigned char heads; - unsigned char sectors; - unsigned short cylinders; - unsigned long start; + unsigned char heads; + unsigned char sectors; + unsigned short cylinders; + unsigned long start; }; #endif #ifndef BLKGETSIZE diff --git a/source/libntfs/dir.c b/source/libntfs/dir.c index 176c9583..297f10f1 100644 --- a/source/libntfs/dir.c +++ b/source/libntfs/dir.c @@ -68,26 +68,20 @@ * and "$Q" as global constants. */ ntfschar NTFS_INDEX_I30[5] = { const_cpu_to_le16('$'), const_cpu_to_le16('I'), - const_cpu_to_le16('3'), const_cpu_to_le16('0'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('3'), const_cpu_to_le16('0'), + const_cpu_to_le16('\0') }; ntfschar NTFS_INDEX_SII[5] = { const_cpu_to_le16('$'), const_cpu_to_le16('S'), - const_cpu_to_le16('I'), const_cpu_to_le16('I'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('I'), const_cpu_to_le16('I'), + const_cpu_to_le16('\0') }; ntfschar NTFS_INDEX_SDH[5] = { const_cpu_to_le16('$'), const_cpu_to_le16('S'), - const_cpu_to_le16('D'), const_cpu_to_le16('H'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('D'), const_cpu_to_le16('H'), + const_cpu_to_le16('\0') }; ntfschar NTFS_INDEX_O[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('O'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('\0') }; ntfschar NTFS_INDEX_Q[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('Q'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('\0') }; ntfschar NTFS_INDEX_R[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('R'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('\0') }; #if CACHE_INODE_SIZE @@ -96,9 +90,10 @@ ntfschar NTFS_INDEX_R[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('R'), */ static int inode_cache_compare(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *wanted) { - return (!cached->variable - || strcmp(cached->variable, wanted->variable)); + const struct CACHED_GENERIC *wanted) +{ + return (!cached->variable + || strcmp(cached->variable, wanted->variable)); } /* @@ -111,17 +106,18 @@ static int inode_cache_compare(const struct CACHED_GENERIC *cached, */ static int inode_cache_inv_compare(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *wanted) { - int len; + const struct CACHED_GENERIC *wanted) +{ + int len; - len = strlen(wanted->variable); - return (!cached->variable - || ((((const struct CACHED_INODE*)wanted)->inum - != MREF(((const struct CACHED_INODE*)cached)->inum)) - && (strncmp((const char*)cached->variable, - (const char*)wanted->variable,len) - || ((((const char*)cached->variable)[len] != '\0') - && (((const char*)cached->variable)[len] != '/'))))); + len = strlen(wanted->variable); + return (!cached->variable + || ((((const struct CACHED_INODE*)wanted)->inum + != MREF(((const struct CACHED_INODE*)cached)->inum)) + && (strncmp((const char*)cached->variable, + (const char*)wanted->variable,len) + || ((((const char*)cached->variable)[len] != '\0') + && (((const char*)cached->variable)[len] != '/'))))); } #endif @@ -152,318 +148,319 @@ static int inode_cache_inv_compare(const struct CACHED_GENERIC *cached, * allow exact matches. */ u64 ntfs_inode_lookup_by_name(ntfs_inode *dir_ni, const ntfschar *uname, - const int uname_len) { - VCN vcn; - u64 mref = 0; - s64 br; - ntfs_volume *vol = dir_ni->vol; - ntfs_attr_search_ctx *ctx; - INDEX_ROOT *ir; - INDEX_ENTRY *ie; - INDEX_ALLOCATION *ia; - u8 *index_end; - ntfs_attr *ia_na; - int eo, rc; - u32 index_block_size, index_vcn_size; - u8 index_vcn_size_bits; + const int uname_len) +{ + VCN vcn; + u64 mref = 0; + s64 br; + ntfs_volume *vol = dir_ni->vol; + ntfs_attr_search_ctx *ctx; + INDEX_ROOT *ir; + INDEX_ENTRY *ie; + INDEX_ALLOCATION *ia; + u8 *index_end; + ntfs_attr *ia_na; + int eo, rc; + u32 index_block_size, index_vcn_size; + u8 index_vcn_size_bits; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); - if (!dir_ni || !dir_ni->mrec || !uname || uname_len <= 0) { - errno = EINVAL; - return -1; - } + if (!dir_ni || !dir_ni->mrec || !uname || uname_len <= 0) { + errno = EINVAL; + return -1; + } - ctx = ntfs_attr_get_search_ctx(dir_ni, NULL); - if (!ctx) - return -1; + ctx = ntfs_attr_get_search_ctx(dir_ni, NULL); + if (!ctx) + return -1; - /* Find the index root attribute in the mft record. */ - if (ntfs_attr_lookup(AT_INDEX_ROOT, NTFS_INDEX_I30, 4, CASE_SENSITIVE, 0, NULL, - 0, ctx)) { - ntfs_log_perror("Index root attribute missing in directory inode " - "%lld", (unsigned long long)dir_ni->mft_no); - goto put_err_out; - } - /* Get to the index root value. */ - ir = (INDEX_ROOT*)((u8*)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - index_block_size = le32_to_cpu(ir->index_block_size); - if (index_block_size < NTFS_BLOCK_SIZE || - index_block_size & (index_block_size - 1)) { - ntfs_log_error("Index block size %u is invalid.\n", - (unsigned)index_block_size); - goto put_err_out; - } - index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length); - /* The first index entry. */ - ie = (INDEX_ENTRY*)((u8*)&ir->index + - le32_to_cpu(ir->index.entries_offset)); - /* - * Loop until we exceed valid memory (corruption case) or until we - * reach the last entry. - */ - for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { - /* Bounds checks. */ - if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie + - sizeof(INDEX_ENTRY_HEADER) > index_end || - (u8*)ie + le16_to_cpu(ie->key_length) > - index_end) { - ntfs_log_error("Index entry out of bounds in inode %lld" - "\n", (unsigned long long)dir_ni->mft_no); - goto put_err_out; - } - /* - * The last entry cannot contain a name. It can however contain - * a pointer to a child node in the B+tree so we just break out. - */ - if (ie->ie_flags & INDEX_ENTRY_END) - break; + /* Find the index root attribute in the mft record. */ + if (ntfs_attr_lookup(AT_INDEX_ROOT, NTFS_INDEX_I30, 4, CASE_SENSITIVE, 0, NULL, + 0, ctx)) { + ntfs_log_perror("Index root attribute missing in directory inode " + "%lld", (unsigned long long)dir_ni->mft_no); + goto put_err_out; + } + /* Get to the index root value. */ + ir = (INDEX_ROOT*)((u8*)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + index_block_size = le32_to_cpu(ir->index_block_size); + if (index_block_size < NTFS_BLOCK_SIZE || + index_block_size & (index_block_size - 1)) { + ntfs_log_error("Index block size %u is invalid.\n", + (unsigned)index_block_size); + goto put_err_out; + } + index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length); + /* The first index entry. */ + ie = (INDEX_ENTRY*)((u8*)&ir->index + + le32_to_cpu(ir->index.entries_offset)); + /* + * Loop until we exceed valid memory (corruption case) or until we + * reach the last entry. + */ + for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { + /* Bounds checks. */ + if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie + + sizeof(INDEX_ENTRY_HEADER) > index_end || + (u8*)ie + le16_to_cpu(ie->key_length) > + index_end) { + ntfs_log_error("Index entry out of bounds in inode %lld" + "\n", (unsigned long long)dir_ni->mft_no); + goto put_err_out; + } + /* + * The last entry cannot contain a name. It can however contain + * a pointer to a child node in the B+tree so we just break out. + */ + if (ie->ie_flags & INDEX_ENTRY_END) + break; + + if (!le16_to_cpu(ie->length)) { + ntfs_log_error("Zero length index entry in inode %lld" + "\n", (unsigned long long)dir_ni->mft_no); + goto put_err_out; + } + /* + * Not a perfect match, need to do full blown collation so we + * know which way in the B+tree we have to go. + */ + rc = ntfs_names_collate(uname, uname_len, + (ntfschar*)&ie->key.file_name.file_name, + ie->key.file_name.file_name_length, 1, + IGNORE_CASE, vol->upcase, vol->upcase_len); + /* + * If uname collates before the name of the current entry, there + * is definitely no such name in this index but we might need to + * descend into the B+tree so we just break out of the loop. + */ + if (rc == -1) + break; + /* The names are not equal, continue the search. */ + if (rc) + continue; + /* + * Names match with case insensitive comparison, now try the + * case sensitive comparison, which is required for proper + * collation. + */ + rc = ntfs_names_collate(uname, uname_len, + (ntfschar*)&ie->key.file_name.file_name, + ie->key.file_name.file_name_length, 1, + CASE_SENSITIVE, vol->upcase, vol->upcase_len); + if (rc == -1) + break; + if (rc) + continue; + /* + * Perfect match, this will never happen as the + * ntfs_are_names_equal() call will have gotten a match but we + * still treat it correctly. + */ + mref = le64_to_cpu(ie->indexed_file); + ntfs_attr_put_search_ctx(ctx); + return mref; + } + /* + * We have finished with this index without success. Check for the + * presence of a child node and if not present return error code + * ENOENT, unless we have got the mft reference of a matching name + * cached in mref in which case return mref. + */ + if (!(ie->ie_flags & INDEX_ENTRY_NODE)) { + ntfs_attr_put_search_ctx(ctx); + if (mref) + return mref; + ntfs_log_debug("Entry not found.\n"); + errno = ENOENT; + return -1; + } /* Child node present, descend into it. */ - if (!le16_to_cpu(ie->length)) { - ntfs_log_error("Zero length index entry in inode %lld" - "\n", (unsigned long long)dir_ni->mft_no); - goto put_err_out; - } - /* - * Not a perfect match, need to do full blown collation so we - * know which way in the B+tree we have to go. - */ - rc = ntfs_names_collate(uname, uname_len, - (ntfschar*)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, 1, - IGNORE_CASE, vol->upcase, vol->upcase_len); - /* - * If uname collates before the name of the current entry, there - * is definitely no such name in this index but we might need to - * descend into the B+tree so we just break out of the loop. - */ - if (rc == -1) - break; - /* The names are not equal, continue the search. */ - if (rc) - continue; - /* - * Names match with case insensitive comparison, now try the - * case sensitive comparison, which is required for proper - * collation. - */ - rc = ntfs_names_collate(uname, uname_len, - (ntfschar*)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, 1, - CASE_SENSITIVE, vol->upcase, vol->upcase_len); - if (rc == -1) - break; - if (rc) - continue; - /* - * Perfect match, this will never happen as the - * ntfs_are_names_equal() call will have gotten a match but we - * still treat it correctly. - */ - mref = le64_to_cpu(ie->indexed_file); - ntfs_attr_put_search_ctx(ctx); - return mref; - } - /* - * We have finished with this index without success. Check for the - * presence of a child node and if not present return error code - * ENOENT, unless we have got the mft reference of a matching name - * cached in mref in which case return mref. - */ - if (!(ie->ie_flags & INDEX_ENTRY_NODE)) { - ntfs_attr_put_search_ctx(ctx); - if (mref) - return mref; - ntfs_log_debug("Entry not found.\n"); - errno = ENOENT; - return -1; - } /* Child node present, descend into it. */ + /* Open the index allocation attribute. */ + ia_na = ntfs_attr_open(dir_ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4); + if (!ia_na) { + ntfs_log_perror("Failed to open index allocation (inode %lld)", + (unsigned long long)dir_ni->mft_no); + goto put_err_out; + } - /* Open the index allocation attribute. */ - ia_na = ntfs_attr_open(dir_ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4); - if (!ia_na) { - ntfs_log_perror("Failed to open index allocation (inode %lld)", - (unsigned long long)dir_ni->mft_no); - goto put_err_out; - } + /* Allocate a buffer for the current index block. */ + ia = ntfs_malloc(index_block_size); + if (!ia) { + ntfs_attr_close(ia_na); + goto put_err_out; + } - /* Allocate a buffer for the current index block. */ - ia = ntfs_malloc(index_block_size); - if (!ia) { - ntfs_attr_close(ia_na); - goto put_err_out; - } + /* Determine the size of a vcn in the directory index. */ + if (vol->cluster_size <= index_block_size) { + index_vcn_size = vol->cluster_size; + index_vcn_size_bits = vol->cluster_size_bits; + } else { + index_vcn_size = vol->sector_size; + index_vcn_size_bits = vol->sector_size_bits; + } - /* Determine the size of a vcn in the directory index. */ - if (vol->cluster_size <= index_block_size) { - index_vcn_size = vol->cluster_size; - index_vcn_size_bits = vol->cluster_size_bits; - } else { - index_vcn_size = vol->sector_size; - index_vcn_size_bits = vol->sector_size_bits; - } - - /* Get the starting vcn of the index_block holding the child node. */ - vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8); + /* Get the starting vcn of the index_block holding the child node. */ + vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8); descend_into_child_node: - /* Read the index block starting at vcn. */ - br = ntfs_attr_mst_pread(ia_na, vcn << index_vcn_size_bits, 1, - index_block_size, ia); - if (br != 1) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read vcn 0x%llx", - (unsigned long long)vcn); - goto close_err_out; - } + /* Read the index block starting at vcn. */ + br = ntfs_attr_mst_pread(ia_na, vcn << index_vcn_size_bits, 1, + index_block_size, ia); + if (br != 1) { + if (br != -1) + errno = EIO; + ntfs_log_perror("Failed to read vcn 0x%llx", + (unsigned long long)vcn); + goto close_err_out; + } - if (sle64_to_cpu(ia->index_block_vcn) != vcn) { - ntfs_log_error("Actual VCN (0x%llx) of index buffer is different " - "from expected VCN (0x%llx).\n", - (long long)sle64_to_cpu(ia->index_block_vcn), - (long long)vcn); - errno = EIO; - goto close_err_out; - } - if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) { - ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode 0x%llx " - "has a size (%u) differing from the directory " - "specified size (%u).\n", (long long)vcn, - (unsigned long long)dir_ni->mft_no, - (unsigned) le32_to_cpu(ia->index.allocated_size) + 0x18, - (unsigned)index_block_size); - errno = EIO; - goto close_err_out; - } - index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length); - if (index_end > (u8*)ia + index_block_size) { - ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode " - "0x%llx exceeds maximum size.\n", - (long long)vcn, (unsigned long long)dir_ni->mft_no); - errno = EIO; - goto close_err_out; - } + if (sle64_to_cpu(ia->index_block_vcn) != vcn) { + ntfs_log_error("Actual VCN (0x%llx) of index buffer is different " + "from expected VCN (0x%llx).\n", + (long long)sle64_to_cpu(ia->index_block_vcn), + (long long)vcn); + errno = EIO; + goto close_err_out; + } + if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) { + ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode 0x%llx " + "has a size (%u) differing from the directory " + "specified size (%u).\n", (long long)vcn, + (unsigned long long)dir_ni->mft_no, + (unsigned) le32_to_cpu(ia->index.allocated_size) + 0x18, + (unsigned)index_block_size); + errno = EIO; + goto close_err_out; + } + index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length); + if (index_end > (u8*)ia + index_block_size) { + ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode " + "0x%llx exceeds maximum size.\n", + (long long)vcn, (unsigned long long)dir_ni->mft_no); + errno = EIO; + goto close_err_out; + } - /* The first index entry. */ - ie = (INDEX_ENTRY*)((u8*)&ia->index + - le32_to_cpu(ia->index.entries_offset)); - /* - * Iterate similar to above big loop but applied to index buffer, thus - * loop until we exceed valid memory (corruption case) or until we - * reach the last entry. - */ - for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { - /* Bounds check. */ - if ((u8*)ie < (u8*)ia || (u8*)ie + - sizeof(INDEX_ENTRY_HEADER) > index_end || - (u8*)ie + le16_to_cpu(ie->key_length) > - index_end) { - ntfs_log_error("Index entry out of bounds in directory " - "inode %lld.\n", - (unsigned long long)dir_ni->mft_no); - errno = EIO; - goto close_err_out; - } - /* - * The last entry cannot contain a name. It can however contain - * a pointer to a child node in the B+tree so we just break out. - */ - if (ie->ie_flags & INDEX_ENTRY_END) - break; - - if (!le16_to_cpu(ie->length)) { - errno = EIO; - ntfs_log_error("Zero length index entry in inode %lld" - "\n", (unsigned long long)dir_ni->mft_no); - goto close_err_out; - } - /* - * Not a perfect match, need to do full blown collation so we - * know which way in the B+tree we have to go. - */ - rc = ntfs_names_collate(uname, uname_len, - (ntfschar*)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, 1, - IGNORE_CASE, vol->upcase, vol->upcase_len); - /* - * If uname collates before the name of the current entry, there - * is definitely no such name in this index but we might need to - * descend into the B+tree so we just break out of the loop. - */ - if (rc == -1) - break; - /* The names are not equal, continue the search. */ - if (rc) - continue; - /* - * Names match with case insensitive comparison, now try the - * case sensitive comparison, which is required for proper - * collation. - */ - rc = ntfs_names_collate(uname, uname_len, - (ntfschar*)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, 1, - CASE_SENSITIVE, vol->upcase, vol->upcase_len); - if (rc == -1) - break; - if (rc) - continue; - - mref = le64_to_cpu(ie->indexed_file); - free(ia); - ntfs_attr_close(ia_na); - ntfs_attr_put_search_ctx(ctx); - return mref; - } - /* - * We have finished with this index buffer without success. Check for - * the presence of a child node. - */ - if (ie->ie_flags & INDEX_ENTRY_NODE) { - if ((ia->index.ih_flags & NODE_MASK) == LEAF_NODE) { - ntfs_log_error("Index entry with child node found in a leaf " - "node in directory inode %lld.\n", - (unsigned long long)dir_ni->mft_no); - errno = EIO; - goto close_err_out; - } - /* Child node present, descend into it. */ - vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8); - if (vcn >= 0) - goto descend_into_child_node; - ntfs_log_error("Negative child node vcn in directory inode " - "0x%llx.\n", (unsigned long long)dir_ni->mft_no); - errno = EIO; - goto close_err_out; - } - free(ia); - ntfs_attr_close(ia_na); - ntfs_attr_put_search_ctx(ctx); - /* - * No child node present, return error code ENOENT, unless we have got - * the mft reference of a matching name cached in mref in which case - * return mref. - */ - if (mref) - return mref; - ntfs_log_debug("Entry not found.\n"); - errno = ENOENT; - return -1; + /* The first index entry. */ + ie = (INDEX_ENTRY*)((u8*)&ia->index + + le32_to_cpu(ia->index.entries_offset)); + /* + * Iterate similar to above big loop but applied to index buffer, thus + * loop until we exceed valid memory (corruption case) or until we + * reach the last entry. + */ + for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { + /* Bounds check. */ + if ((u8*)ie < (u8*)ia || (u8*)ie + + sizeof(INDEX_ENTRY_HEADER) > index_end || + (u8*)ie + le16_to_cpu(ie->key_length) > + index_end) { + ntfs_log_error("Index entry out of bounds in directory " + "inode %lld.\n", + (unsigned long long)dir_ni->mft_no); + errno = EIO; + goto close_err_out; + } + /* + * The last entry cannot contain a name. It can however contain + * a pointer to a child node in the B+tree so we just break out. + */ + if (ie->ie_flags & INDEX_ENTRY_END) + break; + + if (!le16_to_cpu(ie->length)) { + errno = EIO; + ntfs_log_error("Zero length index entry in inode %lld" + "\n", (unsigned long long)dir_ni->mft_no); + goto close_err_out; + } + /* + * Not a perfect match, need to do full blown collation so we + * know which way in the B+tree we have to go. + */ + rc = ntfs_names_collate(uname, uname_len, + (ntfschar*)&ie->key.file_name.file_name, + ie->key.file_name.file_name_length, 1, + IGNORE_CASE, vol->upcase, vol->upcase_len); + /* + * If uname collates before the name of the current entry, there + * is definitely no such name in this index but we might need to + * descend into the B+tree so we just break out of the loop. + */ + if (rc == -1) + break; + /* The names are not equal, continue the search. */ + if (rc) + continue; + /* + * Names match with case insensitive comparison, now try the + * case sensitive comparison, which is required for proper + * collation. + */ + rc = ntfs_names_collate(uname, uname_len, + (ntfschar*)&ie->key.file_name.file_name, + ie->key.file_name.file_name_length, 1, + CASE_SENSITIVE, vol->upcase, vol->upcase_len); + if (rc == -1) + break; + if (rc) + continue; + + mref = le64_to_cpu(ie->indexed_file); + free(ia); + ntfs_attr_close(ia_na); + ntfs_attr_put_search_ctx(ctx); + return mref; + } + /* + * We have finished with this index buffer without success. Check for + * the presence of a child node. + */ + if (ie->ie_flags & INDEX_ENTRY_NODE) { + if ((ia->index.ih_flags & NODE_MASK) == LEAF_NODE) { + ntfs_log_error("Index entry with child node found in a leaf " + "node in directory inode %lld.\n", + (unsigned long long)dir_ni->mft_no); + errno = EIO; + goto close_err_out; + } + /* Child node present, descend into it. */ + vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8); + if (vcn >= 0) + goto descend_into_child_node; + ntfs_log_error("Negative child node vcn in directory inode " + "0x%llx.\n", (unsigned long long)dir_ni->mft_no); + errno = EIO; + goto close_err_out; + } + free(ia); + ntfs_attr_close(ia_na); + ntfs_attr_put_search_ctx(ctx); + /* + * No child node present, return error code ENOENT, unless we have got + * the mft reference of a matching name cached in mref in which case + * return mref. + */ + if (mref) + return mref; + ntfs_log_debug("Entry not found.\n"); + errno = ENOENT; + return -1; put_err_out: - eo = EIO; - ntfs_log_debug("Corrupt directory. Aborting lookup.\n"); + eo = EIO; + ntfs_log_debug("Corrupt directory. Aborting lookup.\n"); eo_put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = eo; - return -1; + ntfs_attr_put_search_ctx(ctx); + errno = eo; + return -1; close_err_out: - eo = errno; - free(ia); - ntfs_attr_close(ia_na); - goto eo_put_err_out; + eo = errno; + free(ia); + ntfs_attr_close(ia_na); + goto eo_put_err_out; } /** @@ -480,189 +477,189 @@ close_err_out: * NULL Error, the pathname was invalid, or some other error occurred */ ntfs_inode *ntfs_pathname_to_inode(ntfs_volume *vol, ntfs_inode *parent, - const char *pathname) { - u64 inum; - int len, err = 0; - char *p, *q; - ntfs_inode *ni; - ntfs_inode *result = NULL; - ntfschar *unicode = NULL; - char *ascii = NULL; + const char *pathname) +{ + u64 inum; + int len, err = 0; + char *p, *q; + ntfs_inode *ni; + ntfs_inode *result = NULL; + ntfschar *unicode = NULL; + char *ascii = NULL; #if CACHE_INODE_SIZE - struct CACHED_INODE item; - struct CACHED_INODE *cached; - char *fullname; + struct CACHED_INODE item; + struct CACHED_INODE *cached; + char *fullname; #endif - if (!vol || !pathname) { - errno = EINVAL; - return NULL; - } + if (!vol || !pathname) { + errno = EINVAL; + return NULL; + } + + ntfs_log_trace("path: '%s'\n", pathname); + + ascii = strdup(pathname); + if (!ascii) { + ntfs_log_error("Out of memory.\n"); + err = ENOMEM; + goto out; + } - ntfs_log_trace("path: '%s'\n", pathname); - - ascii = strdup(pathname); - if (!ascii) { - ntfs_log_error("Out of memory.\n"); - err = ENOMEM; - goto out; - } - - p = ascii; - /* Remove leading /'s. */ - while (p && *p && *p == PATH_SEP) - p++; + p = ascii; + /* Remove leading /'s. */ + while (p && *p && *p == PATH_SEP) + p++; #if CACHE_INODE_SIZE - fullname = p; - if (p[0] && (p[strlen(p)-1] == PATH_SEP)) - ntfs_log_error("Unnormalized path %s\n",ascii); + fullname = p; + if (p[0] && (p[strlen(p)-1] == PATH_SEP)) + ntfs_log_error("Unnormalized path %s\n",ascii); #endif - if (parent) { - ni = parent; - } else { + if (parent) { + ni = parent; + } else { #if CACHE_INODE_SIZE - /* - * fetch inode for full path from cache - */ - if (*fullname) { - item.pathname = fullname; - item.varsize = strlen(fullname) + 1; - cached = (struct CACHED_INODE*)ntfs_fetch_cache( - vol->xinode_cache, GENERIC(&item), - inode_cache_compare); - } else - cached = (struct CACHED_INODE*)NULL; - if (cached) { - /* - * return opened inode if found in cache - */ - inum = MREF(cached->inum); - ni = ntfs_inode_open(vol, inum); - if (!ni) { - ntfs_log_debug("Cannot open inode %llu: %s.\n", - (unsigned long long)inum, p); - err = EIO; - } - result = ni; - goto out; - } + /* + * fetch inode for full path from cache + */ + if (*fullname) { + item.pathname = fullname; + item.varsize = strlen(fullname) + 1; + cached = (struct CACHED_INODE*)ntfs_fetch_cache( + vol->xinode_cache, GENERIC(&item), + inode_cache_compare); + } else + cached = (struct CACHED_INODE*)NULL; + if (cached) { + /* + * return opened inode if found in cache + */ + inum = MREF(cached->inum); + ni = ntfs_inode_open(vol, inum); + if (!ni) { + ntfs_log_debug("Cannot open inode %llu: %s.\n", + (unsigned long long)inum, p); + err = EIO; + } + result = ni; + goto out; + } #endif - ni = ntfs_inode_open(vol, FILE_root); - if (!ni) { - ntfs_log_debug("Couldn't open the inode of the root " - "directory.\n"); - err = EIO; - result = (ntfs_inode*)NULL; - goto out; - } - } + ni = ntfs_inode_open(vol, FILE_root); + if (!ni) { + ntfs_log_debug("Couldn't open the inode of the root " + "directory.\n"); + err = EIO; + result = (ntfs_inode*)NULL; + goto out; + } + } - while (p && *p) { - /* Find the end of the first token. */ - q = strchr(p, PATH_SEP); - if (q != NULL) { - *q = '\0'; - /* q++; JPA */ - } + while (p && *p) { + /* Find the end of the first token. */ + q = strchr(p, PATH_SEP); + if (q != NULL) { + *q = '\0'; + /* q++; JPA */ + } - len = ntfs_mbstoucs(p, &unicode); - if (len < 0) { - ntfs_log_perror("Could not convert filename to Unicode:" - " '%s'", p); - err = errno; - goto close; - } else if (len > NTFS_MAX_NAME_LEN) { - err = ENAMETOOLONG; - goto close; - } + len = ntfs_mbstoucs(p, &unicode); + if (len < 0) { + ntfs_log_perror("Could not convert filename to Unicode:" + " '%s'", p); + err = errno; + goto close; + } else if (len > NTFS_MAX_NAME_LEN) { + err = ENAMETOOLONG; + goto close; + } #if CACHE_INODE_SIZE - /* - * fetch inode for partial path from cache - * if not available, compute and store into cache - */ - if (parent) - inum = ntfs_inode_lookup_by_name(ni, unicode, len); - else { - item.pathname = fullname; - item.varsize = strlen(fullname) + 1; - cached = (struct CACHED_INODE*)ntfs_fetch_cache( - vol->xinode_cache, GENERIC(&item), - inode_cache_compare); - if (cached) { - inum = cached->inum; - } else { - inum = ntfs_inode_lookup_by_name(ni, unicode, len); - if (inum != (u64) -1) { - item.inum = inum; - ntfs_enter_cache(vol->xinode_cache, - GENERIC(&item), - inode_cache_compare); - } - } - } + /* + * fetch inode for partial path from cache + * if not available, compute and store into cache + */ + if (parent) + inum = ntfs_inode_lookup_by_name(ni, unicode, len); + else { + item.pathname = fullname; + item.varsize = strlen(fullname) + 1; + cached = (struct CACHED_INODE*)ntfs_fetch_cache( + vol->xinode_cache, GENERIC(&item), + inode_cache_compare); + if (cached) { + inum = cached->inum; + } else { + inum = ntfs_inode_lookup_by_name(ni, unicode, len); + if (inum != (u64) -1) { + item.inum = inum; + ntfs_enter_cache(vol->xinode_cache, + GENERIC(&item), + inode_cache_compare); + } + } + } #else - inum = ntfs_inode_lookup_by_name(ni, unicode, len); + inum = ntfs_inode_lookup_by_name(ni, unicode, len); #endif - if (inum == (u64) -1) { - ntfs_log_debug("Couldn't find name '%s' in pathname " - "'%s'.\n", p, pathname); - err = ENOENT; - goto close; - } + if (inum == (u64) -1) { + ntfs_log_debug("Couldn't find name '%s' in pathname " + "'%s'.\n", p, pathname); + err = ENOENT; + goto close; + } - if (ni != parent) - if (ntfs_inode_close(ni)) { - err = errno; - goto out; - } + if (ni != parent) + if (ntfs_inode_close(ni)) { + err = errno; + goto out; + } - inum = MREF(inum); - ni = ntfs_inode_open(vol, inum); - if (!ni) { - ntfs_log_debug("Cannot open inode %llu: %s.\n", - (unsigned long long)inum, p); - err = EIO; - goto close; - } + inum = MREF(inum); + ni = ntfs_inode_open(vol, inum); + if (!ni) { + ntfs_log_debug("Cannot open inode %llu: %s.\n", + (unsigned long long)inum, p); + err = EIO; + goto close; + } + + free(unicode); + unicode = NULL; - free(unicode); - unicode = NULL; + if (q) *q++ = PATH_SEP; /* JPA */ + p = q; + while (p && *p && *p == PATH_SEP) + p++; + } - if (q) *q++ = PATH_SEP; /* JPA */ - p = q; - while (p && *p && *p == PATH_SEP) - p++; - } - - result = ni; - ni = NULL; + result = ni; + ni = NULL; close: - if (ni && (ni != parent)) - if (ntfs_inode_close(ni) && !err) - err = errno; + if (ni && (ni != parent)) + if (ntfs_inode_close(ni) && !err) + err = errno; out: - free(ascii); - free(unicode); - if (err) - errno = err; - return result; + free(ascii); + free(unicode); + if (err) + errno = err; + return result; } /* * The little endian Unicode string ".." for ntfs_readdir(). */ static const ntfschar dotdot[3] = { const_cpu_to_le16('.'), - const_cpu_to_le16('.'), - const_cpu_to_le16('\0') - }; + const_cpu_to_le16('.'), + const_cpu_to_le16('\0') }; /* * union index_union - * More helpers for ntfs_readdir(). */ typedef union { - INDEX_ROOT *ir; - INDEX_ALLOCATION *ia; + INDEX_ROOT *ir; + INDEX_ALLOCATION *ia; } index_union __attribute__((__transparent_union__)); /** @@ -670,8 +667,8 @@ typedef union { * More helpers for ntfs_readdir(). */ typedef enum { - INDEX_TYPE_ROOT, /* index root */ - INDEX_TYPE_ALLOCATION, /* index allocation */ + INDEX_TYPE_ROOT, /* index root */ + INDEX_TYPE_ALLOCATION, /* index allocation */ } INDEX_TYPE; /** @@ -689,32 +686,33 @@ typedef enum { * callback. */ static int ntfs_filldir(ntfs_inode *dir_ni, s64 *pos, u8 ivcn_bits, - const INDEX_TYPE index_type, index_union iu, INDEX_ENTRY *ie, - void *dirent, ntfs_filldir_t filldir) { - FILE_NAME_ATTR *fn = &ie->key.file_name; - unsigned dt_type; + const INDEX_TYPE index_type, index_union iu, INDEX_ENTRY *ie, + void *dirent, ntfs_filldir_t filldir) +{ + FILE_NAME_ATTR *fn = &ie->key.file_name; + unsigned dt_type; - ntfs_log_trace("Entering.\n"); - - /* Advance the position even if going to skip the entry. */ - if (index_type == INDEX_TYPE_ALLOCATION) - *pos = (u8*)ie - (u8*)iu.ia + (sle64_to_cpu( - iu.ia->index_block_vcn) << ivcn_bits) + - dir_ni->vol->mft_record_size; - else /* if (index_type == INDEX_TYPE_ROOT) */ - *pos = (u8*)ie - (u8*)iu.ir; - /* Skip root directory self reference entry. */ - if (MREF_LE(ie->indexed_file) == FILE_root) - return 0; - if (ie->key.file_name.file_attributes & FILE_ATTR_I30_INDEX_PRESENT) - dt_type = NTFS_DT_DIR; - else if (fn->file_attributes & FILE_ATTR_SYSTEM) - dt_type = NTFS_DT_UNKNOWN; - else - dt_type = NTFS_DT_REG; - return filldir(dirent, fn->file_name, fn->file_name_length, - fn->file_name_type, *pos, - le64_to_cpu(ie->indexed_file), dt_type); + ntfs_log_trace("Entering.\n"); + + /* Advance the position even if going to skip the entry. */ + if (index_type == INDEX_TYPE_ALLOCATION) + *pos = (u8*)ie - (u8*)iu.ia + (sle64_to_cpu( + iu.ia->index_block_vcn) << ivcn_bits) + + dir_ni->vol->mft_record_size; + else /* if (index_type == INDEX_TYPE_ROOT) */ + *pos = (u8*)ie - (u8*)iu.ir; + /* Skip root directory self reference entry. */ + if (MREF_LE(ie->indexed_file) == FILE_root) + return 0; + if (ie->key.file_name.file_attributes & FILE_ATTR_I30_INDEX_PRESENT) + dt_type = NTFS_DT_DIR; + else if (fn->file_attributes & FILE_ATTR_SYSTEM) + dt_type = NTFS_DT_UNKNOWN; + else + dt_type = NTFS_DT_REG; + return filldir(dirent, fn->file_name, fn->file_name_length, + fn->file_name_type, *pos, + le64_to_cpu(ie->indexed_file), dt_type); } /** @@ -735,50 +733,51 @@ static int ntfs_filldir(ntfs_inode *dir_ni, s64 *pos, u8 ivcn_bits, * Return the mft reference of the parent directory on success or -1 on error * with errno set to the error code. */ -static MFT_REF ntfs_mft_get_parent_ref(ntfs_inode *ni) { - MFT_REF mref; - ntfs_attr_search_ctx *ctx; - FILE_NAME_ATTR *fn; - int eo; +static MFT_REF ntfs_mft_get_parent_ref(ntfs_inode *ni) +{ + MFT_REF mref; + ntfs_attr_search_ctx *ctx; + FILE_NAME_ATTR *fn; + int eo; - ntfs_log_trace("Entering.\n"); + ntfs_log_trace("Entering.\n"); + + if (!ni) { + errno = EINVAL; + return ERR_MREF(-1); + } - if (!ni) { - errno = EINVAL; - return ERR_MREF(-1); - } - - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return ERR_MREF(-1); - if (ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx)) { - ntfs_log_error("No file name found in inode %lld\n", - (unsigned long long)ni->mft_no); - goto err_out; - } - if (ctx->attr->non_resident) { - ntfs_log_error("File name attribute must be resident (inode " - "%lld)\n", (unsigned long long)ni->mft_no); - goto io_err_out; - } - fn = (FILE_NAME_ATTR*)((u8*)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - if ((u8*)fn + le32_to_cpu(ctx->attr->value_length) > - (u8*)ctx->attr + le32_to_cpu(ctx->attr->length)) { - ntfs_log_error("Corrupt file name attribute in inode %lld.\n", - (unsigned long long)ni->mft_no); - goto io_err_out; - } - mref = le64_to_cpu(fn->parent_directory); - ntfs_attr_put_search_ctx(ctx); - return mref; + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return ERR_MREF(-1); + if (ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx)) { + ntfs_log_error("No file name found in inode %lld\n", + (unsigned long long)ni->mft_no); + goto err_out; + } + if (ctx->attr->non_resident) { + ntfs_log_error("File name attribute must be resident (inode " + "%lld)\n", (unsigned long long)ni->mft_no); + goto io_err_out; + } + fn = (FILE_NAME_ATTR*)((u8*)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + if ((u8*)fn + le32_to_cpu(ctx->attr->value_length) > + (u8*)ctx->attr + le32_to_cpu(ctx->attr->length)) { + ntfs_log_error("Corrupt file name attribute in inode %lld.\n", + (unsigned long long)ni->mft_no); + goto io_err_out; + } + mref = le64_to_cpu(fn->parent_directory); + ntfs_attr_put_search_ctx(ctx); + return mref; io_err_out: - errno = EIO; + errno = EIO; err_out: - eo = errno; - ntfs_attr_put_search_ctx(ctx); - errno = eo; - return ERR_MREF(-1); + eo = errno; + ntfs_attr_put_search_ctx(ctx); + errno = eo; + return ERR_MREF(-1); } /** @@ -798,342 +797,343 @@ err_out: * that the directory entries are not returned sorted. */ int ntfs_readdir(ntfs_inode *dir_ni, s64 *pos, - void *dirent, ntfs_filldir_t filldir) { - s64 i_size, br, ia_pos, bmp_pos, ia_start; - ntfs_volume *vol; - ntfs_attr *ia_na, *bmp_na = NULL; - ntfs_attr_search_ctx *ctx = NULL; - u8 *index_end, *bmp = NULL; - INDEX_ROOT *ir; - INDEX_ENTRY *ie; - INDEX_ALLOCATION *ia = NULL; - int rc, ir_pos, bmp_buf_size, bmp_buf_pos, eo; - u32 index_block_size, index_vcn_size; - u8 index_block_size_bits, index_vcn_size_bits; + void *dirent, ntfs_filldir_t filldir) +{ + s64 i_size, br, ia_pos, bmp_pos, ia_start; + ntfs_volume *vol; + ntfs_attr *ia_na, *bmp_na = NULL; + ntfs_attr_search_ctx *ctx = NULL; + u8 *index_end, *bmp = NULL; + INDEX_ROOT *ir; + INDEX_ENTRY *ie; + INDEX_ALLOCATION *ia = NULL; + int rc, ir_pos, bmp_buf_size, bmp_buf_pos, eo; + u32 index_block_size, index_vcn_size; + u8 index_block_size_bits, index_vcn_size_bits; - ntfs_log_trace("Entering.\n"); + ntfs_log_trace("Entering.\n"); + + if (!dir_ni || !pos || !filldir) { + errno = EINVAL; + return -1; + } - if (!dir_ni || !pos || !filldir) { - errno = EINVAL; - return -1; - } + if (!(dir_ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { + errno = ENOTDIR; + return -1; + } - if (!(dir_ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { - errno = ENOTDIR; - return -1; - } + vol = dir_ni->vol; - vol = dir_ni->vol; + ntfs_log_trace("Entering for inode %lld, *pos 0x%llx.\n", + (unsigned long long)dir_ni->mft_no, (long long)*pos); - ntfs_log_trace("Entering for inode %lld, *pos 0x%llx.\n", - (unsigned long long)dir_ni->mft_no, (long long)*pos); + /* Open the index allocation attribute. */ + ia_na = ntfs_attr_open(dir_ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4); + if (!ia_na) { + if (errno != ENOENT) { + ntfs_log_perror("Failed to open index allocation attribute. " + "Directory inode %lld is corrupt or bug", + (unsigned long long)dir_ni->mft_no); + return -1; + } + i_size = 0; + } else + i_size = ia_na->data_size; - /* Open the index allocation attribute. */ - ia_na = ntfs_attr_open(dir_ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4); - if (!ia_na) { - if (errno != ENOENT) { - ntfs_log_perror("Failed to open index allocation attribute. " - "Directory inode %lld is corrupt or bug", - (unsigned long long)dir_ni->mft_no); - return -1; - } - i_size = 0; - } else - i_size = ia_na->data_size; + rc = 0; - rc = 0; + /* Are we at end of dir yet? */ + if (*pos >= i_size + vol->mft_record_size) + goto done; - /* Are we at end of dir yet? */ - if (*pos >= i_size + vol->mft_record_size) - goto done; + /* Emulate . and .. for all directories. */ + if (!*pos) { + rc = filldir(dirent, dotdot, 1, FILE_NAME_POSIX, *pos, + MK_MREF(dir_ni->mft_no, + le16_to_cpu(dir_ni->mrec->sequence_number)), + NTFS_DT_DIR); + if (rc) + goto err_out; + ++*pos; + } + if (*pos == 1) { + MFT_REF parent_mref; - /* Emulate . and .. for all directories. */ - if (!*pos) { - rc = filldir(dirent, dotdot, 1, FILE_NAME_POSIX, *pos, - MK_MREF(dir_ni->mft_no, - le16_to_cpu(dir_ni->mrec->sequence_number)), - NTFS_DT_DIR); - if (rc) - goto err_out; - ++*pos; - } - if (*pos == 1) { - MFT_REF parent_mref; + parent_mref = ntfs_mft_get_parent_ref(dir_ni); + if (parent_mref == ERR_MREF(-1)) { + ntfs_log_perror("Parent directory not found"); + goto dir_err_out; + } - parent_mref = ntfs_mft_get_parent_ref(dir_ni); - if (parent_mref == ERR_MREF(-1)) { - ntfs_log_perror("Parent directory not found"); - goto dir_err_out; - } + rc = filldir(dirent, dotdot, 2, FILE_NAME_POSIX, *pos, + parent_mref, NTFS_DT_DIR); + if (rc) + goto err_out; + ++*pos; + } - rc = filldir(dirent, dotdot, 2, FILE_NAME_POSIX, *pos, - parent_mref, NTFS_DT_DIR); - if (rc) - goto err_out; - ++*pos; - } + ctx = ntfs_attr_get_search_ctx(dir_ni, NULL); + if (!ctx) + goto err_out; - ctx = ntfs_attr_get_search_ctx(dir_ni, NULL); - if (!ctx) - goto err_out; + /* Get the offset into the index root attribute. */ + ir_pos = (int)*pos; + /* Find the index root attribute in the mft record. */ + if (ntfs_attr_lookup(AT_INDEX_ROOT, NTFS_INDEX_I30, 4, CASE_SENSITIVE, 0, NULL, + 0, ctx)) { + ntfs_log_perror("Index root attribute missing in directory inode " + "%lld", (unsigned long long)dir_ni->mft_no); + goto dir_err_out; + } + /* Get to the index root value. */ + ir = (INDEX_ROOT*)((u8*)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); - /* Get the offset into the index root attribute. */ - ir_pos = (int)*pos; - /* Find the index root attribute in the mft record. */ - if (ntfs_attr_lookup(AT_INDEX_ROOT, NTFS_INDEX_I30, 4, CASE_SENSITIVE, 0, NULL, - 0, ctx)) { - ntfs_log_perror("Index root attribute missing in directory inode " - "%lld", (unsigned long long)dir_ni->mft_no); - goto dir_err_out; - } - /* Get to the index root value. */ - ir = (INDEX_ROOT*)((u8*)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); + /* Determine the size of a vcn in the directory index. */ + index_block_size = le32_to_cpu(ir->index_block_size); + if (index_block_size < NTFS_BLOCK_SIZE || + index_block_size & (index_block_size - 1)) { + ntfs_log_error("Index block size %u is invalid.\n", + (unsigned)index_block_size); + goto dir_err_out; + } + index_block_size_bits = ffs(index_block_size) - 1; + if (vol->cluster_size <= index_block_size) { + index_vcn_size = vol->cluster_size; + index_vcn_size_bits = vol->cluster_size_bits; + } else { + index_vcn_size = vol->sector_size; + index_vcn_size_bits = vol->sector_size_bits; + } - /* Determine the size of a vcn in the directory index. */ - index_block_size = le32_to_cpu(ir->index_block_size); - if (index_block_size < NTFS_BLOCK_SIZE || - index_block_size & (index_block_size - 1)) { - ntfs_log_error("Index block size %u is invalid.\n", - (unsigned)index_block_size); - goto dir_err_out; - } - index_block_size_bits = ffs(index_block_size) - 1; - if (vol->cluster_size <= index_block_size) { - index_vcn_size = vol->cluster_size; - index_vcn_size_bits = vol->cluster_size_bits; - } else { - index_vcn_size = vol->sector_size; - index_vcn_size_bits = vol->sector_size_bits; - } + /* Are we jumping straight into the index allocation attribute? */ + if (*pos >= vol->mft_record_size) { + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; + goto skip_index_root; + } - /* Are we jumping straight into the index allocation attribute? */ - if (*pos >= vol->mft_record_size) { - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - goto skip_index_root; - } + index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length); + /* The first index entry. */ + ie = (INDEX_ENTRY*)((u8*)&ir->index + + le32_to_cpu(ir->index.entries_offset)); + /* + * Loop until we exceed valid memory (corruption case) or until we + * reach the last entry or until filldir tells us it has had enough + * or signals an error (both covered by the rc test). + */ + for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { + ntfs_log_debug("In index root, offset %d.\n", (int)((u8*)ie - (u8*)ir)); + /* Bounds checks. */ + if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie + + sizeof(INDEX_ENTRY_HEADER) > index_end || + (u8*)ie + le16_to_cpu(ie->key_length) > + index_end) + goto dir_err_out; + /* The last entry cannot contain a name. */ + if (ie->ie_flags & INDEX_ENTRY_END) + break; + + if (!le16_to_cpu(ie->length)) + goto dir_err_out; + + /* Skip index root entry if continuing previous readdir. */ + if (ir_pos > (u8*)ie - (u8*)ir) + continue; + /* + * Submit the directory entry to ntfs_filldir(), which will + * invoke the filldir() callback as appropriate. + */ + rc = ntfs_filldir(dir_ni, pos, index_vcn_size_bits, + INDEX_TYPE_ROOT, ir, ie, dirent, filldir); + if (rc) { + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; + goto err_out; + } + } + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; - index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length); - /* The first index entry. */ - ie = (INDEX_ENTRY*)((u8*)&ir->index + - le32_to_cpu(ir->index.entries_offset)); - /* - * Loop until we exceed valid memory (corruption case) or until we - * reach the last entry or until filldir tells us it has had enough - * or signals an error (both covered by the rc test). - */ - for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { - ntfs_log_debug("In index root, offset %d.\n", (int)((u8*)ie - (u8*)ir)); - /* Bounds checks. */ - if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie + - sizeof(INDEX_ENTRY_HEADER) > index_end || - (u8*)ie + le16_to_cpu(ie->key_length) > - index_end) - goto dir_err_out; - /* The last entry cannot contain a name. */ - if (ie->ie_flags & INDEX_ENTRY_END) - break; + /* If there is no index allocation attribute we are finished. */ + if (!ia_na) + goto EOD; - if (!le16_to_cpu(ie->length)) - goto dir_err_out; - - /* Skip index root entry if continuing previous readdir. */ - if (ir_pos > (u8*)ie - (u8*)ir) - continue; - /* - * Submit the directory entry to ntfs_filldir(), which will - * invoke the filldir() callback as appropriate. - */ - rc = ntfs_filldir(dir_ni, pos, index_vcn_size_bits, - INDEX_TYPE_ROOT, ir, ie, dirent, filldir); - if (rc) { - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - goto err_out; - } - } - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - - /* If there is no index allocation attribute we are finished. */ - if (!ia_na) - goto EOD; - - /* Advance *pos to the beginning of the index allocation. */ - *pos = vol->mft_record_size; + /* Advance *pos to the beginning of the index allocation. */ + *pos = vol->mft_record_size; skip_index_root: - if (!ia_na) - goto done; + if (!ia_na) + goto done; - /* Allocate a buffer for the current index block. */ - ia = ntfs_malloc(index_block_size); - if (!ia) - goto err_out; + /* Allocate a buffer for the current index block. */ + ia = ntfs_malloc(index_block_size); + if (!ia) + goto err_out; - bmp_na = ntfs_attr_open(dir_ni, AT_BITMAP, NTFS_INDEX_I30, 4); - if (!bmp_na) { - ntfs_log_perror("Failed to open index bitmap attribute"); - goto dir_err_out; - } + bmp_na = ntfs_attr_open(dir_ni, AT_BITMAP, NTFS_INDEX_I30, 4); + if (!bmp_na) { + ntfs_log_perror("Failed to open index bitmap attribute"); + goto dir_err_out; + } - /* Get the offset into the index allocation attribute. */ - ia_pos = *pos - vol->mft_record_size; + /* Get the offset into the index allocation attribute. */ + ia_pos = *pos - vol->mft_record_size; - bmp_pos = ia_pos >> index_block_size_bits; - if (bmp_pos >> 3 >= bmp_na->data_size) { - ntfs_log_error("Current index position exceeds index bitmap " - "size.\n"); - goto dir_err_out; - } + bmp_pos = ia_pos >> index_block_size_bits; + if (bmp_pos >> 3 >= bmp_na->data_size) { + ntfs_log_error("Current index position exceeds index bitmap " + "size.\n"); + goto dir_err_out; + } - bmp_buf_size = min(bmp_na->data_size - (bmp_pos >> 3), 4096); - bmp = ntfs_malloc(bmp_buf_size); - if (!bmp) - goto err_out; + bmp_buf_size = min(bmp_na->data_size - (bmp_pos >> 3), 4096); + bmp = ntfs_malloc(bmp_buf_size); + if (!bmp) + goto err_out; - br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp); - if (br != bmp_buf_size) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read from index bitmap attribute"); - goto err_out; - } + br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp); + if (br != bmp_buf_size) { + if (br != -1) + errno = EIO; + ntfs_log_perror("Failed to read from index bitmap attribute"); + goto err_out; + } - bmp_buf_pos = 0; - /* If the index block is not in use find the next one that is. */ - while (!(bmp[bmp_buf_pos >> 3] & (1 << (bmp_buf_pos & 7)))) { + bmp_buf_pos = 0; + /* If the index block is not in use find the next one that is. */ + while (!(bmp[bmp_buf_pos >> 3] & (1 << (bmp_buf_pos & 7)))) { find_next_index_buffer: - bmp_pos++; - bmp_buf_pos++; - /* If we have reached the end of the bitmap, we are done. */ - if (bmp_pos >> 3 >= bmp_na->data_size) - goto EOD; - ia_pos = bmp_pos << index_block_size_bits; - if (bmp_buf_pos >> 3 < bmp_buf_size) - continue; - /* Read next chunk from the index bitmap. */ - bmp_buf_pos = 0; - if ((bmp_pos >> 3) + bmp_buf_size > bmp_na->data_size) - bmp_buf_size = bmp_na->data_size - (bmp_pos >> 3); - br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp); - if (br != bmp_buf_size) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read from index bitmap attribute"); - goto err_out; - } - } + bmp_pos++; + bmp_buf_pos++; + /* If we have reached the end of the bitmap, we are done. */ + if (bmp_pos >> 3 >= bmp_na->data_size) + goto EOD; + ia_pos = bmp_pos << index_block_size_bits; + if (bmp_buf_pos >> 3 < bmp_buf_size) + continue; + /* Read next chunk from the index bitmap. */ + bmp_buf_pos = 0; + if ((bmp_pos >> 3) + bmp_buf_size > bmp_na->data_size) + bmp_buf_size = bmp_na->data_size - (bmp_pos >> 3); + br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp); + if (br != bmp_buf_size) { + if (br != -1) + errno = EIO; + ntfs_log_perror("Failed to read from index bitmap attribute"); + goto err_out; + } + } - ntfs_log_debug("Handling index block 0x%llx.\n", (long long)bmp_pos); + ntfs_log_debug("Handling index block 0x%llx.\n", (long long)bmp_pos); - /* Read the index block starting at bmp_pos. */ - br = ntfs_attr_mst_pread(ia_na, bmp_pos << index_block_size_bits, 1, - index_block_size, ia); - if (br != 1) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read index block"); - goto err_out; - } + /* Read the index block starting at bmp_pos. */ + br = ntfs_attr_mst_pread(ia_na, bmp_pos << index_block_size_bits, 1, + index_block_size, ia); + if (br != 1) { + if (br != -1) + errno = EIO; + ntfs_log_perror("Failed to read index block"); + goto err_out; + } - ia_start = ia_pos & ~(s64)(index_block_size - 1); - if (sle64_to_cpu(ia->index_block_vcn) != ia_start >> - index_vcn_size_bits) { - ntfs_log_error("Actual VCN (0x%llx) of index buffer is different " - "from expected VCN (0x%llx) in inode 0x%llx.\n", - (long long)sle64_to_cpu(ia->index_block_vcn), - (long long)ia_start >> index_vcn_size_bits, - (unsigned long long)dir_ni->mft_no); - goto dir_err_out; - } - if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) { - ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode %lld " - "has a size (%u) differing from the directory " - "specified size (%u).\n", (long long)ia_start >> - index_vcn_size_bits, - (unsigned long long)dir_ni->mft_no, - (unsigned) le32_to_cpu(ia->index.allocated_size) - + 0x18, (unsigned)index_block_size); - goto dir_err_out; - } - index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length); - if (index_end > (u8*)ia + index_block_size) { - ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode " - "%lld exceeds maximum size.\n", - (long long)ia_start >> index_vcn_size_bits, - (unsigned long long)dir_ni->mft_no); - goto dir_err_out; - } - /* The first index entry. */ - ie = (INDEX_ENTRY*)((u8*)&ia->index + - le32_to_cpu(ia->index.entries_offset)); - /* - * Loop until we exceed valid memory (corruption case) or until we - * reach the last entry or until ntfs_filldir tells us it has had - * enough or signals an error (both covered by the rc test). - */ - for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { - ntfs_log_debug("In index allocation, offset 0x%llx.\n", - (long long)ia_start + ((u8*)ie - (u8*)ia)); - /* Bounds checks. */ - if ((u8*)ie < (u8*)ia || (u8*)ie + - sizeof(INDEX_ENTRY_HEADER) > index_end || - (u8*)ie + le16_to_cpu(ie->key_length) > - index_end) { - ntfs_log_error("Index entry out of bounds in directory inode " - "%lld.\n", (unsigned long long)dir_ni->mft_no); - goto dir_err_out; - } - /* The last entry cannot contain a name. */ - if (ie->ie_flags & INDEX_ENTRY_END) - break; - - if (!le16_to_cpu(ie->length)) - goto dir_err_out; - - /* Skip index entry if continuing previous readdir. */ - if (ia_pos - ia_start > (u8*)ie - (u8*)ia) - continue; - /* - * Submit the directory entry to ntfs_filldir(), which will - * invoke the filldir() callback as appropriate. - */ - rc = ntfs_filldir(dir_ni, pos, index_vcn_size_bits, - INDEX_TYPE_ALLOCATION, ia, ie, dirent, filldir); - if (rc) - goto err_out; - } - goto find_next_index_buffer; + ia_start = ia_pos & ~(s64)(index_block_size - 1); + if (sle64_to_cpu(ia->index_block_vcn) != ia_start >> + index_vcn_size_bits) { + ntfs_log_error("Actual VCN (0x%llx) of index buffer is different " + "from expected VCN (0x%llx) in inode 0x%llx.\n", + (long long)sle64_to_cpu(ia->index_block_vcn), + (long long)ia_start >> index_vcn_size_bits, + (unsigned long long)dir_ni->mft_no); + goto dir_err_out; + } + if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) { + ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode %lld " + "has a size (%u) differing from the directory " + "specified size (%u).\n", (long long)ia_start >> + index_vcn_size_bits, + (unsigned long long)dir_ni->mft_no, + (unsigned) le32_to_cpu(ia->index.allocated_size) + + 0x18, (unsigned)index_block_size); + goto dir_err_out; + } + index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length); + if (index_end > (u8*)ia + index_block_size) { + ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode " + "%lld exceeds maximum size.\n", + (long long)ia_start >> index_vcn_size_bits, + (unsigned long long)dir_ni->mft_no); + goto dir_err_out; + } + /* The first index entry. */ + ie = (INDEX_ENTRY*)((u8*)&ia->index + + le32_to_cpu(ia->index.entries_offset)); + /* + * Loop until we exceed valid memory (corruption case) or until we + * reach the last entry or until ntfs_filldir tells us it has had + * enough or signals an error (both covered by the rc test). + */ + for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { + ntfs_log_debug("In index allocation, offset 0x%llx.\n", + (long long)ia_start + ((u8*)ie - (u8*)ia)); + /* Bounds checks. */ + if ((u8*)ie < (u8*)ia || (u8*)ie + + sizeof(INDEX_ENTRY_HEADER) > index_end || + (u8*)ie + le16_to_cpu(ie->key_length) > + index_end) { + ntfs_log_error("Index entry out of bounds in directory inode " + "%lld.\n", (unsigned long long)dir_ni->mft_no); + goto dir_err_out; + } + /* The last entry cannot contain a name. */ + if (ie->ie_flags & INDEX_ENTRY_END) + break; + + if (!le16_to_cpu(ie->length)) + goto dir_err_out; + + /* Skip index entry if continuing previous readdir. */ + if (ia_pos - ia_start > (u8*)ie - (u8*)ia) + continue; + /* + * Submit the directory entry to ntfs_filldir(), which will + * invoke the filldir() callback as appropriate. + */ + rc = ntfs_filldir(dir_ni, pos, index_vcn_size_bits, + INDEX_TYPE_ALLOCATION, ia, ie, dirent, filldir); + if (rc) + goto err_out; + } + goto find_next_index_buffer; EOD: - /* We are finished, set *pos to EOD. */ - *pos = i_size + vol->mft_record_size; + /* We are finished, set *pos to EOD. */ + *pos = i_size + vol->mft_record_size; done: - free(ia); - free(bmp); - if (bmp_na) - ntfs_attr_close(bmp_na); - if (ia_na) - ntfs_attr_close(ia_na); - ntfs_log_debug("EOD, *pos 0x%llx, returning 0.\n", (long long)*pos); - return 0; + free(ia); + free(bmp); + if (bmp_na) + ntfs_attr_close(bmp_na); + if (ia_na) + ntfs_attr_close(ia_na); + ntfs_log_debug("EOD, *pos 0x%llx, returning 0.\n", (long long)*pos); + return 0; dir_err_out: - errno = EIO; + errno = EIO; err_out: - eo = errno; - ntfs_log_trace("failed.\n"); - if (ctx) - ntfs_attr_put_search_ctx(ctx); - free(ia); - free(bmp); - if (bmp_na) - ntfs_attr_close(bmp_na); - if (ia_na) - ntfs_attr_close(ia_na); - errno = eo; - return -1; + eo = errno; + ntfs_log_trace("failed.\n"); + if (ctx) + ntfs_attr_put_search_ctx(ctx); + free(ia); + free(bmp); + if (bmp_na) + ntfs_attr_close(bmp_na); + if (ia_na) + ntfs_attr_close(ia_na); + errno = eo; + return -1; } @@ -1170,246 +1170,247 @@ err_out: * on error with errno set to the error code. */ static ntfs_inode *__ntfs_create(ntfs_inode *dir_ni, le32 securid, - ntfschar *name, u8 name_len, mode_t type, dev_t dev, - ntfschar *target, int target_len) { - ntfs_inode *ni; - int rollback_data = 0, rollback_sd = 0; - FILE_NAME_ATTR *fn = NULL; - STANDARD_INFORMATION *si = NULL; - int err, fn_len, si_len; + ntfschar *name, u8 name_len, mode_t type, dev_t dev, + ntfschar *target, int target_len) +{ + ntfs_inode *ni; + int rollback_data = 0, rollback_sd = 0; + FILE_NAME_ATTR *fn = NULL; + STANDARD_INFORMATION *si = NULL; + int err, fn_len, si_len; - ntfs_log_trace("Entering.\n"); + ntfs_log_trace("Entering.\n"); + + /* Sanity checks. */ + if (!dir_ni || !name || !name_len) { + ntfs_log_error("Invalid arguments.\n"); + errno = EINVAL; + return NULL; + } + + if (dir_ni->flags & FILE_ATTR_REPARSE_POINT) { + errno = EOPNOTSUPP; + return NULL; + } + + ni = ntfs_mft_record_alloc(dir_ni->vol, NULL); + if (!ni) + return NULL; + /* + * Create STANDARD_INFORMATION attribute. + * JPA Depending on available inherited security descriptor, + * Write STANDARD_INFORMATION v1.2 (no inheritance) or v3 + */ + if (securid) + si_len = sizeof(STANDARD_INFORMATION); + else + si_len = offsetof(STANDARD_INFORMATION, v1_end); + si = ntfs_calloc(si_len); + if (!si) { + err = errno; + goto err_out; + } + si->creation_time = utc2ntfs(ni->creation_time); + si->last_data_change_time = utc2ntfs(ni->last_data_change_time); + si->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); + si->last_access_time = utc2ntfs(ni->last_access_time); + if (securid) { + set_nino_flag(ni, v3_Extensions); + ni->owner_id = si->owner_id = 0; + ni->security_id = si->security_id = securid; + ni->quota_charged = si->quota_charged = const_cpu_to_le64(0); + ni->usn = si->usn = const_cpu_to_le64(0); + } else + clear_nino_flag(ni, v3_Extensions); + if (!S_ISREG(type) && !S_ISDIR(type)) { + si->file_attributes = FILE_ATTR_SYSTEM; + ni->flags = FILE_ATTR_SYSTEM; + } + if ((dir_ni->flags & FILE_ATTR_COMPRESSED) + && (S_ISREG(type) || S_ISDIR(type))) + ni->flags |= FILE_ATTR_COMPRESSED; + /* Add STANDARD_INFORMATION to inode. */ + if (ntfs_attr_add(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0, + (u8*)si, si_len)) { + err = errno; + ntfs_log_error("Failed to add STANDARD_INFORMATION " + "attribute.\n"); + goto err_out; + } - /* Sanity checks. */ - if (!dir_ni || !name || !name_len) { - ntfs_log_error("Invalid arguments.\n"); - errno = EINVAL; - return NULL; - } + if (!securid) { + if (ntfs_sd_add_everyone(ni)) { + err = errno; + goto err_out; + } + } + rollback_sd = 1; - if (dir_ni->flags & FILE_ATTR_REPARSE_POINT) { - errno = EOPNOTSUPP; - return NULL; - } + if (S_ISDIR(type)) { + INDEX_ROOT *ir = NULL; + INDEX_ENTRY *ie; + int ir_len, index_len; - ni = ntfs_mft_record_alloc(dir_ni->vol, NULL); - if (!ni) - return NULL; - /* - * Create STANDARD_INFORMATION attribute. - * JPA Depending on available inherited security descriptor, - * Write STANDARD_INFORMATION v1.2 (no inheritance) or v3 - */ - if (securid) - si_len = sizeof(STANDARD_INFORMATION); - else - si_len = offsetof(STANDARD_INFORMATION, v1_end); - si = ntfs_calloc(si_len); - if (!si) { - err = errno; - goto err_out; - } - si->creation_time = utc2ntfs(ni->creation_time); - si->last_data_change_time = utc2ntfs(ni->last_data_change_time); - si->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); - si->last_access_time = utc2ntfs(ni->last_access_time); - if (securid) { - set_nino_flag(ni, v3_Extensions); - ni->owner_id = si->owner_id = 0; - ni->security_id = si->security_id = securid; - ni->quota_charged = si->quota_charged = const_cpu_to_le64(0); - ni->usn = si->usn = const_cpu_to_le64(0); - } else - clear_nino_flag(ni, v3_Extensions); - if (!S_ISREG(type) && !S_ISDIR(type)) { - si->file_attributes = FILE_ATTR_SYSTEM; - ni->flags = FILE_ATTR_SYSTEM; - } - if ((dir_ni->flags & FILE_ATTR_COMPRESSED) - && (S_ISREG(type) || S_ISDIR(type))) - ni->flags |= FILE_ATTR_COMPRESSED; - /* Add STANDARD_INFORMATION to inode. */ - if (ntfs_attr_add(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0, - (u8*)si, si_len)) { - err = errno; - ntfs_log_error("Failed to add STANDARD_INFORMATION " - "attribute.\n"); - goto err_out; - } + /* Create INDEX_ROOT attribute. */ + index_len = sizeof(INDEX_HEADER) + sizeof(INDEX_ENTRY_HEADER); + ir_len = offsetof(INDEX_ROOT, index) + index_len; + ir = ntfs_calloc(ir_len); + if (!ir) { + err = errno; + goto err_out; + } + ir->type = AT_FILE_NAME; + ir->collation_rule = COLLATION_FILE_NAME; + ir->index_block_size = cpu_to_le32(ni->vol->indx_record_size); + if (ni->vol->cluster_size <= ni->vol->indx_record_size) + ir->clusters_per_index_block = + ni->vol->indx_record_size >> + ni->vol->cluster_size_bits; + else + ir->clusters_per_index_block = + ni->vol->indx_record_size >> + ni->vol->sector_size_bits; + ir->index.entries_offset = cpu_to_le32(sizeof(INDEX_HEADER)); + ir->index.index_length = cpu_to_le32(index_len); + ir->index.allocated_size = cpu_to_le32(index_len); + ie = (INDEX_ENTRY*)((u8*)ir + sizeof(INDEX_ROOT)); + ie->length = cpu_to_le16(sizeof(INDEX_ENTRY_HEADER)); + ie->key_length = 0; + ie->ie_flags = INDEX_ENTRY_END; + /* Add INDEX_ROOT attribute to inode. */ + if (ntfs_attr_add(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4, + (u8*)ir, ir_len)) { + err = errno; + free(ir); + ntfs_log_error("Failed to add INDEX_ROOT attribute.\n"); + goto err_out; + } + free(ir); + } else { + INTX_FILE *data; + int data_len; - if (!securid) { - if (ntfs_sd_add_everyone(ni)) { - err = errno; - goto err_out; - } - } - rollback_sd = 1; - - if (S_ISDIR(type)) { - INDEX_ROOT *ir = NULL; - INDEX_ENTRY *ie; - int ir_len, index_len; - - /* Create INDEX_ROOT attribute. */ - index_len = sizeof(INDEX_HEADER) + sizeof(INDEX_ENTRY_HEADER); - ir_len = offsetof(INDEX_ROOT, index) + index_len; - ir = ntfs_calloc(ir_len); - if (!ir) { - err = errno; - goto err_out; - } - ir->type = AT_FILE_NAME; - ir->collation_rule = COLLATION_FILE_NAME; - ir->index_block_size = cpu_to_le32(ni->vol->indx_record_size); - if (ni->vol->cluster_size <= ni->vol->indx_record_size) - ir->clusters_per_index_block = - ni->vol->indx_record_size >> - ni->vol->cluster_size_bits; - else - ir->clusters_per_index_block = - ni->vol->indx_record_size >> - ni->vol->sector_size_bits; - ir->index.entries_offset = cpu_to_le32(sizeof(INDEX_HEADER)); - ir->index.index_length = cpu_to_le32(index_len); - ir->index.allocated_size = cpu_to_le32(index_len); - ie = (INDEX_ENTRY*)((u8*)ir + sizeof(INDEX_ROOT)); - ie->length = cpu_to_le16(sizeof(INDEX_ENTRY_HEADER)); - ie->key_length = 0; - ie->ie_flags = INDEX_ENTRY_END; - /* Add INDEX_ROOT attribute to inode. */ - if (ntfs_attr_add(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4, - (u8*)ir, ir_len)) { - err = errno; - free(ir); - ntfs_log_error("Failed to add INDEX_ROOT attribute.\n"); - goto err_out; - } - free(ir); - } else { - INTX_FILE *data; - int data_len; - - switch (type) { - case S_IFBLK: - case S_IFCHR: - data_len = offsetof(INTX_FILE, device_end); - data = ntfs_malloc(data_len); - if (!data) { - err = errno; - goto err_out; - } - data->major = cpu_to_le64(major(dev)); - data->minor = cpu_to_le64(minor(dev)); - if (type == S_IFBLK) - data->magic = INTX_BLOCK_DEVICE; - if (type == S_IFCHR) - data->magic = INTX_CHARACTER_DEVICE; - break; - case S_IFLNK: - data_len = sizeof(INTX_FILE_TYPES) + - target_len * sizeof(ntfschar); - data = ntfs_malloc(data_len); - if (!data) { - err = errno; - goto err_out; - } - data->magic = INTX_SYMBOLIC_LINK; - memcpy(data->target, target, - target_len * sizeof(ntfschar)); - break; - case S_IFSOCK: - data = NULL; - data_len = 1; - break; - default: /* FIFO or regular file. */ - data = NULL; - data_len = 0; - break; - } - /* Add DATA attribute to inode. */ - if (ntfs_attr_add(ni, AT_DATA, AT_UNNAMED, 0, (u8*)data, - data_len)) { - err = errno; - ntfs_log_error("Failed to add DATA attribute.\n"); - free(data); - goto err_out; - } - rollback_data = 1; - free(data); - } - /* Create FILE_NAME attribute. */ - fn_len = sizeof(FILE_NAME_ATTR) + name_len * sizeof(ntfschar); - fn = ntfs_calloc(fn_len); - if (!fn) { - err = errno; - goto err_out; - } - fn->parent_directory = MK_LE_MREF(dir_ni->mft_no, - le16_to_cpu(dir_ni->mrec->sequence_number)); - fn->file_name_length = name_len; - fn->file_name_type = FILE_NAME_POSIX; - if (S_ISDIR(type)) - fn->file_attributes = FILE_ATTR_I30_INDEX_PRESENT; - if (!S_ISREG(type) && !S_ISDIR(type)) - fn->file_attributes = FILE_ATTR_SYSTEM; - else - fn->file_attributes |= ni->flags & FILE_ATTR_COMPRESSED; - fn->creation_time = utc2ntfs(ni->creation_time); - fn->last_data_change_time = utc2ntfs(ni->last_data_change_time); - fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); - fn->last_access_time = utc2ntfs(ni->last_access_time); - fn->data_size = cpu_to_sle64(ni->data_size); - fn->allocated_size = cpu_to_sle64(ni->allocated_size); - memcpy(fn->file_name, name, name_len * sizeof(ntfschar)); - /* Add FILE_NAME attribute to inode. */ - if (ntfs_attr_add(ni, AT_FILE_NAME, AT_UNNAMED, 0, (u8*)fn, fn_len)) { - err = errno; - ntfs_log_error("Failed to add FILE_NAME attribute.\n"); - goto err_out; - } - /* Add FILE_NAME attribute to index. */ - if (ntfs_index_add_filename(dir_ni, fn, MK_MREF(ni->mft_no, - le16_to_cpu(ni->mrec->sequence_number)))) { - err = errno; - ntfs_log_perror("Failed to add entry to the index"); - goto err_out; - } - /* Set hard links count and directory flag. */ - ni->mrec->link_count = cpu_to_le16(1); - if (S_ISDIR(type)) - ni->mrec->flags |= MFT_RECORD_IS_DIRECTORY; - ntfs_inode_mark_dirty(ni); - /* Done! */ - free(fn); - free(si); - ntfs_log_trace("Done.\n"); - return ni; + switch (type) { + case S_IFBLK: + case S_IFCHR: + data_len = offsetof(INTX_FILE, device_end); + data = ntfs_malloc(data_len); + if (!data) { + err = errno; + goto err_out; + } + data->major = cpu_to_le64(major(dev)); + data->minor = cpu_to_le64(minor(dev)); + if (type == S_IFBLK) + data->magic = INTX_BLOCK_DEVICE; + if (type == S_IFCHR) + data->magic = INTX_CHARACTER_DEVICE; + break; + case S_IFLNK: + data_len = sizeof(INTX_FILE_TYPES) + + target_len * sizeof(ntfschar); + data = ntfs_malloc(data_len); + if (!data) { + err = errno; + goto err_out; + } + data->magic = INTX_SYMBOLIC_LINK; + memcpy(data->target, target, + target_len * sizeof(ntfschar)); + break; + case S_IFSOCK: + data = NULL; + data_len = 1; + break; + default: /* FIFO or regular file. */ + data = NULL; + data_len = 0; + break; + } + /* Add DATA attribute to inode. */ + if (ntfs_attr_add(ni, AT_DATA, AT_UNNAMED, 0, (u8*)data, + data_len)) { + err = errno; + ntfs_log_error("Failed to add DATA attribute.\n"); + free(data); + goto err_out; + } + rollback_data = 1; + free(data); + } + /* Create FILE_NAME attribute. */ + fn_len = sizeof(FILE_NAME_ATTR) + name_len * sizeof(ntfschar); + fn = ntfs_calloc(fn_len); + if (!fn) { + err = errno; + goto err_out; + } + fn->parent_directory = MK_LE_MREF(dir_ni->mft_no, + le16_to_cpu(dir_ni->mrec->sequence_number)); + fn->file_name_length = name_len; + fn->file_name_type = FILE_NAME_POSIX; + if (S_ISDIR(type)) + fn->file_attributes = FILE_ATTR_I30_INDEX_PRESENT; + if (!S_ISREG(type) && !S_ISDIR(type)) + fn->file_attributes = FILE_ATTR_SYSTEM; + else + fn->file_attributes |= ni->flags & FILE_ATTR_COMPRESSED; + fn->creation_time = utc2ntfs(ni->creation_time); + fn->last_data_change_time = utc2ntfs(ni->last_data_change_time); + fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); + fn->last_access_time = utc2ntfs(ni->last_access_time); + fn->data_size = cpu_to_sle64(ni->data_size); + fn->allocated_size = cpu_to_sle64(ni->allocated_size); + memcpy(fn->file_name, name, name_len * sizeof(ntfschar)); + /* Add FILE_NAME attribute to inode. */ + if (ntfs_attr_add(ni, AT_FILE_NAME, AT_UNNAMED, 0, (u8*)fn, fn_len)) { + err = errno; + ntfs_log_error("Failed to add FILE_NAME attribute.\n"); + goto err_out; + } + /* Add FILE_NAME attribute to index. */ + if (ntfs_index_add_filename(dir_ni, fn, MK_MREF(ni->mft_no, + le16_to_cpu(ni->mrec->sequence_number)))) { + err = errno; + ntfs_log_perror("Failed to add entry to the index"); + goto err_out; + } + /* Set hard links count and directory flag. */ + ni->mrec->link_count = cpu_to_le16(1); + if (S_ISDIR(type)) + ni->mrec->flags |= MFT_RECORD_IS_DIRECTORY; + ntfs_inode_mark_dirty(ni); + /* Done! */ + free(fn); + free(si); + ntfs_log_trace("Done.\n"); + return ni; err_out: - ntfs_log_trace("Failed.\n"); + ntfs_log_trace("Failed.\n"); - if (rollback_sd) - ntfs_attr_remove(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0); - - if (rollback_data) - ntfs_attr_remove(ni, AT_DATA, AT_UNNAMED, 0); - /* - * Free extent MFT records (should not exist any with current - * ntfs_create implementation, but for any case if something will be - * changed in the future). - */ - while (ni->nr_extents) - if (ntfs_mft_record_free(ni->vol, *(ni->extent_nis))) { - err = errno; - ntfs_log_error("Failed to free extent MFT record. " - "Leaving inconsistent metadata.\n"); - } - if (ntfs_mft_record_free(ni->vol, ni)) - ntfs_log_error("Failed to free MFT record. " - "Leaving inconsistent metadata. Run chkdsk.\n"); - free(fn); - free(si); - errno = err; - return NULL; + if (rollback_sd) + ntfs_attr_remove(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0); + + if (rollback_data) + ntfs_attr_remove(ni, AT_DATA, AT_UNNAMED, 0); + /* + * Free extent MFT records (should not exist any with current + * ntfs_create implementation, but for any case if something will be + * changed in the future). + */ + while (ni->nr_extents) + if (ntfs_mft_record_free(ni->vol, *(ni->extent_nis))) { + err = errno; + ntfs_log_error("Failed to free extent MFT record. " + "Leaving inconsistent metadata.\n"); + } + if (ntfs_mft_record_free(ni->vol, ni)) + ntfs_log_error("Failed to free MFT record. " + "Leaving inconsistent metadata. Run chkdsk.\n"); + free(fn); + free(si); + errno = err; + return NULL; } /** @@ -1417,82 +1418,87 @@ err_out: */ ntfs_inode *ntfs_create(ntfs_inode *dir_ni, le32 securid, ntfschar *name, - u8 name_len, mode_t type) { - if (type != S_IFREG && type != S_IFDIR && type != S_IFIFO && - type != S_IFSOCK) { - ntfs_log_error("Invalid arguments.\n"); - return NULL; - } - return __ntfs_create(dir_ni, securid, name, name_len, type, 0, NULL, 0); + u8 name_len, mode_t type) +{ + if (type != S_IFREG && type != S_IFDIR && type != S_IFIFO && + type != S_IFSOCK) { + ntfs_log_error("Invalid arguments.\n"); + return NULL; + } + return __ntfs_create(dir_ni, securid, name, name_len, type, 0, NULL, 0); } ntfs_inode *ntfs_create_device(ntfs_inode *dir_ni, le32 securid, - ntfschar *name, u8 name_len, mode_t type, dev_t dev) { - if (type != S_IFCHR && type != S_IFBLK) { - ntfs_log_error("Invalid arguments.\n"); - return NULL; - } - return __ntfs_create(dir_ni, securid, name, name_len, type, dev, NULL, 0); + ntfschar *name, u8 name_len, mode_t type, dev_t dev) +{ + if (type != S_IFCHR && type != S_IFBLK) { + ntfs_log_error("Invalid arguments.\n"); + return NULL; + } + return __ntfs_create(dir_ni, securid, name, name_len, type, dev, NULL, 0); } ntfs_inode *ntfs_create_symlink(ntfs_inode *dir_ni, le32 securid, - ntfschar *name, u8 name_len, ntfschar *target, int target_len) { - if (!target || !target_len) { - ntfs_log_error("%s: Invalid argument (%p, %d)\n", __FUNCTION__, - target, target_len); - return NULL; - } - return __ntfs_create(dir_ni, securid, name, name_len, S_IFLNK, 0, - target, target_len); + ntfschar *name, u8 name_len, ntfschar *target, int target_len) +{ + if (!target || !target_len) { + ntfs_log_error("%s: Invalid argument (%p, %d)\n", __FUNCTION__, + target, target_len); + return NULL; + } + return __ntfs_create(dir_ni, securid, name, name_len, S_IFLNK, 0, + target, target_len); } -int ntfs_check_empty_dir(ntfs_inode *ni) { - ntfs_attr *na; - int ret = 0; +int ntfs_check_empty_dir(ntfs_inode *ni) +{ + ntfs_attr *na; + int ret = 0; + + if (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) + return 0; - if (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) - return 0; - - na = ntfs_attr_open(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4); - if (!na) { - errno = EIO; - ntfs_log_perror("Failed to open directory"); - return -1; - } - - /* Non-empty directory? */ - if ((na->data_size != sizeof(INDEX_ROOT) + sizeof(INDEX_ENTRY_HEADER))) { - /* Both ENOTEMPTY and EEXIST are ok. We use the more common. */ - errno = ENOTEMPTY; - ntfs_log_debug("Directory is not empty\n"); - ret = -1; - } - - ntfs_attr_close(na); - return ret; + na = ntfs_attr_open(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4); + if (!na) { + errno = EIO; + ntfs_log_perror("Failed to open directory"); + return -1; + } + + /* Non-empty directory? */ + if ((na->data_size != sizeof(INDEX_ROOT) + sizeof(INDEX_ENTRY_HEADER))){ + /* Both ENOTEMPTY and EEXIST are ok. We use the more common. */ + errno = ENOTEMPTY; + ntfs_log_debug("Directory is not empty\n"); + ret = -1; + } + + ntfs_attr_close(na); + return ret; } -static int ntfs_check_unlinkable_dir(ntfs_inode *ni, FILE_NAME_ATTR *fn) { - int link_count = le16_to_cpu(ni->mrec->link_count); - int ret; - - ret = ntfs_check_empty_dir(ni); - if (!ret || errno != ENOTEMPTY) - return ret; - /* - * Directory is non-empty, so we can unlink only if there is more than - * one "real" hard link, i.e. links aren't different DOS and WIN32 names - */ - if ((link_count == 1) || - (link_count == 2 && fn->file_name_type == FILE_NAME_DOS)) { - errno = ENOTEMPTY; - ntfs_log_debug("Non-empty directory without hard links\n"); - goto no_hardlink; - } - - ret = 0; -no_hardlink: - return ret; +static int ntfs_check_unlinkable_dir(ntfs_inode *ni, FILE_NAME_ATTR *fn) +{ + int link_count = le16_to_cpu(ni->mrec->link_count); + int ret; + + ret = ntfs_check_empty_dir(ni); + if (!ret || errno != ENOTEMPTY) + return ret; + /* + * Directory is non-empty, so we can unlink only if there is more than + * one "real" hard link, i.e. links aren't different DOS and WIN32 names + */ + if ((link_count == 1) || + (link_count == 2 && fn->file_name_type == FILE_NAME_DOS)) { + errno = ENOTEMPTY; + ntfs_log_debug("Non-empty directory without hard links\n"); + goto no_hardlink; + } + + ret = 0; +no_hardlink: + return ret; } /** @@ -1508,224 +1514,225 @@ no_hardlink: * Return 0 on success or -1 on error with errno set to the error code. */ int ntfs_delete(ntfs_volume *vol, const char *pathname, - ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len) { - ntfs_attr_search_ctx *actx = NULL; - FILE_NAME_ATTR *fn = NULL; - BOOL looking_for_dos_name = FALSE, looking_for_win32_name = FALSE; - BOOL case_sensitive_match = TRUE; - int err = 0; + ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len) +{ + ntfs_attr_search_ctx *actx = NULL; + FILE_NAME_ATTR *fn = NULL; + BOOL looking_for_dos_name = FALSE, looking_for_win32_name = FALSE; + BOOL case_sensitive_match = TRUE; + int err = 0; #if CACHE_INODE_SIZE - struct CACHED_INODE item; - const char *p; - u64 inum = (u64)-1; - int count; + struct CACHED_INODE item; + const char *p; + u64 inum = (u64)-1; + int count; #endif - ntfs_log_trace("Entering.\n"); - - if (!ni || !dir_ni || !name || !name_len) { - ntfs_log_error("Invalid arguments.\n"); - errno = EINVAL; - goto err_out; - } - if (ni->nr_extents == -1) - ni = ni->base_ni; - if (dir_ni->nr_extents == -1) - dir_ni = dir_ni->base_ni; - /* - * Search for FILE_NAME attribute with such name. If it's in POSIX or - * WIN32_AND_DOS namespace, then simply remove it from index and inode. - * If filename in DOS or in WIN32 namespace, then remove DOS name first, - * only then remove WIN32 name. - */ - actx = ntfs_attr_get_search_ctx(ni, NULL); - if (!actx) - goto err_out; + ntfs_log_trace("Entering.\n"); + + if (!ni || !dir_ni || !name || !name_len) { + ntfs_log_error("Invalid arguments.\n"); + errno = EINVAL; + goto err_out; + } + if (ni->nr_extents == -1) + ni = ni->base_ni; + if (dir_ni->nr_extents == -1) + dir_ni = dir_ni->base_ni; + /* + * Search for FILE_NAME attribute with such name. If it's in POSIX or + * WIN32_AND_DOS namespace, then simply remove it from index and inode. + * If filename in DOS or in WIN32 namespace, then remove DOS name first, + * only then remove WIN32 name. + */ + actx = ntfs_attr_get_search_ctx(ni, NULL); + if (!actx) + goto err_out; search: - while (!ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE, - 0, NULL, 0, actx)) { - char *s; - BOOL case_sensitive = IGNORE_CASE; + while (!ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE, + 0, NULL, 0, actx)) { + char *s; + BOOL case_sensitive = IGNORE_CASE; - errno = 0; - fn = (FILE_NAME_ATTR*)((u8*)actx->attr + - le16_to_cpu(actx->attr->value_offset)); - s = ntfs_attr_name_get(fn->file_name, fn->file_name_length); - ntfs_log_trace("name: '%s' type: %d dos: %d win32: %d " - "case: %d\n", s, fn->file_name_type, - looking_for_dos_name, looking_for_win32_name, - case_sensitive_match); - ntfs_attr_name_free(&s); - if (looking_for_dos_name) { - if (fn->file_name_type == FILE_NAME_DOS) - break; - else - continue; - } - if (looking_for_win32_name) { - if (fn->file_name_type == FILE_NAME_WIN32) - break; - else - continue; - } - - /* Ignore hard links from other directories */ - if (dir_ni->mft_no != MREF_LE(fn->parent_directory)) { - ntfs_log_debug("MFT record numbers don't match " - "(%llu != %llu)\n", - (long long unsigned)dir_ni->mft_no, - (long long unsigned)MREF_LE(fn->parent_directory)); - continue; - } - - if (fn->file_name_type == FILE_NAME_POSIX || case_sensitive_match) - case_sensitive = CASE_SENSITIVE; - - if (ntfs_names_are_equal(fn->file_name, fn->file_name_length, - name, name_len, case_sensitive, - ni->vol->upcase, ni->vol->upcase_len)) { - - if (fn->file_name_type == FILE_NAME_WIN32) { - looking_for_dos_name = TRUE; - ntfs_attr_reinit_search_ctx(actx); - continue; - } - if (fn->file_name_type == FILE_NAME_DOS) - looking_for_dos_name = TRUE; - break; - } - } - if (errno) { - /* - * If case sensitive search failed, then try once again - * ignoring case. - */ - if (errno == ENOENT && case_sensitive_match) { - case_sensitive_match = FALSE; - ntfs_attr_reinit_search_ctx(actx); - goto search; - } - goto err_out; - } - - if (ntfs_check_unlinkable_dir(ni, fn) < 0) - goto err_out; - - if (ntfs_index_remove(dir_ni, ni, fn, le32_to_cpu(actx->attr->value_length))) - goto err_out; - - if (ntfs_attr_record_rm(actx)) - goto err_out; - - ni->mrec->link_count = cpu_to_le16(le16_to_cpu( - ni->mrec->link_count) - 1); - - ntfs_inode_mark_dirty(ni); - if (looking_for_dos_name) { - looking_for_dos_name = FALSE; - looking_for_win32_name = TRUE; - ntfs_attr_reinit_search_ctx(actx); - goto search; - } - /* TODO: Update object id, quota and securiry indexes if required. */ - /* - * If hard link count is not equal to zero then we are done. In other - * case there are no reference to this inode left, so we should free all - * non-resident attributes and mark all MFT record as not in use. - */ + errno = 0; + fn = (FILE_NAME_ATTR*)((u8*)actx->attr + + le16_to_cpu(actx->attr->value_offset)); + s = ntfs_attr_name_get(fn->file_name, fn->file_name_length); + ntfs_log_trace("name: '%s' type: %d dos: %d win32: %d " + "case: %d\n", s, fn->file_name_type, + looking_for_dos_name, looking_for_win32_name, + case_sensitive_match); + ntfs_attr_name_free(&s); + if (looking_for_dos_name) { + if (fn->file_name_type == FILE_NAME_DOS) + break; + else + continue; + } + if (looking_for_win32_name) { + if (fn->file_name_type == FILE_NAME_WIN32) + break; + else + continue; + } + + /* Ignore hard links from other directories */ + if (dir_ni->mft_no != MREF_LE(fn->parent_directory)) { + ntfs_log_debug("MFT record numbers don't match " + "(%llu != %llu)\n", + (long long unsigned)dir_ni->mft_no, + (long long unsigned)MREF_LE(fn->parent_directory)); + continue; + } + + if (fn->file_name_type == FILE_NAME_POSIX || case_sensitive_match) + case_sensitive = CASE_SENSITIVE; + + if (ntfs_names_are_equal(fn->file_name, fn->file_name_length, + name, name_len, case_sensitive, + ni->vol->upcase, ni->vol->upcase_len)){ + + if (fn->file_name_type == FILE_NAME_WIN32) { + looking_for_dos_name = TRUE; + ntfs_attr_reinit_search_ctx(actx); + continue; + } + if (fn->file_name_type == FILE_NAME_DOS) + looking_for_dos_name = TRUE; + break; + } + } + if (errno) { + /* + * If case sensitive search failed, then try once again + * ignoring case. + */ + if (errno == ENOENT && case_sensitive_match) { + case_sensitive_match = FALSE; + ntfs_attr_reinit_search_ctx(actx); + goto search; + } + goto err_out; + } + + if (ntfs_check_unlinkable_dir(ni, fn) < 0) + goto err_out; + + if (ntfs_index_remove(dir_ni, ni, fn, le32_to_cpu(actx->attr->value_length))) + goto err_out; + + if (ntfs_attr_record_rm(actx)) + goto err_out; + + ni->mrec->link_count = cpu_to_le16(le16_to_cpu( + ni->mrec->link_count) - 1); + + ntfs_inode_mark_dirty(ni); + if (looking_for_dos_name) { + looking_for_dos_name = FALSE; + looking_for_win32_name = TRUE; + ntfs_attr_reinit_search_ctx(actx); + goto search; + } + /* TODO: Update object id, quota and securiry indexes if required. */ + /* + * If hard link count is not equal to zero then we are done. In other + * case there are no reference to this inode left, so we should free all + * non-resident attributes and mark all MFT record as not in use. + */ #if CACHE_INODE_SIZE - inum = ni->mft_no; + inum = ni->mft_no; #endif - if (ni->mrec->link_count) { - ntfs_inode_update_times(ni, NTFS_UPDATE_CTIME); - goto ok; - } - if (ntfs_delete_reparse_index(ni)) { - /* - * Failed to remove the reparse index : proceed anyway - * This is not a critical error, the entry is useless - * because of sequence_number, and stopping file deletion - * would be much worse as the file is not referenced now. - */ - err = errno; - } - ntfs_attr_reinit_search_ctx(actx); - while (!ntfs_attrs_walk(actx)) { - if (actx->attr->non_resident) { - runlist *rl; + if (ni->mrec->link_count) { + ntfs_inode_update_times(ni, NTFS_UPDATE_CTIME); + goto ok; + } + if (ntfs_delete_reparse_index(ni)) { + /* + * Failed to remove the reparse index : proceed anyway + * This is not a critical error, the entry is useless + * because of sequence_number, and stopping file deletion + * would be much worse as the file is not referenced now. + */ + err = errno; + } + ntfs_attr_reinit_search_ctx(actx); + while (!ntfs_attrs_walk(actx)) { + if (actx->attr->non_resident) { + runlist *rl; - rl = ntfs_mapping_pairs_decompress(ni->vol, actx->attr, - NULL); - if (!rl) { - err = errno; - ntfs_log_error("Failed to decompress runlist. " - "Leaving inconsistent metadata.\n"); - continue; - } - if (ntfs_cluster_free_from_rl(ni->vol, rl)) { - err = errno; - ntfs_log_error("Failed to free clusters. " - "Leaving inconsistent metadata.\n"); - continue; - } - free(rl); - } - } - if (errno != ENOENT) { - err = errno; - ntfs_log_error("Attribute enumeration failed. " - "Probably leaving inconsistent metadata.\n"); - } - /* All extents should be attached after attribute walk. */ - while (ni->nr_extents) - if (ntfs_mft_record_free(ni->vol, *(ni->extent_nis))) { - err = errno; - ntfs_log_error("Failed to free extent MFT record. " - "Leaving inconsistent metadata.\n"); - } - if (ntfs_mft_record_free(ni->vol, ni)) { - err = errno; - ntfs_log_error("Failed to free base MFT record. " - "Leaving inconsistent metadata.\n"); - } - ni = NULL; -ok: - ntfs_inode_update_times(dir_ni, NTFS_UPDATE_MCTIME); + rl = ntfs_mapping_pairs_decompress(ni->vol, actx->attr, + NULL); + if (!rl) { + err = errno; + ntfs_log_error("Failed to decompress runlist. " + "Leaving inconsistent metadata.\n"); + continue; + } + if (ntfs_cluster_free_from_rl(ni->vol, rl)) { + err = errno; + ntfs_log_error("Failed to free clusters. " + "Leaving inconsistent metadata.\n"); + continue; + } + free(rl); + } + } + if (errno != ENOENT) { + err = errno; + ntfs_log_error("Attribute enumeration failed. " + "Probably leaving inconsistent metadata.\n"); + } + /* All extents should be attached after attribute walk. */ + while (ni->nr_extents) + if (ntfs_mft_record_free(ni->vol, *(ni->extent_nis))) { + err = errno; + ntfs_log_error("Failed to free extent MFT record. " + "Leaving inconsistent metadata.\n"); + } + if (ntfs_mft_record_free(ni->vol, ni)) { + err = errno; + ntfs_log_error("Failed to free base MFT record. " + "Leaving inconsistent metadata.\n"); + } + ni = NULL; +ok: + ntfs_inode_update_times(dir_ni, NTFS_UPDATE_MCTIME); out: - if (actx) - ntfs_attr_put_search_ctx(actx); - if (ntfs_inode_close(dir_ni) && !err) - err = errno; - if (ntfs_inode_close(ni) && !err) - err = errno; + if (actx) + ntfs_attr_put_search_ctx(actx); + if (ntfs_inode_close(dir_ni) && !err) + err = errno; + if (ntfs_inode_close(ni) && !err) + err = errno; #if CACHE_INODE_SIZE - if (pathname) { - /* invalide cache entry, even if there was an error */ - /* Remove leading /'s. */ - p = pathname; - while (*p == PATH_SEP) - p++; - if (p[0] && (p[strlen(p)-1] == PATH_SEP)) - ntfs_log_error("Unnormalized path %s\n",pathname); - item.pathname = p; - item.inum = inum; - count = ntfs_invalidate_cache(vol->xinode_cache, GENERIC(&item), - inode_cache_inv_compare); - if (!count) - ntfs_log_error("Could not delete inode cache entry for %s\n", - pathname); - } + if (pathname) { + /* invalide cache entry, even if there was an error */ + /* Remove leading /'s. */ + p = pathname; + while (*p == PATH_SEP) + p++; + if (p[0] && (p[strlen(p)-1] == PATH_SEP)) + ntfs_log_error("Unnormalized path %s\n",pathname); + item.pathname = p; + item.inum = inum; + count = ntfs_invalidate_cache(vol->xinode_cache, GENERIC(&item), + inode_cache_inv_compare); + if (!count) + ntfs_log_error("Could not delete inode cache entry for %s\n", + pathname); + } #endif - if (err) { - errno = err; - ntfs_log_debug("Could not delete file: %s\n", strerror(errno)); - return -1; - } - ntfs_log_trace("Done.\n"); - return 0; + if (err) { + errno = err; + ntfs_log_debug("Could not delete file: %s\n", strerror(errno)); + return -1; + } + ntfs_log_trace("Done.\n"); + return 0; err_out: - err = errno; - goto out; + err = errno; + goto out; } /** @@ -1744,80 +1751,82 @@ err_out: * Return 0 on success or -1 on error with errno set to the error code. */ static int ntfs_link_i(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, - u8 name_len, FILE_NAME_TYPE_FLAGS nametype) { - FILE_NAME_ATTR *fn = NULL; - int fn_len, err; + u8 name_len, FILE_NAME_TYPE_FLAGS nametype) +{ + FILE_NAME_ATTR *fn = NULL; + int fn_len, err; - ntfs_log_trace("Entering.\n"); - - if (!ni || !dir_ni || !name || !name_len || - ni->mft_no == dir_ni->mft_no) { - err = EINVAL; - ntfs_log_perror("ntfs_link wrong arguments"); - goto err_out; - } - - if ((ni->flags & FILE_ATTR_REPARSE_POINT) - && !ntfs_possible_symlink(ni)) { - err = EOPNOTSUPP; - goto err_out; - } - - /* Create FILE_NAME attribute. */ - fn_len = sizeof(FILE_NAME_ATTR) + name_len * sizeof(ntfschar); - fn = ntfs_calloc(fn_len); - if (!fn) { - err = errno; - goto err_out; - } - fn->parent_directory = MK_LE_MREF(dir_ni->mft_no, - le16_to_cpu(dir_ni->mrec->sequence_number)); - fn->file_name_length = name_len; - fn->file_name_type = nametype; - fn->file_attributes = ni->flags; - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - fn->file_attributes |= FILE_ATTR_I30_INDEX_PRESENT; - fn->allocated_size = cpu_to_sle64(ni->allocated_size); - fn->data_size = cpu_to_sle64(ni->data_size); - fn->creation_time = utc2ntfs(ni->creation_time); - fn->last_data_change_time = utc2ntfs(ni->last_data_change_time); - fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); - fn->last_access_time = utc2ntfs(ni->last_access_time); - memcpy(fn->file_name, name, name_len * sizeof(ntfschar)); - /* Add FILE_NAME attribute to index. */ - if (ntfs_index_add_filename(dir_ni, fn, MK_MREF(ni->mft_no, - le16_to_cpu(ni->mrec->sequence_number)))) { - err = errno; - ntfs_log_perror("Failed to add filename to the index"); - goto err_out; - } - /* Add FILE_NAME attribute to inode. */ - if (ntfs_attr_add(ni, AT_FILE_NAME, AT_UNNAMED, 0, (u8*)fn, fn_len)) { - ntfs_log_error("Failed to add FILE_NAME attribute.\n"); - err = errno; - /* Try to remove just added attribute from index. */ - if (ntfs_index_remove(dir_ni, ni, fn, fn_len)) - goto rollback_failed; - goto err_out; - } - /* Increment hard links count. */ - ni->mrec->link_count = cpu_to_le16(le16_to_cpu( - ni->mrec->link_count) + 1); - /* Done! */ - ntfs_inode_mark_dirty(ni); - free(fn); - ntfs_log_trace("Done.\n"); - return 0; + ntfs_log_trace("Entering.\n"); + + if (!ni || !dir_ni || !name || !name_len || + ni->mft_no == dir_ni->mft_no) { + err = EINVAL; + ntfs_log_perror("ntfs_link wrong arguments"); + goto err_out; + } + + if ((ni->flags & FILE_ATTR_REPARSE_POINT) + && !ntfs_possible_symlink(ni)) { + err = EOPNOTSUPP; + goto err_out; + } + + /* Create FILE_NAME attribute. */ + fn_len = sizeof(FILE_NAME_ATTR) + name_len * sizeof(ntfschar); + fn = ntfs_calloc(fn_len); + if (!fn) { + err = errno; + goto err_out; + } + fn->parent_directory = MK_LE_MREF(dir_ni->mft_no, + le16_to_cpu(dir_ni->mrec->sequence_number)); + fn->file_name_length = name_len; + fn->file_name_type = nametype; + fn->file_attributes = ni->flags; + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + fn->file_attributes |= FILE_ATTR_I30_INDEX_PRESENT; + fn->allocated_size = cpu_to_sle64(ni->allocated_size); + fn->data_size = cpu_to_sle64(ni->data_size); + fn->creation_time = utc2ntfs(ni->creation_time); + fn->last_data_change_time = utc2ntfs(ni->last_data_change_time); + fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); + fn->last_access_time = utc2ntfs(ni->last_access_time); + memcpy(fn->file_name, name, name_len * sizeof(ntfschar)); + /* Add FILE_NAME attribute to index. */ + if (ntfs_index_add_filename(dir_ni, fn, MK_MREF(ni->mft_no, + le16_to_cpu(ni->mrec->sequence_number)))) { + err = errno; + ntfs_log_perror("Failed to add filename to the index"); + goto err_out; + } + /* Add FILE_NAME attribute to inode. */ + if (ntfs_attr_add(ni, AT_FILE_NAME, AT_UNNAMED, 0, (u8*)fn, fn_len)) { + ntfs_log_error("Failed to add FILE_NAME attribute.\n"); + err = errno; + /* Try to remove just added attribute from index. */ + if (ntfs_index_remove(dir_ni, ni, fn, fn_len)) + goto rollback_failed; + goto err_out; + } + /* Increment hard links count. */ + ni->mrec->link_count = cpu_to_le16(le16_to_cpu( + ni->mrec->link_count) + 1); + /* Done! */ + ntfs_inode_mark_dirty(ni); + free(fn); + ntfs_log_trace("Done.\n"); + return 0; rollback_failed: - ntfs_log_error("Rollback failed. Leaving inconsistent metadata.\n"); + ntfs_log_error("Rollback failed. Leaving inconsistent metadata.\n"); err_out: - free(fn); - errno = err; - return -1; + free(fn); + errno = err; + return -1; } -int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len) { - return (ntfs_link_i(ni, dir_ni, name, name_len, FILE_NAME_POSIX)); +int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len) +{ + return (ntfs_link_i(ni, dir_ni, name, name_len, FILE_NAME_POSIX)); } #ifdef HAVE_SETXATTR @@ -1832,37 +1841,38 @@ int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len) { * -1 if there was an error (described by errno) */ -static int get_dos_name(ntfs_inode *ni, u64 dnum, ntfschar *dosname) { - size_t outsize = 0; - FILE_NAME_ATTR *fn; - ntfs_attr_search_ctx *ctx; +static int get_dos_name(ntfs_inode *ni, u64 dnum, ntfschar *dosname) +{ + size_t outsize = 0; + FILE_NAME_ATTR *fn; + ntfs_attr_search_ctx *ctx; - /* find the name in the attributes */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; + /* find the name in the attributes */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return -1; - while (!ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - /* We know this will always be resident. */ - fn = (FILE_NAME_ATTR*)((u8*)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); + while (!ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + /* We know this will always be resident. */ + fn = (FILE_NAME_ATTR*)((u8*)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); - if ((fn->file_name_type & FILE_NAME_DOS) - && (MREF_LE(fn->parent_directory) == dnum)) { - /* - * Found a DOS or WIN32+DOS name for the entry - * copy name, after truncation for safety - */ - outsize = fn->file_name_length; - /* TODO : reject if name is too long ? */ - if (outsize > MAX_DOS_NAME_LENGTH) - outsize = MAX_DOS_NAME_LENGTH; - memcpy(dosname,fn->file_name,outsize*sizeof(ntfschar)); - } - } - ntfs_attr_put_search_ctx(ctx); - return (outsize); + if ((fn->file_name_type & FILE_NAME_DOS) + && (MREF_LE(fn->parent_directory) == dnum)) { + /* + * Found a DOS or WIN32+DOS name for the entry + * copy name, after truncation for safety + */ + outsize = fn->file_name_length; +/* TODO : reject if name is too long ? */ + if (outsize > MAX_DOS_NAME_LENGTH) + outsize = MAX_DOS_NAME_LENGTH; + memcpy(dosname,fn->file_name,outsize*sizeof(ntfschar)); + } + } + ntfs_attr_put_search_ctx(ctx); + return (outsize); } @@ -1871,60 +1881,61 @@ static int get_dos_name(ntfs_inode *ni, u64 dnum, ntfschar *dosname) { */ int ntfs_get_ntfs_dos_name(const char *path, - char *value, size_t size, ntfs_inode *ni) { - int outsize = 0; - char *outname = (char*)NULL; - ntfs_inode *dir_ni = NULL; - u64 dnum; - char *dirname; - const char *rdirname; - char *p; - int doslen; - ntfschar dosname[MAX_DOS_NAME_LENGTH]; + char *value, size_t size, ntfs_inode *ni) +{ + int outsize = 0; + char *outname = (char*)NULL; + ntfs_inode *dir_ni = NULL; + u64 dnum; + char *dirname; + const char *rdirname; + char *p; + int doslen; + ntfschar dosname[MAX_DOS_NAME_LENGTH]; - /* get the parent directory */ - dirname = strdup(path); - if (dirname) { - p = strrchr(dirname,'/'); - if (p) { - *p++ = 0; - rdirname = (dirname[0] ? dirname : "/"); - dir_ni = ntfs_pathname_to_inode(ni->vol, NULL, rdirname); - dnum = dir_ni->mft_no; - free(dirname); - } - } - if (dir_ni) { - doslen = get_dos_name(ni, dnum, dosname); - if (doslen > 0) { - /* - * Found a DOS name for the entry, make - * uppercase and encode into the buffer - * if there is enough space - */ - ntfs_name_upcase(dosname, doslen, - ni->vol->upcase, ni->vol->upcase_len); - if (ntfs_ucstombs(dosname, doslen, &outname, size) < 0) { - ntfs_log_error("Cannot represent dosname in current locale.\n"); - outsize = -errno; - } else { - outsize = strlen(outname); - if (value && (outsize <= (int)size)) - memcpy(value, outname, outsize); - else - if (size && (outsize > (int)size)) - outsize = -ERANGE; - free(outname); - } - } else { - if (doslen == 0) - errno = ENODATA; - outsize = -errno; - } - ntfs_inode_close(dir_ni); - } else - outsize = -errno; - return (outsize); + /* get the parent directory */ + dirname = strdup(path); + if (dirname) { + p = strrchr(dirname,'/'); + if (p) { + *p++ = 0; + rdirname = (dirname[0] ? dirname : "/"); + dir_ni = ntfs_pathname_to_inode(ni->vol, NULL, rdirname); + dnum = dir_ni->mft_no; + free(dirname); + } + } + if (dir_ni) { + doslen = get_dos_name(ni, dnum, dosname); + if (doslen > 0) { + /* + * Found a DOS name for the entry, make + * uppercase and encode into the buffer + * if there is enough space + */ + ntfs_name_upcase(dosname, doslen, + ni->vol->upcase, ni->vol->upcase_len); + if (ntfs_ucstombs(dosname, doslen, &outname, size) < 0) { + ntfs_log_error("Cannot represent dosname in current locale.\n"); + outsize = -errno; + } else { + outsize = strlen(outname); + if (value && (outsize <= (int)size)) + memcpy(value, outname, outsize); + else + if (size && (outsize > (int)size)) + outsize = -ERANGE; + free(outname); + } + } else { + if (doslen == 0) + errno = ENODATA; + outsize = -errno; + } + ntfs_inode_close(dir_ni); + } else + outsize = -errno; + return (outsize); } /* @@ -1935,50 +1946,51 @@ int ntfs_get_ntfs_dos_name(const char *path, */ static int set_namespace(ntfs_inode *ni, ntfs_inode *dir_ni, - ntfschar *name, int len, - FILE_NAME_TYPE_FLAGS nametype) { - ntfs_attr_search_ctx *actx; - ntfs_index_context *icx; - FILE_NAME_ATTR *fnx; - FILE_NAME_ATTR *fn = NULL; - BOOL found; - int lkup; - int ret; + ntfschar *name, int len, + FILE_NAME_TYPE_FLAGS nametype) +{ + ntfs_attr_search_ctx *actx; + ntfs_index_context *icx; + FILE_NAME_ATTR *fnx; + FILE_NAME_ATTR *fn = NULL; + BOOL found; + int lkup; + int ret; - ret = -1; - actx = ntfs_attr_get_search_ctx(ni, NULL); - if (actx) { - found = FALSE; - do { - lkup = ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, - CASE_SENSITIVE, 0, NULL, 0, actx); - if (!lkup) { - fn = (FILE_NAME_ATTR*)((u8*)actx->attr + - le16_to_cpu(actx->attr->value_offset)); - found = (MREF_LE(fn->parent_directory) - == dir_ni->mft_no) - && !memcmp(fn->file_name, name, - len*sizeof(ntfschar)); - } - } while (!lkup && !found); - if (found) { - icx = ntfs_index_ctx_get(dir_ni, NTFS_INDEX_I30, 4); - if (icx) { - lkup = ntfs_index_lookup((char*)fn, len, icx); - if (!lkup && icx->data && icx->data_len) { - fnx = (FILE_NAME_ATTR*)icx->data; - ret = fn->file_name_type; - fn->file_name_type = nametype; - fnx->file_name_type = nametype; - ntfs_inode_mark_dirty(ni); - ntfs_index_entry_mark_dirty(icx); - } - ntfs_index_ctx_put(icx); - } - } - ntfs_attr_put_search_ctx(actx); - } - return (ret); + ret = -1; + actx = ntfs_attr_get_search_ctx(ni, NULL); + if (actx) { + found = FALSE; + do { + lkup = ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, + CASE_SENSITIVE, 0, NULL, 0, actx); + if (!lkup) { + fn = (FILE_NAME_ATTR*)((u8*)actx->attr + + le16_to_cpu(actx->attr->value_offset)); + found = (MREF_LE(fn->parent_directory) + == dir_ni->mft_no) + && !memcmp(fn->file_name, name, + len*sizeof(ntfschar)); + } + } while (!lkup && !found); + if (found) { + icx = ntfs_index_ctx_get(dir_ni, NTFS_INDEX_I30, 4); + if (icx) { + lkup = ntfs_index_lookup((char*)fn, len, icx); + if (!lkup && icx->data && icx->data_len) { + fnx = (FILE_NAME_ATTR*)icx->data; + ret = fn->file_name_type; + fn->file_name_type = nametype; + fnx->file_name_type = nametype; + ntfs_inode_mark_dirty(ni); + ntfs_index_entry_mark_dirty(icx); + } + ntfs_index_ctx_put(icx); + } + } + ntfs_attr_put_search_ctx(actx); + } + return (ret); } /* @@ -2008,83 +2020,84 @@ static int set_namespace(ntfs_inode *ni, ntfs_inode *dir_ni, */ static int set_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, - const char *fullpath, - ntfschar *shortname, int shortlen, - ntfschar *longname, int longlen, - ntfschar *deletename, int deletelen, BOOL existed) { - unsigned int linkcount; - ntfs_volume *vol; - BOOL collapsible; - BOOL deleted; - BOOL done; - FILE_NAME_TYPE_FLAGS oldnametype; - u64 dnum; - u64 fnum; - int res; + const char *fullpath, + ntfschar *shortname, int shortlen, + ntfschar *longname, int longlen, + ntfschar *deletename, int deletelen, BOOL existed) +{ + unsigned int linkcount; + ntfs_volume *vol; + BOOL collapsible; + BOOL deleted; + BOOL done; + FILE_NAME_TYPE_FLAGS oldnametype; + u64 dnum; + u64 fnum; + int res; - res = -1; - vol = ni->vol; - dnum = dir_ni->mft_no; - fnum = ni->mft_no; - /* save initial link count */ - linkcount = le16_to_cpu(ni->mrec->link_count); + res = -1; + vol = ni->vol; + dnum = dir_ni->mft_no; + fnum = ni->mft_no; + /* save initial link count */ + linkcount = le16_to_cpu(ni->mrec->link_count); - /* check whether the same name may be used as DOS and WIN32 */ - collapsible = ntfs_collapsible_chars(ni->vol, shortname, shortlen, - longname, longlen); - if (collapsible) { - deleted = FALSE; - done = FALSE; - if (existed) { - oldnametype = set_namespace(ni, dir_ni, deletename, - deletelen, FILE_NAME_POSIX); - if (oldnametype == FILE_NAME_DOS) { - if (set_namespace(ni, dir_ni, longname, longlen, - FILE_NAME_WIN32_AND_DOS) >= 0) { - if (!ntfs_delete(vol, - (const char*)NULL, ni, dir_ni, - deletename, deletelen)) - res = 0; - deleted = TRUE; - } else - done = TRUE; - } - } - if (!deleted) { - if (!done && (set_namespace(ni, dir_ni, - longname, longlen, - FILE_NAME_WIN32_AND_DOS) >= 0)) - res = 0; - ntfs_inode_close(ni); - ntfs_inode_close(dir_ni); - } - } else - if (!ntfs_link_i(ni, dir_ni, shortname, shortlen, - FILE_NAME_DOS) - /* make sure a new link was recorded */ - && (le16_to_cpu(ni->mrec->link_count) > linkcount)) { - /* delete the existing long name or short name */ - if (!ntfs_delete(vol, fullpath, ni, dir_ni, - deletename, deletelen)) { - /* delete closes the inodes, so have to open again */ - dir_ni = ntfs_inode_open(vol, dnum); - if (dir_ni) { - ni = ntfs_inode_open(vol, fnum); - if (ni) { - if (!ntfs_link_i(ni, dir_ni, - longname, longlen, - FILE_NAME_WIN32)) - res = 0; - ntfs_inode_close(ni); - } - ntfs_inode_close(dir_ni); - } - } - } else { - ntfs_inode_close(ni); - ntfs_inode_close(dir_ni); - } - return (res); + /* check whether the same name may be used as DOS and WIN32 */ + collapsible = ntfs_collapsible_chars(ni->vol, shortname, shortlen, + longname, longlen); + if (collapsible) { + deleted = FALSE; + done = FALSE; + if (existed) { + oldnametype = set_namespace(ni, dir_ni, deletename, + deletelen, FILE_NAME_POSIX); + if (oldnametype == FILE_NAME_DOS) { + if (set_namespace(ni, dir_ni, longname, longlen, + FILE_NAME_WIN32_AND_DOS) >= 0) { + if (!ntfs_delete(vol, + (const char*)NULL, ni, dir_ni, + deletename, deletelen)) + res = 0; + deleted = TRUE; + } else + done = TRUE; + } + } + if (!deleted) { + if (!done && (set_namespace(ni, dir_ni, + longname, longlen, + FILE_NAME_WIN32_AND_DOS) >= 0)) + res = 0; + ntfs_inode_close(ni); + ntfs_inode_close(dir_ni); + } + } else + if (!ntfs_link_i(ni, dir_ni, shortname, shortlen, + FILE_NAME_DOS) + /* make sure a new link was recorded */ + && (le16_to_cpu(ni->mrec->link_count) > linkcount)) { + /* delete the existing long name or short name */ + if (!ntfs_delete(vol, fullpath, ni, dir_ni, + deletename, deletelen)) { + /* delete closes the inodes, so have to open again */ + dir_ni = ntfs_inode_open(vol, dnum); + if (dir_ni) { + ni = ntfs_inode_open(vol, fnum); + if (ni) { + if (!ntfs_link_i(ni, dir_ni, + longname, longlen, + FILE_NAME_WIN32)) + res = 0; + ntfs_inode_close(ni); + } + ntfs_inode_close(dir_ni); + } + } + } else { + ntfs_inode_close(ni); + ntfs_inode_close(dir_ni); + } + return (res); } @@ -2099,188 +2112,190 @@ static int set_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, */ int ntfs_set_ntfs_dos_name(const char *path, const char *value, size_t size, - int flags, ntfs_inode *ni) { - int res = 0; - int longlen = 0; - int shortlen = 0; - char newname[MAX_DOS_NAME_LENGTH + 1]; - ntfschar oldname[MAX_DOS_NAME_LENGTH]; - int oldlen; - ntfs_volume *vol; - u64 fnum; - u64 dnum; - BOOL closed = FALSE; - ntfschar *shortname = NULL; - ntfschar *longname = NULL; - ntfs_inode *dir_ni = NULL; - char *dirname = (char*)NULL; - const char *rdirname; - char *p; + int flags, ntfs_inode *ni) +{ + int res = 0; + int longlen = 0; + int shortlen = 0; + char newname[MAX_DOS_NAME_LENGTH + 1]; + ntfschar oldname[MAX_DOS_NAME_LENGTH]; + int oldlen; + ntfs_volume *vol; + u64 fnum; + u64 dnum; + BOOL closed = FALSE; + ntfschar *shortname = NULL; + ntfschar *longname = NULL; + ntfs_inode *dir_ni = NULL; + char *dirname = (char*)NULL; + const char *rdirname; + char *p; - vol = ni->vol; - fnum = ni->mft_no; - /* convert the string to the NTFS wide chars */ - if (size > MAX_DOS_NAME_LENGTH) - size = MAX_DOS_NAME_LENGTH; - strncpy(newname, value, size); - newname[size] = 0; - shortlen = ntfs_mbstoucs(newname, &shortname); - /* make sure the short name has valid chars */ - if ((shortlen < 0) || ntfs_forbidden_chars(shortname,shortlen)) { - ntfs_inode_close(ni); - res = -errno; - return res; - } - /* get the parent directory */ - dirname = strdup(path); - if (dirname) { - p = strrchr(dirname,'/'); - if (p) { - *p++ = 0; - longlen = ntfs_mbstoucs(p, &longname); - /* make sure the long name had valid chars */ - if (!ntfs_forbidden_chars(longname,longlen)) { - rdirname = (dirname[0] ? dirname : "/"); - dir_ni = ntfs_pathname_to_inode(vol, NULL, rdirname); - } - } - } - if (dir_ni) { - dnum = dir_ni->mft_no; - oldlen = get_dos_name(ni, dnum, oldname); - if (oldlen >= 0) { - if (oldlen > 0) { - if (flags & XATTR_CREATE) { - res = -1; - errno = EEXIST; - } else - if ((shortlen == oldlen) - && !memcmp(shortname,oldname, - oldlen*sizeof(ntfschar))) - /* already set, done */ - res = 0; - else { - res = set_dos_name(ni, dir_ni, - path, - shortname, shortlen, - longname, longlen, - oldname, oldlen, TRUE); - closed = TRUE; - } - } else { - if (flags & XATTR_REPLACE) { - res = -1; - errno = ENODATA; - } else { - res = set_dos_name(ni, dir_ni, path, - shortname, shortlen, - longname, longlen, - longname, longlen, FALSE); - closed = TRUE; - } - } - } else - res = -1; - if (!closed) - ntfs_inode_close(dir_ni); - } else { - res = -1; - errno = EINVAL; - } - free(dirname); - free(longname); - free(shortname); - if (!closed) - ntfs_inode_close(ni); - return (res ? -1 : 0); + vol = ni->vol; + fnum = ni->mft_no; + /* convert the string to the NTFS wide chars */ + if (size > MAX_DOS_NAME_LENGTH) + size = MAX_DOS_NAME_LENGTH; + strncpy(newname, value, size); + newname[size] = 0; + shortlen = ntfs_mbstoucs(newname, &shortname); + /* make sure the short name has valid chars */ + if ((shortlen < 0) || ntfs_forbidden_chars(shortname,shortlen)) { + ntfs_inode_close(ni); + res = -errno; + return res; + } + /* get the parent directory */ + dirname = strdup(path); + if (dirname) { + p = strrchr(dirname,'/'); + if (p) { + *p++ = 0; + longlen = ntfs_mbstoucs(p, &longname); + /* make sure the long name had valid chars */ + if (!ntfs_forbidden_chars(longname,longlen)) { + rdirname = (dirname[0] ? dirname : "/"); + dir_ni = ntfs_pathname_to_inode(vol, NULL, rdirname); + } + } + } + if (dir_ni) { + dnum = dir_ni->mft_no; + oldlen = get_dos_name(ni, dnum, oldname); + if (oldlen >= 0) { + if (oldlen > 0) { + if (flags & XATTR_CREATE) { + res = -1; + errno = EEXIST; + } else + if ((shortlen == oldlen) + && !memcmp(shortname,oldname, + oldlen*sizeof(ntfschar))) + /* already set, done */ + res = 0; + else { + res = set_dos_name(ni, dir_ni, + path, + shortname, shortlen, + longname, longlen, + oldname, oldlen, TRUE); + closed = TRUE; + } + } else { + if (flags & XATTR_REPLACE) { + res = -1; + errno = ENODATA; + } else { + res = set_dos_name(ni, dir_ni, path, + shortname, shortlen, + longname, longlen, + longname, longlen, FALSE); + closed = TRUE; + } + } + } else + res = -1; + if (!closed) + ntfs_inode_close(dir_ni); + } else { + res = -1; + errno = EINVAL; + } + free(dirname); + free(longname); + free(shortname); + if (!closed) + ntfs_inode_close(ni); + return (res ? -1 : 0); } /* * Delete the ntfs DOS name */ -int ntfs_remove_ntfs_dos_name(const char *path, ntfs_inode *ni) { - int res; - int oldnametype; - int longlen = 0; - int shortlen; - u64 dnum; - ntfs_volume *vol; - BOOL deleted = FALSE; - ntfschar shortname[MAX_DOS_NAME_LENGTH]; - ntfschar *longname = NULL; - ntfs_inode *dir_ni = NULL; - char *dirname = (char*)NULL; - const char *rdirname; - char *p; +int ntfs_remove_ntfs_dos_name(const char *path, ntfs_inode *ni) +{ + int res; + int oldnametype; + int longlen = 0; + int shortlen; + u64 dnum; + ntfs_volume *vol; + BOOL deleted = FALSE; + ntfschar shortname[MAX_DOS_NAME_LENGTH]; + ntfschar *longname = NULL; + ntfs_inode *dir_ni = NULL; + char *dirname = (char*)NULL; + const char *rdirname; + char *p; - res = -1; - vol = ni->vol; - /* get the parent directory */ - dirname = strdup(path); - if (dirname) { - p = strrchr(dirname,'/'); - if (p) { - *p++ = 0; - longlen = ntfs_mbstoucs(p, &longname); - rdirname = (dirname[0] ? dirname : "/"); - dir_ni = ntfs_pathname_to_inode(vol, NULL, rdirname); - } - } - if (dir_ni) { - dnum = dir_ni->mft_no; - shortlen = get_dos_name(ni, dnum, shortname); - if (shortlen >= 0) { - /* migrate the long name as Posix */ - oldnametype = set_namespace(ni,dir_ni,longname,longlen, - FILE_NAME_POSIX); - switch (oldnametype) { - case FILE_NAME_WIN32_AND_DOS : - /* name was Win32+DOS : done */ - res = 0; - break; - case FILE_NAME_DOS : - /* name was DOS, make it back to DOS */ - set_namespace(ni,dir_ni,longname,longlen, - FILE_NAME_DOS); - errno = ENOENT; - break; - case FILE_NAME_WIN32 : - /* name was Win32, make it Posix and delete */ - if (set_namespace(ni,dir_ni,shortname,shortlen, - FILE_NAME_POSIX) >= 0) { - if (!ntfs_delete(vol, - (const char*)NULL, ni, - dir_ni, shortname, - shortlen)) - res = 0; - deleted = TRUE; - } else { - /* - * DOS name has been found, but cannot - * migrate to Posix : something bad - * has happened - */ - errno = EIO; - ntfs_log_error("Could not change" - " DOS name of %s to Posix\n", - path); - } - break; - default : - /* name was Posix or not found : error */ - errno = ENOENT; - break; - } - } - if (!deleted) - ntfs_inode_close(dir_ni); - } - if (!deleted) - ntfs_inode_close(ni); - free(longname); - free(dirname); - return (res); + res = -1; + vol = ni->vol; + /* get the parent directory */ + dirname = strdup(path); + if (dirname) { + p = strrchr(dirname,'/'); + if (p) { + *p++ = 0; + longlen = ntfs_mbstoucs(p, &longname); + rdirname = (dirname[0] ? dirname : "/"); + dir_ni = ntfs_pathname_to_inode(vol, NULL, rdirname); + } + } + if (dir_ni) { + dnum = dir_ni->mft_no; + shortlen = get_dos_name(ni, dnum, shortname); + if (shortlen >= 0) { + /* migrate the long name as Posix */ + oldnametype = set_namespace(ni,dir_ni,longname,longlen, + FILE_NAME_POSIX); + switch (oldnametype) { + case FILE_NAME_WIN32_AND_DOS : + /* name was Win32+DOS : done */ + res = 0; + break; + case FILE_NAME_DOS : + /* name was DOS, make it back to DOS */ + set_namespace(ni,dir_ni,longname,longlen, + FILE_NAME_DOS); + errno = ENOENT; + break; + case FILE_NAME_WIN32 : + /* name was Win32, make it Posix and delete */ + if (set_namespace(ni,dir_ni,shortname,shortlen, + FILE_NAME_POSIX) >= 0) { + if (!ntfs_delete(vol, + (const char*)NULL, ni, + dir_ni, shortname, + shortlen)) + res = 0; + deleted = TRUE; + } else { + /* + * DOS name has been found, but cannot + * migrate to Posix : something bad + * has happened + */ + errno = EIO; + ntfs_log_error("Could not change" + " DOS name of %s to Posix\n", + path); + } + break; + default : + /* name was Posix or not found : error */ + errno = ENOENT; + break; + } + } + if (!deleted) + ntfs_inode_close(dir_ni); + } + if (!deleted) + ntfs_inode_close(ni); + free(longname); + free(dirname); + return (res); } #endif diff --git a/source/libntfs/dir.h b/source/libntfs/dir.h index 5595b8bc..49f706fb 100644 --- a/source/libntfs/dir.h +++ b/source/libntfs/dir.h @@ -60,23 +60,23 @@ extern ntfschar NTFS_INDEX_Q[3]; extern ntfschar NTFS_INDEX_R[3]; extern u64 ntfs_inode_lookup_by_name(ntfs_inode *dir_ni, - const ntfschar *uname, const int uname_len); + const ntfschar *uname, const int uname_len); extern ntfs_inode *ntfs_pathname_to_inode(ntfs_volume *vol, ntfs_inode *parent, - const char *pathname); + const char *pathname); extern ntfs_inode *ntfs_create(ntfs_inode *dir_ni, le32 securid, - ntfschar *name, u8 name_len, mode_t type); + ntfschar *name, u8 name_len, mode_t type); extern ntfs_inode *ntfs_create_device(ntfs_inode *dir_ni, le32 securid, - ntfschar *name, u8 name_len, mode_t type, dev_t dev); + ntfschar *name, u8 name_len, mode_t type, dev_t dev); extern ntfs_inode *ntfs_create_symlink(ntfs_inode *dir_ni, le32 securid, - ntfschar *name, u8 name_len, ntfschar *target, int target_len); + ntfschar *name, u8 name_len, ntfschar *target, int target_len); extern int ntfs_check_empty_dir(ntfs_inode *ni); extern int ntfs_delete(ntfs_volume *vol, const char *path, - ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, - u8 name_len); + ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, + u8 name_len); extern int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, - u8 name_len); + u8 name_len); /* * File types (adapted from include ) @@ -98,17 +98,17 @@ extern int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, * to have different dirent layouts depending on the binary type. */ typedef int (*ntfs_filldir_t)(void *dirent, const ntfschar *name, - const int name_len, const int name_type, const s64 pos, - const MFT_REF mref, const unsigned dt_type); + const int name_len, const int name_type, const s64 pos, + const MFT_REF mref, const unsigned dt_type); extern int ntfs_readdir(ntfs_inode *dir_ni, s64 *pos, - void *dirent, ntfs_filldir_t filldir); + void *dirent, ntfs_filldir_t filldir); int ntfs_get_ntfs_dos_name(const char *path, - char *value, size_t size, ntfs_inode *ni); + char *value, size_t size, ntfs_inode *ni); int ntfs_set_ntfs_dos_name(const char *path, - const char *value, size_t size, int flags, - ntfs_inode *ni); + const char *value, size_t size, int flags, + ntfs_inode *ni); int ntfs_remove_ntfs_dos_name(const char *path, ntfs_inode *ni); #endif /* defined _NTFS_DIR_H */ diff --git a/source/libntfs/efs.c b/source/libntfs/efs.c index 824c203c..e7a134a2 100644 --- a/source/libntfs/efs.c +++ b/source/libntfs/efs.c @@ -61,11 +61,11 @@ #ifdef HAVE_SETXATTR /* extended attributes interface required */ static ntfschar logged_utility_stream_name[] = { - const_cpu_to_le16('$'), - const_cpu_to_le16('E'), - const_cpu_to_le16('F'), - const_cpu_to_le16('S'), - const_cpu_to_le16(0) + const_cpu_to_le16('$'), + const_cpu_to_le16('E'), + const_cpu_to_le16('F'), + const_cpu_to_le16('S'), + const_cpu_to_le16(0) } ; @@ -74,47 +74,48 @@ static ntfschar logged_utility_stream_name[] = { */ int ntfs_get_efs_info(const char *path, - char *value, size_t size, ntfs_inode *ni) { - EFS_ATTR_HEADER *efs_info; - s64 attr_size = 0; + char *value, size_t size, ntfs_inode *ni) +{ + EFS_ATTR_HEADER *efs_info; + s64 attr_size = 0; - if (ni) { - if (ni->flags & FILE_ATTR_ENCRYPTED) { - efs_info = (EFS_ATTR_HEADER*)ntfs_attr_readall(ni, - AT_LOGGED_UTILITY_STREAM,(ntfschar*)NULL, 0, - &attr_size); - if (efs_info - && (le32_to_cpu(efs_info->length) == attr_size)) { - if (attr_size <= (s64)size) { - if (value) - memcpy(value,efs_info,attr_size); - else { - errno = EFAULT; - attr_size = 0; - } - } else - if (size) { - errno = ERANGE; - attr_size = 0; - } - free (efs_info); - } else { - if (efs_info) { - free(efs_info); - ntfs_log_info("Bad efs_info for file %s\n",path); - } else { - ntfs_log_info("Could not get efsinfo" - " for file %s\n", path); - } - errno = EIO; - attr_size = 0; - } - } else { - errno = ENODATA; - ntfs_log_info("File %s is not encrypted",path); - } - } - return (attr_size ? (int)attr_size : -errno); + if (ni) { + if (ni->flags & FILE_ATTR_ENCRYPTED) { + efs_info = (EFS_ATTR_HEADER*)ntfs_attr_readall(ni, + AT_LOGGED_UTILITY_STREAM,(ntfschar*)NULL, 0, + &attr_size); + if (efs_info + && (le32_to_cpu(efs_info->length) == attr_size)) { + if (attr_size <= (s64)size) { + if (value) + memcpy(value,efs_info,attr_size); + else { + errno = EFAULT; + attr_size = 0; + } + } else + if (size) { + errno = ERANGE; + attr_size = 0; + } + free (efs_info); + } else { + if (efs_info) { + free(efs_info); + ntfs_log_info("Bad efs_info for file %s\n",path); + } else { + ntfs_log_info("Could not get efsinfo" + " for file %s\n", path); + } + errno = EIO; + attr_size = 0; + } + } else { + errno = ENODATA; + ntfs_log_info("File %s is not encrypted",path); + } + } + return (attr_size ? (int)attr_size : -errno); } /* @@ -124,111 +125,112 @@ int ntfs_get_efs_info(const char *path, */ int ntfs_set_efs_info(const char *path __attribute__((unused)), - const char *value, size_t size, int flags, - ntfs_inode *ni) { - int res; - int written; - ntfs_attr *na; - const EFS_ATTR_HEADER *info_header; - ntfs_attr_search_ctx *ctx; + const char *value, size_t size, int flags, + ntfs_inode *ni) +{ + int res; + int written; + ntfs_attr *na; + const EFS_ATTR_HEADER *info_header; + ntfs_attr_search_ctx *ctx; - res = 0; - if (ni && value && size) { - if (ni->flags & (FILE_ATTR_ENCRYPTED | FILE_ATTR_COMPRESSED)) { - if (ni->flags & FILE_ATTR_ENCRYPTED) { - ntfs_log_info("File %s already encrypted",path); - errno = EEXIST; - } else { - /* - * Possible problem : if encrypted file was - * restored in a compressed directory, it was - * restored as compressed. - * TODO : decompress first. - */ - ntfs_log_error("File %s cannot be encrypted and compressed\n", - path); - errno = EIO; - } - return -1; - } - info_header = (const EFS_ATTR_HEADER*)value; - /* make sure we get a likely efsinfo */ - if (le32_to_cpu(info_header->length) != size) { - errno = EINVAL; - return (-1); - } - if (!ntfs_attr_exist(ni,AT_LOGGED_UTILITY_STREAM, - (ntfschar*)NULL,0)) { - if (!(flags & XATTR_REPLACE)) { - /* - * no logged_utility_stream attribute : add one, - * apparently, this does not feed the new value in - */ - res = ntfs_attr_add(ni,AT_LOGGED_UTILITY_STREAM, - logged_utility_stream_name,4, - (u8*)NULL,(s64)size); - } else { - errno = ENODATA; - res = -1; - } - } else { - errno = EEXIST; - res = -1; - } - if (!res) { - /* - * open and update the existing efs data - */ - na = ntfs_attr_open(ni, AT_LOGGED_UTILITY_STREAM, - logged_utility_stream_name, 4); - if (na) { - /* resize attribute */ - res = ntfs_attr_truncate(na, (s64)size); - /* overwrite value if any */ - if (!res && value) { - written = (int)ntfs_attr_pwrite(na, - (s64)0, (s64)size, value); - if (written != (s64)size) { - ntfs_log_error("Failed to " - "update efs data\n"); - errno = EIO; - res = -1; - } - } - ntfs_attr_close(na); - } else - res = -1; - } - if (!res) { - /* Don't handle AT_DATA Attribute(s) if inode is a directory */ - if (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { - /* iterate over AT_DATA attributes */ - /* set encrypted flag, truncate attribute to match padding bytes */ - - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) { - ntfs_log_error("Failed to get ctx for efs\n"); - return (-1); - } - while (!ntfs_attr_lookup(AT_DATA, NULL, 0, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (ntfs_efs_fixup_attribute(ctx, NULL)) { - ntfs_log_error("Error in efs fixup of AT_DATA Attribute"); - ntfs_attr_put_search_ctx(ctx); - return(-1); - } - } - ntfs_attr_put_search_ctx(ctx); - } - ni->flags |= FILE_ATTR_ENCRYPTED; - NInoSetDirty(ni); - NInoFileNameSetDirty(ni); - } - } else { - errno = EINVAL; - res = -1; - } - return (res ? -1 : 0); + res = 0; + if (ni && value && size) { + if (ni->flags & (FILE_ATTR_ENCRYPTED | FILE_ATTR_COMPRESSED)) { + if (ni->flags & FILE_ATTR_ENCRYPTED) { + ntfs_log_info("File %s already encrypted",path); + errno = EEXIST; + } else { + /* + * Possible problem : if encrypted file was + * restored in a compressed directory, it was + * restored as compressed. + * TODO : decompress first. + */ + ntfs_log_error("File %s cannot be encrypted and compressed\n", + path); + errno = EIO; + } + return -1; + } + info_header = (const EFS_ATTR_HEADER*)value; + /* make sure we get a likely efsinfo */ + if (le32_to_cpu(info_header->length) != size) { + errno = EINVAL; + return (-1); + } + if (!ntfs_attr_exist(ni,AT_LOGGED_UTILITY_STREAM, + (ntfschar*)NULL,0)) { + if (!(flags & XATTR_REPLACE)) { + /* + * no logged_utility_stream attribute : add one, + * apparently, this does not feed the new value in + */ + res = ntfs_attr_add(ni,AT_LOGGED_UTILITY_STREAM, + logged_utility_stream_name,4, + (u8*)NULL,(s64)size); + } else { + errno = ENODATA; + res = -1; + } + } else { + errno = EEXIST; + res = -1; + } + if (!res) { + /* + * open and update the existing efs data + */ + na = ntfs_attr_open(ni, AT_LOGGED_UTILITY_STREAM, + logged_utility_stream_name, 4); + if (na) { + /* resize attribute */ + res = ntfs_attr_truncate(na, (s64)size); + /* overwrite value if any */ + if (!res && value) { + written = (int)ntfs_attr_pwrite(na, + (s64)0, (s64)size, value); + if (written != (s64)size) { + ntfs_log_error("Failed to " + "update efs data\n"); + errno = EIO; + res = -1; + } + } + ntfs_attr_close(na); + } else + res = -1; + } + if (!res) { + /* Don't handle AT_DATA Attribute(s) if inode is a directory */ + if (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { + /* iterate over AT_DATA attributes */ + /* set encrypted flag, truncate attribute to match padding bytes */ + + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) { + ntfs_log_error("Failed to get ctx for efs\n"); + return (-1); + } + while (!ntfs_attr_lookup(AT_DATA, NULL, 0, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (ntfs_efs_fixup_attribute(ctx, NULL)) { + ntfs_log_error("Error in efs fixup of AT_DATA Attribute"); + ntfs_attr_put_search_ctx(ctx); + return(-1); + } + } + ntfs_attr_put_search_ctx(ctx); + } + ni->flags |= FILE_ATTR_ENCRYPTED; + NInoSetDirty(ni); + NInoFileNameSetDirty(ni); + } + } else { + errno = EINVAL; + res = -1; + } + return (res ? -1 : 0); } /* @@ -236,105 +238,106 @@ int ntfs_set_efs_info(const char *path __attribute__((unused)), * read padding length from last two bytes * truncate attribute, make non-resident, * set data size to match padding length - * set ATTR_IS_ENCRYPTED flag on attribute + * set ATTR_IS_ENCRYPTED flag on attribute * * Return 0 if successful * -1 if failed (errno tells why) */ -int ntfs_efs_fixup_attribute(ntfs_attr_search_ctx *ctx, ntfs_attr *na) { - u64 newsize; - le16 appended_bytes; - u16 padding_length; - ATTR_RECORD *a; - ntfs_inode *ni; - BOOL close_na = FALSE; - BOOL close_ctx = FALSE; +int ntfs_efs_fixup_attribute(ntfs_attr_search_ctx *ctx, ntfs_attr *na) +{ + u64 newsize; + le16 appended_bytes; + u16 padding_length; + ATTR_RECORD *a; + ntfs_inode *ni; + BOOL close_na = FALSE; + BOOL close_ctx = FALSE; - if (!ctx && !na) { - ntfs_log_error("neither ctx nor na specified for efs_fixup_attribute\n"); - goto err_out; - } - if (!ctx) { - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) { - ntfs_log_error("Failed to get ctx for efs\n"); - goto err_out; - } - close_ctx=TRUE; - if (ntfs_attr_lookup(AT_DATA, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - ntfs_log_error("attr lookup for AT_DATA attribute failed in efs fixup\n"); - goto err_out; - } - } + if (!ctx && !na) { + ntfs_log_error("neither ctx nor na specified for efs_fixup_attribute\n"); + goto err_out; + } + if (!ctx) { + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) { + ntfs_log_error("Failed to get ctx for efs\n"); + goto err_out; + } + close_ctx=TRUE; + if (ntfs_attr_lookup(AT_DATA, na->name, na->name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + ntfs_log_error("attr lookup for AT_DATA attribute failed in efs fixup\n"); + goto err_out; + } + } - a = ctx->attr; - if (!na) { - na = ntfs_attr_open(ctx->ntfs_ino, AT_DATA, - (ntfschar*)((u8*)a + le16_to_cpu(a->name_offset)), - a->name_length); - if (!na) { - ntfs_log_error("can't open DATA Attribute\n"); - return (-1); - } - close_na = TRUE; - } - /* make sure size is valid for a raw encrypted stream */ - if ((na->data_size & 511) != 2) { - ntfs_log_error("Bad raw encrypted stream"); - goto err_out; - } - /* read padding length from last two bytes of attribute */ - if (ntfs_attr_pread(na, na->data_size-2, 2, &appended_bytes) != 2) { - ntfs_log_error("Error reading padding length\n"); - goto err_out; - } - padding_length = le16_to_cpu(appended_bytes); - if (padding_length > 511 || padding_length > na->data_size-2) { - errno = EINVAL; - ntfs_log_error("invalid padding length %d for data_size %lld\n", - padding_length, (long long)na->data_size); - goto err_out; - } - newsize = na->data_size - padding_length - 2; - /* truncate attribute to possibly free clusters allocated - for the last two bytes */ - if (ntfs_attr_truncate(na, na->data_size-2)) { - ntfs_log_error("Error truncating attribute\n"); - goto err_out; - } + a = ctx->attr; + if (!na) { + na = ntfs_attr_open(ctx->ntfs_ino, AT_DATA, + (ntfschar*)((u8*)a + le16_to_cpu(a->name_offset)), + a->name_length); + if (!na) { + ntfs_log_error("can't open DATA Attribute\n"); + return (-1); + } + close_na = TRUE; + } + /* make sure size is valid for a raw encrypted stream */ + if ((na->data_size & 511) != 2) { + ntfs_log_error("Bad raw encrypted stream"); + goto err_out; + } + /* read padding length from last two bytes of attribute */ + if (ntfs_attr_pread(na, na->data_size-2, 2, &appended_bytes) != 2) { + ntfs_log_error("Error reading padding length\n"); + goto err_out; + } + padding_length = le16_to_cpu(appended_bytes); + if (padding_length > 511 || padding_length > na->data_size-2) { + errno = EINVAL; + ntfs_log_error("invalid padding length %d for data_size %lld\n", + padding_length, (long long)na->data_size); + goto err_out; + } + newsize = na->data_size - padding_length - 2; + /* truncate attribute to possibly free clusters allocated + for the last two bytes */ + if (ntfs_attr_truncate(na, na->data_size-2)) { + ntfs_log_error("Error truncating attribute\n"); + goto err_out; + } - /* Encrypted AT_DATA Attributes MUST be non-resident */ - if (!NAttrNonResident(na) - && ntfs_attr_make_non_resident(na, ctx)) { - ntfs_log_error("Error making DATA attribute non-resident\n"); - goto err_out; - } - ni = na->ni; - if (!na->name_len) { - ni->data_size = newsize; - ni->allocated_size = na->allocated_size; - } - NInoSetDirty(ni); - NInoFileNameSetDirty(ni); - if (close_na) - ntfs_attr_close(na); + /* Encrypted AT_DATA Attributes MUST be non-resident */ + if (!NAttrNonResident(na) + && ntfs_attr_make_non_resident(na, ctx)) { + ntfs_log_error("Error making DATA attribute non-resident\n"); + goto err_out; + } + ni = na->ni; + if (!na->name_len) { + ni->data_size = newsize; + ni->allocated_size = na->allocated_size; + } + NInoSetDirty(ni); + NInoFileNameSetDirty(ni); + if (close_na) + ntfs_attr_close(na); - ctx->attr->data_size = cpu_to_le64(newsize); - if (le64_to_cpu(ctx->attr->initialized_size) > newsize) - ctx->attr->initialized_size = ctx->attr->data_size; - ctx->attr->flags |= ATTR_IS_ENCRYPTED; - if (close_ctx) - ntfs_attr_put_search_ctx(ctx); - - return (0); + ctx->attr->data_size = cpu_to_le64(newsize); + if (le64_to_cpu(ctx->attr->initialized_size) > newsize) + ctx->attr->initialized_size = ctx->attr->data_size; + ctx->attr->flags |= ATTR_IS_ENCRYPTED; + if (close_ctx) + ntfs_attr_put_search_ctx(ctx); + + return (0); err_out: - if (close_na && na) - ntfs_attr_close(na); - if (close_ctx && ctx) - ntfs_attr_put_search_ctx(ctx); - return (-1); + if (close_na && na) + ntfs_attr_close(na); + if (close_ctx && ctx) + ntfs_attr_put_search_ctx(ctx); + return (-1); } #endif /* HAVE_SETXATTR */ diff --git a/source/libntfs/efs.h b/source/libntfs/efs.h index d2a8184e..bb28e3c7 100644 --- a/source/libntfs/efs.h +++ b/source/libntfs/efs.h @@ -22,10 +22,10 @@ #define EFS_H int ntfs_get_efs_info(const char *path, - char *value, size_t size, ntfs_inode *ni); + char *value, size_t size, ntfs_inode *ni); int ntfs_set_efs_info(const char *path, - const char *value, size_t size, int flags, - ntfs_inode *ni); + const char *value, size_t size, int flags, + ntfs_inode *ni); int ntfs_efs_fixup_attribute(ntfs_attr_search_ctx *ctx, ntfs_attr *na); #endif /* EFS_H */ diff --git a/source/libntfs/endians.h b/source/libntfs/endians.h index e5f7e4db..397f1c20 100644 --- a/source/libntfs/endians.h +++ b/source/libntfs/endians.h @@ -1,5 +1,5 @@ /* - * endians.h - Definitions related to handling of byte ordering. + * endians.h - Definitions related to handling of byte ordering. * Originated from the Linux-NTFS project. * * Copyright (c) 2000-2005 Anton Altaparmakov diff --git a/source/libntfs/gekko_io.c b/source/libntfs/gekko_io.c index c5232a0e..61db831e 100644 --- a/source/libntfs/gekko_io.c +++ b/source/libntfs/gekko_io.c @@ -74,7 +74,8 @@ static bool ntfs_device_gekko_io_writesectors(struct ntfs_device *dev, sec_t sec /** * */ -static int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) { +static int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) +{ ntfs_log_trace("dev %p, flags %i\n", dev, flags); // Get the device driver descriptor @@ -158,7 +159,8 @@ static int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) { /** * */ -static int ntfs_device_gekko_io_close(struct ntfs_device *dev) { +static int ntfs_device_gekko_io_close(struct ntfs_device *dev) +{ ntfs_log_trace("dev %p\n", dev); // Get the device driver descriptor @@ -212,7 +214,8 @@ static int ntfs_device_gekko_io_close(struct ntfs_device *dev) { /** * */ -static s64 ntfs_device_gekko_io_seek(struct ntfs_device *dev, s64 offset, int whence) { +static s64 ntfs_device_gekko_io_seek(struct ntfs_device *dev, s64 offset, int whence) +{ ntfs_log_trace("dev %p, offset %Li, whence %i\n", dev, offset, whence); // Get the device driver descriptor @@ -223,16 +226,10 @@ static s64 ntfs_device_gekko_io_seek(struct ntfs_device *dev, s64 offset, int wh } // Set the current position on the device (in bytes) - switch (whence) { - case SEEK_SET: - fd->pos = MIN(MAX(offset, 0), fd->len); - break; - case SEEK_CUR: - fd->pos = MIN(MAX(fd->pos + offset, 0), fd->len); - break; - case SEEK_END: - fd->pos = MIN(MAX(fd->len + offset, 0), fd->len); - break; + switch(whence) { + case SEEK_SET: fd->pos = MIN(MAX(offset, 0), fd->len); break; + case SEEK_CUR: fd->pos = MIN(MAX(fd->pos + offset, 0), fd->len); break; + case SEEK_END: fd->pos = MIN(MAX(fd->len + offset, 0), fd->len); break; } return 0; @@ -241,35 +238,40 @@ static s64 ntfs_device_gekko_io_seek(struct ntfs_device *dev, s64 offset, int wh /** * */ -static s64 ntfs_device_gekko_io_read(struct ntfs_device *dev, void *buf, s64 count) { +static s64 ntfs_device_gekko_io_read(struct ntfs_device *dev, void *buf, s64 count) +{ return ntfs_device_gekko_io_readbytes(dev, DEV_FD(dev)->pos, count, buf); } /** * */ -static s64 ntfs_device_gekko_io_write(struct ntfs_device *dev, const void *buf, s64 count) { +static s64 ntfs_device_gekko_io_write(struct ntfs_device *dev, const void *buf, s64 count) +{ return ntfs_device_gekko_io_writebytes(dev, DEV_FD(dev)->pos, count, buf); } /** * */ -static s64 ntfs_device_gekko_io_pread(struct ntfs_device *dev, void *buf, s64 count, s64 offset) { +static s64 ntfs_device_gekko_io_pread(struct ntfs_device *dev, void *buf, s64 count, s64 offset) +{ return ntfs_device_gekko_io_readbytes(dev, offset, count, buf); } /** * */ -static s64 ntfs_device_gekko_io_pwrite(struct ntfs_device *dev, const void *buf, s64 count, s64 offset) { +static s64 ntfs_device_gekko_io_pwrite(struct ntfs_device *dev, const void *buf, s64 count, s64 offset) +{ return ntfs_device_gekko_io_writebytes(dev, offset, count, buf); } /** * */ -static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s64 count, void *buf) { +static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s64 count, void *buf) +{ //ntfs_log_trace("dev %p, offset %Li, count %Li\n", dev, offset, count); ntfs_log_trace("dev %p, offset %d, count %d\n", dev, (u32)offset, (u32)count); @@ -287,7 +289,7 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s return -1; } - if (!count) + if(!count) return 0; sec_t sec_start = (sec_t) fd->startSector; @@ -306,7 +308,7 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s // If this read happens to be on the sector boundaries then do the read straight into the destination buffer - if ((offset % fd->sectorSize == 0) && (count % fd->sectorSize == 0)) { + if((offset % fd->sectorSize == 0) && (count % fd->sectorSize == 0)) { // Read from the device ntfs_log_trace("direct read from sector %d (%d sector(s) long)\n", sec_start, sec_count); @@ -316,8 +318,9 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s return -1; } - // Else read into a buffer and copy over only what was requested - } else { + // Else read into a buffer and copy over only what was requested + } else + { // Allocate a buffer to hold the read data buffer = (u8*)ntfs_alloc(sec_count * fd->sectorSize); @@ -348,7 +351,8 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s /** * */ -static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, s64 count, const void *buf) { +static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, s64 count, const void *buf) +{ ntfs_log_trace("dev %p, offset %Li, count %Li\n", dev, offset, count); // Get the device driver descriptor @@ -371,7 +375,7 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, return -1; } - if (!count) + if(!count) return 0; sec_t sec_start = (sec_t) fd->startSector; @@ -389,7 +393,7 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, } // If this write happens to be on the sector boundaries then do the write straight to disc - if ((offset % fd->sectorSize == 0) && (count % fd->sectorSize == 0)) { + if((offset % fd->sectorSize == 0) && (count % fd->sectorSize == 0)) { // Write to the device ntfs_log_trace("direct write to sector %d (%d sector(s) long)\n", sec_start, sec_count); @@ -399,7 +403,7 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, return -1; } - // Else write from a buffer aligned to the sector boundaries + // Else write from a buffer aligned to the sector boundaries } else { // Allocate a buffer to hold the write data @@ -411,7 +415,7 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, // Read the first and last sectors of the buffer from disc (if required) // NOTE: This is done because the data does not line up with the sector boundaries, // we just read in the buffer edges where the data overlaps with the rest of the disc - if (offset % fd->sectorSize != 0) { + if(offset % fd->sectorSize != 0) { if (!ntfs_device_gekko_io_readsectors(dev, sec_start, 1, buffer)) { ntfs_log_perror("read failure @ sector %d\n", sec_start); ntfs_free(buffer); @@ -419,12 +423,12 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, return -1; } } - if (count % fd->sectorSize != 0) { + if(count % fd->sectorSize != 0) { if (!ntfs_device_gekko_io_readsectors(dev, sec_start + sec_count-1, 1, buffer + ((sec_count - 1) * fd->sectorSize))) { - ntfs_log_perror("read failure @ sector %d\n", sec_start + sec_count); - ntfs_free(buffer); - errno = EIO; - return -1; + ntfs_log_perror("read failure @ sector %d\n", sec_start + sec_count); + ntfs_free(buffer); + errno = EIO; + return -1; } } @@ -452,7 +456,8 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, return count; } -static bool ntfs_device_gekko_io_readsectors(struct ntfs_device *dev, sec_t sector, sec_t numSectors, void* buffer) { +static bool ntfs_device_gekko_io_readsectors(struct ntfs_device *dev, sec_t sector, sec_t numSectors, void* buffer) +{ // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); if (!fd) { @@ -468,7 +473,8 @@ static bool ntfs_device_gekko_io_readsectors(struct ntfs_device *dev, sec_t sect return false; } -static bool ntfs_device_gekko_io_writesectors(struct ntfs_device *dev, sec_t sector, sec_t numSectors, const void* buffer) { +static bool ntfs_device_gekko_io_writesectors(struct ntfs_device *dev, sec_t sector, sec_t numSectors, const void* buffer) +{ // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); if (!fd) { @@ -488,8 +494,9 @@ static bool ntfs_device_gekko_io_writesectors(struct ntfs_device *dev, sec_t sec /** * */ -static int ntfs_device_gekko_io_sync(struct ntfs_device *dev) { - gekko_fd *fd = DEV_FD(dev); +static int ntfs_device_gekko_io_sync(struct ntfs_device *dev) +{ + gekko_fd *fd = DEV_FD(dev); ntfs_log_trace("dev %p\n", dev); // Check that the device can be written to @@ -515,7 +522,8 @@ static int ntfs_device_gekko_io_sync(struct ntfs_device *dev) { /** * */ -static int ntfs_device_gekko_io_stat(struct ntfs_device *dev, struct stat *buf) { +static int ntfs_device_gekko_io_stat(struct ntfs_device *dev, struct stat *buf) +{ ntfs_log_trace("dev %p, buf %p\n", dev, buf); // Get the device driver descriptor @@ -551,7 +559,8 @@ static int ntfs_device_gekko_io_stat(struct ntfs_device *dev, struct stat *buf) /** * */ -static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void *argp) { +static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void *argp) +{ ntfs_log_trace("dev %p, request %i, argp %p\n", dev, request, argp); // Get the device driver descriptor @@ -565,24 +574,24 @@ static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void switch (request) { // Get block device size (sectors) -#if defined(BLKGETSIZE) - case BLKGETSIZE: { + #if defined(BLKGETSIZE) + case BLKGETSIZE: { *(u32*)argp = fd->sectorCount; return 0; } -#endif + #endif // Get block device size (bytes) -#if defined(BLKGETSIZE64) - case BLKGETSIZE64: { + #if defined(BLKGETSIZE64) + case BLKGETSIZE64: { *(u64*)argp = (fd->sectorCount * fd->sectorSize); return 0; } -#endif + #endif // Get hard drive geometry -#if defined(HDIO_GETGEO) - case HDIO_GETGEO: { + #if defined(HDIO_GETGEO) + case HDIO_GETGEO: { struct hd_geometry *geo = (struct hd_geometry*)argp; geo->sectors = 0; geo->heads = 0; @@ -590,19 +599,19 @@ static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void geo->start = fd->hiddenSectors; return -1; } -#endif + #endif // Get block device sector size (bytes) -#if defined(BLKSSZGET) - case BLKSSZGET: { + #if defined(BLKSSZGET) + case BLKSSZGET: { *(int*)argp = fd->sectorSize; return 0; } -#endif + #endif // Set block device block size (bytes) -#if defined(BLKBSZSET) - case BLKBSZSET: { + #if defined(BLKBSZSET) + case BLKBSZSET: { int sectorSize = *(int*)argp; if (sectorSize != BYTES_PER_SECTOR) { ntfs_log_perror("Attempt to set sector size to an unsupported value (%i), ignored\n", sectorSize); @@ -612,10 +621,10 @@ static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void fd->sectorSize = sectorSize; return 0; } -#endif + #endif // Unimplemented ioctrl - default: { + default: { ntfs_log_perror("Unimplemented ioctrl %i\n", request); errno = EOPNOTSUPP; return -1; diff --git a/source/libntfs/gekko_io.h b/source/libntfs/gekko_io.h index 218ddbed..5f6ba035 100644 --- a/source/libntfs/gekko_io.h +++ b/source/libntfs/gekko_io.h @@ -44,7 +44,7 @@ typedef struct _gekko_fd { u64 pos; /* Current position within the partition (in bytes) */ u64 len; /* Total length of partition (in bytes) */ ino_t ino; /* Device identifier */ - NTFS_CACHE *cache; /* Cache */ + NTFS_CACHE *cache; /* Cache */ u32 cachePageCount; /* The number of pages in the cache */ u32 cachePageSize; /* The number of sectors per cache page */ } gekko_fd; diff --git a/source/libntfs/index.c b/source/libntfs/index.c index 485ab688..f78336aa 100644 --- a/source/libntfs/index.c +++ b/source/libntfs/index.c @@ -62,44 +62,49 @@ * attribute, set ib_dirty to TRUE, thus index block will be updated during * ntfs_index_ctx_put. */ -void ntfs_index_entry_mark_dirty(ntfs_index_context *ictx) { - if (ictx->is_in_root) - ntfs_inode_mark_dirty(ictx->actx->ntfs_ino); - else - ictx->ib_dirty = TRUE; +void ntfs_index_entry_mark_dirty(ntfs_index_context *ictx) +{ + if (ictx->is_in_root) + ntfs_inode_mark_dirty(ictx->actx->ntfs_ino); + else + ictx->ib_dirty = TRUE; } -static s64 ntfs_ib_vcn_to_pos(ntfs_index_context *icx, VCN vcn) { - return vcn << icx->vcn_size_bits; +static s64 ntfs_ib_vcn_to_pos(ntfs_index_context *icx, VCN vcn) +{ + return vcn << icx->vcn_size_bits; } -static VCN ntfs_ib_pos_to_vcn(ntfs_index_context *icx, s64 pos) { - return pos >> icx->vcn_size_bits; +static VCN ntfs_ib_pos_to_vcn(ntfs_index_context *icx, s64 pos) +{ + return pos >> icx->vcn_size_bits; } -static int ntfs_ib_write(ntfs_index_context *icx, INDEX_BLOCK *ib) { - s64 ret, vcn = sle64_to_cpu(ib->index_block_vcn); - - ntfs_log_trace("vcn: %lld\n", (long long)vcn); - - ret = ntfs_attr_mst_pwrite(icx->ia_na, ntfs_ib_vcn_to_pos(icx, vcn), - 1, icx->block_size, ib); - if (ret != 1) { - ntfs_log_perror("Failed to write index block %lld, inode %llu", - (long long)vcn, (unsigned long long)icx->ni->mft_no); - return STATUS_ERROR; - } - - return STATUS_OK; +static int ntfs_ib_write(ntfs_index_context *icx, INDEX_BLOCK *ib) +{ + s64 ret, vcn = sle64_to_cpu(ib->index_block_vcn); + + ntfs_log_trace("vcn: %lld\n", (long long)vcn); + + ret = ntfs_attr_mst_pwrite(icx->ia_na, ntfs_ib_vcn_to_pos(icx, vcn), + 1, icx->block_size, ib); + if (ret != 1) { + ntfs_log_perror("Failed to write index block %lld, inode %llu", + (long long)vcn, (unsigned long long)icx->ni->mft_no); + return STATUS_ERROR; + } + + return STATUS_OK; } -static int ntfs_icx_ib_write(ntfs_index_context *icx) { - if (ntfs_ib_write(icx, icx->ib)) - return STATUS_ERROR; - - icx->ib_dirty = FALSE; - - return STATUS_OK; +static int ntfs_icx_ib_write(ntfs_index_context *icx) +{ + if (ntfs_ib_write(icx, icx->ib)) + return STATUS_ERROR; + + icx->ib_dirty = FALSE; + + return STATUS_OK; } /** @@ -112,45 +117,47 @@ static int ntfs_icx_ib_write(ntfs_index_context *icx) { * Return NULL if allocation failed. */ ntfs_index_context *ntfs_index_ctx_get(ntfs_inode *ni, - ntfschar *name, u32 name_len) { - ntfs_index_context *icx; + ntfschar *name, u32 name_len) +{ + ntfs_index_context *icx; - ntfs_log_trace("Entering\n"); - - if (!ni) { - errno = EINVAL; - return NULL; - } - if (ni->nr_extents == -1) - ni = ni->base_ni; - icx = ntfs_calloc(sizeof(ntfs_index_context)); - if (icx) - *icx = (ntfs_index_context) { - .ni = ni, - .name = name, - .name_len = name_len, - }; - return icx; + ntfs_log_trace("Entering\n"); + + if (!ni) { + errno = EINVAL; + return NULL; + } + if (ni->nr_extents == -1) + ni = ni->base_ni; + icx = ntfs_calloc(sizeof(ntfs_index_context)); + if (icx) + *icx = (ntfs_index_context) { + .ni = ni, + .name = name, + .name_len = name_len, + }; + return icx; } -static void ntfs_index_ctx_free(ntfs_index_context *icx) { - ntfs_log_trace("Entering\n"); +static void ntfs_index_ctx_free(ntfs_index_context *icx) +{ + ntfs_log_trace("Entering\n"); + + if (!icx->entry) + return; - if (!icx->entry) - return; + if (icx->actx) + ntfs_attr_put_search_ctx(icx->actx); - if (icx->actx) - ntfs_attr_put_search_ctx(icx->actx); - - if (!icx->is_in_root) { - if (icx->ib_dirty) { - /* FIXME: Error handling!!! */ - ntfs_ib_write(icx, icx->ib); - } - free(icx->ib); - } - - ntfs_attr_close(icx->ia_na); + if (!icx->is_in_root) { + if (icx->ib_dirty) { + /* FIXME: Error handling!!! */ + ntfs_ib_write(icx, icx->ib); + } + free(icx->ib); + } + + ntfs_attr_close(icx->ia_na); } /** @@ -159,9 +166,10 @@ static void ntfs_index_ctx_free(ntfs_index_context *icx) { * * Release the index context @icx, releasing all associated resources. */ -void ntfs_index_ctx_put(ntfs_index_context *icx) { - ntfs_index_ctx_free(icx); - free(icx); +void ntfs_index_ctx_put(ntfs_index_context *icx) +{ + ntfs_index_ctx_free(icx); + free(icx); } /** @@ -170,278 +178,302 @@ void ntfs_index_ctx_put(ntfs_index_context *icx) { * * Reinitialize the index context @icx so it can be used for ntfs_index_lookup. */ -void ntfs_index_ctx_reinit(ntfs_index_context *icx) { - ntfs_log_trace("Entering\n"); - - ntfs_index_ctx_free(icx); - - *icx = (ntfs_index_context) { - .ni = icx->ni, - .name = icx->name, - .name_len = icx->name_len, - }; +void ntfs_index_ctx_reinit(ntfs_index_context *icx) +{ + ntfs_log_trace("Entering\n"); + + ntfs_index_ctx_free(icx); + + *icx = (ntfs_index_context) { + .ni = icx->ni, + .name = icx->name, + .name_len = icx->name_len, + }; } -static VCN *ntfs_ie_get_vcn_addr(INDEX_ENTRY *ie) { - return (VCN *)((u8 *)ie + le16_to_cpu(ie->length) - sizeof(VCN)); +static VCN *ntfs_ie_get_vcn_addr(INDEX_ENTRY *ie) +{ + return (VCN *)((u8 *)ie + le16_to_cpu(ie->length) - sizeof(VCN)); } /** * Get the subnode vcn to which the index entry refers. */ -VCN ntfs_ie_get_vcn(INDEX_ENTRY *ie) { - return sle64_to_cpup(ntfs_ie_get_vcn_addr(ie)); +VCN ntfs_ie_get_vcn(INDEX_ENTRY *ie) +{ + return sle64_to_cpup(ntfs_ie_get_vcn_addr(ie)); } -static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) { - return (INDEX_ENTRY *)((u8 *)ih + le32_to_cpu(ih->entries_offset)); +static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) +{ + return (INDEX_ENTRY *)((u8 *)ih + le32_to_cpu(ih->entries_offset)); } -static INDEX_ENTRY *ntfs_ie_get_next(INDEX_ENTRY *ie) { - return (INDEX_ENTRY *)((char *)ie + le16_to_cpu(ie->length)); +static INDEX_ENTRY *ntfs_ie_get_next(INDEX_ENTRY *ie) +{ + return (INDEX_ENTRY *)((char *)ie + le16_to_cpu(ie->length)); } -static u8 *ntfs_ie_get_end(INDEX_HEADER *ih) { - /* FIXME: check if it isn't overflowing the index block size */ - return (u8 *)ih + le32_to_cpu(ih->index_length); +static u8 *ntfs_ie_get_end(INDEX_HEADER *ih) +{ + /* FIXME: check if it isn't overflowing the index block size */ + return (u8 *)ih + le32_to_cpu(ih->index_length); } -static int ntfs_ie_end(INDEX_ENTRY *ie) { - return ie->ie_flags & INDEX_ENTRY_END || !ie->length; +static int ntfs_ie_end(INDEX_ENTRY *ie) +{ + return ie->ie_flags & INDEX_ENTRY_END || !ie->length; } -/** +/** * Find the last entry in the index block */ -static INDEX_ENTRY *ntfs_ie_get_last(INDEX_ENTRY *ie, char *ies_end) { - ntfs_log_trace("Entering\n"); - - while ((char *)ie < ies_end && !ntfs_ie_end(ie)) - ie = ntfs_ie_get_next(ie); - - return ie; +static INDEX_ENTRY *ntfs_ie_get_last(INDEX_ENTRY *ie, char *ies_end) +{ + ntfs_log_trace("Entering\n"); + + while ((char *)ie < ies_end && !ntfs_ie_end(ie)) + ie = ntfs_ie_get_next(ie); + + return ie; } -static INDEX_ENTRY *ntfs_ie_get_by_pos(INDEX_HEADER *ih, int pos) { - INDEX_ENTRY *ie; - - ntfs_log_trace("pos: %d\n", pos); - - ie = ntfs_ie_get_first(ih); - - while (pos-- > 0) - ie = ntfs_ie_get_next(ie); - - return ie; +static INDEX_ENTRY *ntfs_ie_get_by_pos(INDEX_HEADER *ih, int pos) +{ + INDEX_ENTRY *ie; + + ntfs_log_trace("pos: %d\n", pos); + + ie = ntfs_ie_get_first(ih); + + while (pos-- > 0) + ie = ntfs_ie_get_next(ie); + + return ie; } -static INDEX_ENTRY *ntfs_ie_prev(INDEX_HEADER *ih, INDEX_ENTRY *ie) { - INDEX_ENTRY *ie_prev = NULL; - INDEX_ENTRY *tmp; - - ntfs_log_trace("Entering\n"); - - tmp = ntfs_ie_get_first(ih); - - while (tmp != ie) { - ie_prev = tmp; - tmp = ntfs_ie_get_next(tmp); - } - - return ie_prev; +static INDEX_ENTRY *ntfs_ie_prev(INDEX_HEADER *ih, INDEX_ENTRY *ie) +{ + INDEX_ENTRY *ie_prev = NULL; + INDEX_ENTRY *tmp; + + ntfs_log_trace("Entering\n"); + + tmp = ntfs_ie_get_first(ih); + + while (tmp != ie) { + ie_prev = tmp; + tmp = ntfs_ie_get_next(tmp); + } + + return ie_prev; } -char *ntfs_ie_filename_get(INDEX_ENTRY *ie) { - FILE_NAME_ATTR *fn; +char *ntfs_ie_filename_get(INDEX_ENTRY *ie) +{ + FILE_NAME_ATTR *fn; - fn = (FILE_NAME_ATTR *)&ie->key; - return ntfs_attr_name_get(fn->file_name, fn->file_name_length); + fn = (FILE_NAME_ATTR *)&ie->key; + return ntfs_attr_name_get(fn->file_name, fn->file_name_length); } -void ntfs_ie_filename_dump(INDEX_ENTRY *ie) { - char *s; +void ntfs_ie_filename_dump(INDEX_ENTRY *ie) +{ + char *s; - s = ntfs_ie_filename_get(ie); - ntfs_log_debug("'%s' ", s); - ntfs_attr_name_free(&s); + s = ntfs_ie_filename_get(ie); + ntfs_log_debug("'%s' ", s); + ntfs_attr_name_free(&s); } -void ntfs_ih_filename_dump(INDEX_HEADER *ih) { - INDEX_ENTRY *ie; - - ntfs_log_trace("Entering\n"); - - ie = ntfs_ie_get_first(ih); - while (!ntfs_ie_end(ie)) { - ntfs_ie_filename_dump(ie); - ie = ntfs_ie_get_next(ie); - } +void ntfs_ih_filename_dump(INDEX_HEADER *ih) +{ + INDEX_ENTRY *ie; + + ntfs_log_trace("Entering\n"); + + ie = ntfs_ie_get_first(ih); + while (!ntfs_ie_end(ie)) { + ntfs_ie_filename_dump(ie); + ie = ntfs_ie_get_next(ie); + } } -static int ntfs_ih_numof_entries(INDEX_HEADER *ih) { - int n; - INDEX_ENTRY *ie; - u8 *end; - - ntfs_log_trace("Entering\n"); - - end = ntfs_ie_get_end(ih); - ie = ntfs_ie_get_first(ih); - for (n = 0; !ntfs_ie_end(ie) && (u8 *)ie < end; n++) - ie = ntfs_ie_get_next(ie); - return n; +static int ntfs_ih_numof_entries(INDEX_HEADER *ih) +{ + int n; + INDEX_ENTRY *ie; + u8 *end; + + ntfs_log_trace("Entering\n"); + + end = ntfs_ie_get_end(ih); + ie = ntfs_ie_get_first(ih); + for (n = 0; !ntfs_ie_end(ie) && (u8 *)ie < end; n++) + ie = ntfs_ie_get_next(ie); + return n; } -static int ntfs_ih_one_entry(INDEX_HEADER *ih) { - return (ntfs_ih_numof_entries(ih) == 1); +static int ntfs_ih_one_entry(INDEX_HEADER *ih) +{ + return (ntfs_ih_numof_entries(ih) == 1); } -static int ntfs_ih_zero_entry(INDEX_HEADER *ih) { - return (ntfs_ih_numof_entries(ih) == 0); +static int ntfs_ih_zero_entry(INDEX_HEADER *ih) +{ + return (ntfs_ih_numof_entries(ih) == 0); } -static void ntfs_ie_delete(INDEX_HEADER *ih, INDEX_ENTRY *ie) { - u32 new_size; - - ntfs_log_trace("Entering\n"); - - new_size = le32_to_cpu(ih->index_length) - le16_to_cpu(ie->length); - ih->index_length = cpu_to_le32(new_size); - memmove(ie, (u8 *)ie + le16_to_cpu(ie->length), - new_size - ((u8 *)ie - (u8 *)ih)); +static void ntfs_ie_delete(INDEX_HEADER *ih, INDEX_ENTRY *ie) +{ + u32 new_size; + + ntfs_log_trace("Entering\n"); + + new_size = le32_to_cpu(ih->index_length) - le16_to_cpu(ie->length); + ih->index_length = cpu_to_le32(new_size); + memmove(ie, (u8 *)ie + le16_to_cpu(ie->length), + new_size - ((u8 *)ie - (u8 *)ih)); } -static void ntfs_ie_set_vcn(INDEX_ENTRY *ie, VCN vcn) { - *ntfs_ie_get_vcn_addr(ie) = cpu_to_le64(vcn); +static void ntfs_ie_set_vcn(INDEX_ENTRY *ie, VCN vcn) +{ + *ntfs_ie_get_vcn_addr(ie) = cpu_to_le64(vcn); } /** * Insert @ie index entry at @pos entry. Used @ih values should be ok already. */ -static void ntfs_ie_insert(INDEX_HEADER *ih, INDEX_ENTRY *ie, INDEX_ENTRY *pos) { - int ie_size = le16_to_cpu(ie->length); - - ntfs_log_trace("Entering\n"); - - ih->index_length = cpu_to_le32(le32_to_cpu(ih->index_length) + ie_size); - memmove((u8 *)pos + ie_size, pos, - le32_to_cpu(ih->index_length) - ((u8 *)pos - (u8 *)ih) - ie_size); - memcpy(pos, ie, ie_size); +static void ntfs_ie_insert(INDEX_HEADER *ih, INDEX_ENTRY *ie, INDEX_ENTRY *pos) +{ + int ie_size = le16_to_cpu(ie->length); + + ntfs_log_trace("Entering\n"); + + ih->index_length = cpu_to_le32(le32_to_cpu(ih->index_length) + ie_size); + memmove((u8 *)pos + ie_size, pos, + le32_to_cpu(ih->index_length) - ((u8 *)pos - (u8 *)ih) - ie_size); + memcpy(pos, ie, ie_size); } -static INDEX_ENTRY *ntfs_ie_dup(INDEX_ENTRY *ie) { - INDEX_ENTRY *dup; - - ntfs_log_trace("Entering\n"); - - dup = ntfs_malloc(le16_to_cpu(ie->length)); - if (dup) - memcpy(dup, ie, le16_to_cpu(ie->length)); - - return dup; +static INDEX_ENTRY *ntfs_ie_dup(INDEX_ENTRY *ie) +{ + INDEX_ENTRY *dup; + + ntfs_log_trace("Entering\n"); + + dup = ntfs_malloc(le16_to_cpu(ie->length)); + if (dup) + memcpy(dup, ie, le16_to_cpu(ie->length)); + + return dup; } -static INDEX_ENTRY *ntfs_ie_dup_novcn(INDEX_ENTRY *ie) { - INDEX_ENTRY *dup; - int size = le16_to_cpu(ie->length); - - ntfs_log_trace("Entering\n"); - - if (ie->ie_flags & INDEX_ENTRY_NODE) - size -= sizeof(VCN); - - dup = ntfs_malloc(size); - if (dup) { - memcpy(dup, ie, size); - dup->ie_flags &= ~INDEX_ENTRY_NODE; - dup->length = cpu_to_le16(size); - } - return dup; +static INDEX_ENTRY *ntfs_ie_dup_novcn(INDEX_ENTRY *ie) +{ + INDEX_ENTRY *dup; + int size = le16_to_cpu(ie->length); + + ntfs_log_trace("Entering\n"); + + if (ie->ie_flags & INDEX_ENTRY_NODE) + size -= sizeof(VCN); + + dup = ntfs_malloc(size); + if (dup) { + memcpy(dup, ie, size); + dup->ie_flags &= ~INDEX_ENTRY_NODE; + dup->length = cpu_to_le16(size); + } + return dup; } -static int ntfs_ia_check(ntfs_index_context *icx, INDEX_BLOCK *ib, VCN vcn) { - u32 ib_size = (unsigned)le32_to_cpu(ib->index.allocated_size) + 0x18; - - ntfs_log_trace("Entering\n"); - - if (!ntfs_is_indx_record(ib->magic)) { - - ntfs_log_error("Corrupt index block signature: vcn %lld inode " - "%llu\n", (long long)vcn, - (unsigned long long)icx->ni->mft_no); - return -1; - } - - if (sle64_to_cpu(ib->index_block_vcn) != vcn) { - - ntfs_log_error("Corrupt index block: VCN (%lld) is different " - "from expected VCN (%lld) in inode %llu\n", - (long long)sle64_to_cpu(ib->index_block_vcn), - (long long)vcn, - (unsigned long long)icx->ni->mft_no); - return -1; - } - - if (ib_size != icx->block_size) { - - ntfs_log_error("Corrupt index block : VCN (%lld) of inode %llu " - "has a size (%u) differing from the index " - "specified size (%u)\n", (long long)vcn, - (unsigned long long)icx->ni->mft_no, ib_size, - icx->block_size); - return -1; - } - return 0; +static int ntfs_ia_check(ntfs_index_context *icx, INDEX_BLOCK *ib, VCN vcn) +{ + u32 ib_size = (unsigned)le32_to_cpu(ib->index.allocated_size) + 0x18; + + ntfs_log_trace("Entering\n"); + + if (!ntfs_is_indx_record(ib->magic)) { + + ntfs_log_error("Corrupt index block signature: vcn %lld inode " + "%llu\n", (long long)vcn, + (unsigned long long)icx->ni->mft_no); + return -1; + } + + if (sle64_to_cpu(ib->index_block_vcn) != vcn) { + + ntfs_log_error("Corrupt index block: VCN (%lld) is different " + "from expected VCN (%lld) in inode %llu\n", + (long long)sle64_to_cpu(ib->index_block_vcn), + (long long)vcn, + (unsigned long long)icx->ni->mft_no); + return -1; + } + + if (ib_size != icx->block_size) { + + ntfs_log_error("Corrupt index block : VCN (%lld) of inode %llu " + "has a size (%u) differing from the index " + "specified size (%u)\n", (long long)vcn, + (unsigned long long)icx->ni->mft_no, ib_size, + icx->block_size); + return -1; + } + return 0; } static INDEX_ROOT *ntfs_ir_lookup(ntfs_inode *ni, ntfschar *name, - u32 name_len, ntfs_attr_search_ctx **ctx) { - ATTR_RECORD *a; - INDEX_ROOT *ir = NULL; + u32 name_len, ntfs_attr_search_ctx **ctx) +{ + ATTR_RECORD *a; + INDEX_ROOT *ir = NULL; - ntfs_log_trace("Entering\n"); - - *ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!*ctx) - return NULL; - - if (ntfs_attr_lookup(AT_INDEX_ROOT, name, name_len, CASE_SENSITIVE, - 0, NULL, 0, *ctx)) { - ntfs_log_perror("Failed to lookup $INDEX_ROOT"); - goto err_out; - } - - a = (*ctx)->attr; - if (a->non_resident) { - errno = EINVAL; - ntfs_log_perror("Non-resident $INDEX_ROOT detected"); - goto err_out; - } - - ir = (INDEX_ROOT *)((char *)a + le16_to_cpu(a->value_offset)); + ntfs_log_trace("Entering\n"); + + *ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!*ctx) + return NULL; + + if (ntfs_attr_lookup(AT_INDEX_ROOT, name, name_len, CASE_SENSITIVE, + 0, NULL, 0, *ctx)) { + ntfs_log_perror("Failed to lookup $INDEX_ROOT"); + goto err_out; + } + + a = (*ctx)->attr; + if (a->non_resident) { + errno = EINVAL; + ntfs_log_perror("Non-resident $INDEX_ROOT detected"); + goto err_out; + } + + ir = (INDEX_ROOT *)((char *)a + le16_to_cpu(a->value_offset)); err_out: - if (!ir) { - ntfs_attr_put_search_ctx(*ctx); - *ctx = NULL; - } - return ir; + if (!ir) { + ntfs_attr_put_search_ctx(*ctx); + *ctx = NULL; + } + return ir; } -static INDEX_ROOT *ntfs_ir_lookup2(ntfs_inode *ni, ntfschar *name, u32 len) { - ntfs_attr_search_ctx *ctx; - INDEX_ROOT *ir; +static INDEX_ROOT *ntfs_ir_lookup2(ntfs_inode *ni, ntfschar *name, u32 len) +{ + ntfs_attr_search_ctx *ctx; + INDEX_ROOT *ir; - ir = ntfs_ir_lookup(ni, name, len, &ctx); - if (ir) - ntfs_attr_put_search_ctx(ctx); - return ir; + ir = ntfs_ir_lookup(ni, name, len, &ctx); + if (ir) + ntfs_attr_put_search_ctx(ctx); + return ir; } -/** +/** * Find a key in the index block. - * + * * Return values: - * STATUS_OK with errno set to ESUCCESS if we know for sure that the + * STATUS_OK with errno set to ESUCCESS if we know for sure that the * entry exists and @ie_out points to this entry. * STATUS_NOT_FOUND with errno set to ENOENT if we know for sure the * entry doesn't exist and @ie_out is the insertion point. @@ -450,148 +482,153 @@ static INDEX_ROOT *ntfs_ir_lookup2(ntfs_inode *ni, ntfschar *name, u32 len) { * STATUS_ERROR with errno set if on unexpected error during lookup. */ static int ntfs_ie_lookup(const void *key, const int key_len, - ntfs_index_context *icx, INDEX_HEADER *ih, - VCN *vcn, INDEX_ENTRY **ie_out) { - INDEX_ENTRY *ie; - u8 *index_end; - int rc, item = 0; + ntfs_index_context *icx, INDEX_HEADER *ih, + VCN *vcn, INDEX_ENTRY **ie_out) +{ + INDEX_ENTRY *ie; + u8 *index_end; + int rc, item = 0; + + ntfs_log_trace("Entering\n"); + + index_end = ntfs_ie_get_end(ih); + + /* + * Loop until we exceed valid memory (corruption case) or until we + * reach the last entry. + */ + for (ie = ntfs_ie_get_first(ih); ; ie = ntfs_ie_get_next(ie)) { + /* Bounds checks. */ + if ((u8 *)ie + sizeof(INDEX_ENTRY_HEADER) > index_end || + (u8 *)ie + le16_to_cpu(ie->length) > index_end) { + errno = ERANGE; + ntfs_log_error("Index entry out of bounds in inode " + "%llu.\n", + (unsigned long long)icx->ni->mft_no); + return STATUS_ERROR; + } + /* + * The last entry cannot contain a key. It can however contain + * a pointer to a child node in the B+tree so we just break out. + */ + if (ntfs_ie_end(ie)) + break; + /* + * Not a perfect match, need to do full blown collation so we + * know which way in the B+tree we have to go. + */ + rc = ntfs_collate(icx->ni->vol, icx->cr, key, key_len, &ie->key, + le16_to_cpu(ie->key_length)); + if (rc == NTFS_COLLATION_ERROR) { + ntfs_log_error("Collation error. Perhaps a filename " + "contains invalid characters?\n"); + errno = ERANGE; + return STATUS_ERROR; + } + /* + * If @key collates before the key of the current entry, there + * is definitely no such key in this index but we might need to + * descend into the B+tree so we just break out of the loop. + */ + if (rc == -1) + break; + + if (!rc) { + *ie_out = ie; + errno = 0; + icx->parent_pos[icx->pindex] = item; + return STATUS_OK; + } + + item++; + } + /* + * We have finished with this index block without success. Check for the + * presence of a child node and if not present return with errno ENOENT, + * otherwise we will keep searching in another index block. + */ + if (!(ie->ie_flags & INDEX_ENTRY_NODE)) { + ntfs_log_debug("Index entry wasn't found.\n"); + *ie_out = ie; + errno = ENOENT; + return STATUS_NOT_FOUND; + } + + /* Get the starting vcn of the index_block holding the child node. */ + *vcn = ntfs_ie_get_vcn(ie); + if (*vcn < 0) { + errno = EINVAL; + ntfs_log_perror("Negative vcn in inode %llu", + (unsigned long long)icx->ni->mft_no); + return STATUS_ERROR; + } - ntfs_log_trace("Entering\n"); - - index_end = ntfs_ie_get_end(ih); - - /* - * Loop until we exceed valid memory (corruption case) or until we - * reach the last entry. - */ - for (ie = ntfs_ie_get_first(ih); ; ie = ntfs_ie_get_next(ie)) { - /* Bounds checks. */ - if ((u8 *)ie + sizeof(INDEX_ENTRY_HEADER) > index_end || - (u8 *)ie + le16_to_cpu(ie->length) > index_end) { - errno = ERANGE; - ntfs_log_error("Index entry out of bounds in inode " - "%llu.\n", - (unsigned long long)icx->ni->mft_no); - return STATUS_ERROR; - } - /* - * The last entry cannot contain a key. It can however contain - * a pointer to a child node in the B+tree so we just break out. - */ - if (ntfs_ie_end(ie)) - break; - /* - * Not a perfect match, need to do full blown collation so we - * know which way in the B+tree we have to go. - */ - rc = ntfs_collate(icx->ni->vol, icx->cr, key, key_len, &ie->key, - le16_to_cpu(ie->key_length)); - if (rc == NTFS_COLLATION_ERROR) { - ntfs_log_error("Collation error. Perhaps a filename " - "contains invalid characters?\n"); - errno = ERANGE; - return STATUS_ERROR; - } - /* - * If @key collates before the key of the current entry, there - * is definitely no such key in this index but we might need to - * descend into the B+tree so we just break out of the loop. - */ - if (rc == -1) - break; - - if (!rc) { - *ie_out = ie; - errno = 0; - icx->parent_pos[icx->pindex] = item; - return STATUS_OK; - } - - item++; - } - /* - * We have finished with this index block without success. Check for the - * presence of a child node and if not present return with errno ENOENT, - * otherwise we will keep searching in another index block. - */ - if (!(ie->ie_flags & INDEX_ENTRY_NODE)) { - ntfs_log_debug("Index entry wasn't found.\n"); - *ie_out = ie; - errno = ENOENT; - return STATUS_NOT_FOUND; - } - - /* Get the starting vcn of the index_block holding the child node. */ - *vcn = ntfs_ie_get_vcn(ie); - if (*vcn < 0) { - errno = EINVAL; - ntfs_log_perror("Negative vcn in inode %llu", - (unsigned long long)icx->ni->mft_no); - return STATUS_ERROR; - } - - ntfs_log_trace("Parent entry number %d\n", item); - icx->parent_pos[icx->pindex] = item; - - return STATUS_KEEP_SEARCHING; + ntfs_log_trace("Parent entry number %d\n", item); + icx->parent_pos[icx->pindex] = item; + + return STATUS_KEEP_SEARCHING; } -static ntfs_attr *ntfs_ia_open(ntfs_index_context *icx, ntfs_inode *ni) { - ntfs_attr *na; - - na = ntfs_attr_open(ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len); - if (!na) { - ntfs_log_perror("Failed to open index allocation of inode " - "%llu", (unsigned long long)ni->mft_no); - return NULL; - } - - return na; +static ntfs_attr *ntfs_ia_open(ntfs_index_context *icx, ntfs_inode *ni) +{ + ntfs_attr *na; + + na = ntfs_attr_open(ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len); + if (!na) { + ntfs_log_perror("Failed to open index allocation of inode " + "%llu", (unsigned long long)ni->mft_no); + return NULL; + } + + return na; } -static int ntfs_ib_read(ntfs_index_context *icx, VCN vcn, INDEX_BLOCK *dst) { - s64 pos, ret; +static int ntfs_ib_read(ntfs_index_context *icx, VCN vcn, INDEX_BLOCK *dst) +{ + s64 pos, ret; - ntfs_log_trace("vcn: %lld\n", (long long)vcn); + ntfs_log_trace("vcn: %lld\n", (long long)vcn); + + pos = ntfs_ib_vcn_to_pos(icx, vcn); - pos = ntfs_ib_vcn_to_pos(icx, vcn); - - ret = ntfs_attr_mst_pread(icx->ia_na, pos, 1, icx->block_size, (u8 *)dst); - if (ret != 1) { - if (ret == -1) - ntfs_log_perror("Failed to read index block"); - else - ntfs_log_error("Failed to read full index block at " - "%lld\n", (long long)pos); - return -1; - } - - if (ntfs_ia_check(icx, dst, vcn)) - return -1; - - return 0; + ret = ntfs_attr_mst_pread(icx->ia_na, pos, 1, icx->block_size, (u8 *)dst); + if (ret != 1) { + if (ret == -1) + ntfs_log_perror("Failed to read index block"); + else + ntfs_log_error("Failed to read full index block at " + "%lld\n", (long long)pos); + return -1; + } + + if (ntfs_ia_check(icx, dst, vcn)) + return -1; + + return 0; } -static int ntfs_icx_parent_inc(ntfs_index_context *icx) { - icx->pindex++; - if (icx->pindex >= MAX_PARENT_VCN) { - errno = EOPNOTSUPP; - ntfs_log_perror("Index is over %d level deep", MAX_PARENT_VCN); - return STATUS_ERROR; - } - return STATUS_OK; +static int ntfs_icx_parent_inc(ntfs_index_context *icx) +{ + icx->pindex++; + if (icx->pindex >= MAX_PARENT_VCN) { + errno = EOPNOTSUPP; + ntfs_log_perror("Index is over %d level deep", MAX_PARENT_VCN); + return STATUS_ERROR; + } + return STATUS_OK; } -static int ntfs_icx_parent_dec(ntfs_index_context *icx) { - icx->pindex--; - if (icx->pindex < 0) { - errno = EINVAL; - ntfs_log_perror("Corrupt index pointer (%d)", icx->pindex); - return STATUS_ERROR; - } - return STATUS_OK; +static int ntfs_icx_parent_dec(ntfs_index_context *icx) +{ + icx->pindex--; + if (icx->pindex < 0) { + errno = EINVAL; + ntfs_log_perror("Corrupt index pointer (%d)", icx->pindex); + return STATUS_ERROR; + } + return STATUS_OK; } - + /** * ntfs_index_lookup - find a key in an index and return its index entry * @key: [IN] key for which to search in the index @@ -624,652 +661,675 @@ static int ntfs_icx_parent_dec(ntfs_index_context *icx) { * the call to ntfs_index_ctx_put() to ensure that the changes are written * to disk. */ -int ntfs_index_lookup(const void *key, const int key_len, ntfs_index_context *icx) { - VCN old_vcn, vcn; - ntfs_inode *ni = icx->ni; - INDEX_ROOT *ir; - INDEX_ENTRY *ie; - INDEX_BLOCK *ib = NULL; - int ret, err = 0; +int ntfs_index_lookup(const void *key, const int key_len, ntfs_index_context *icx) +{ + VCN old_vcn, vcn; + ntfs_inode *ni = icx->ni; + INDEX_ROOT *ir; + INDEX_ENTRY *ie; + INDEX_BLOCK *ib = NULL; + int ret, err = 0; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); + + if (!key || key_len <= 0) { + errno = EINVAL; + ntfs_log_perror("key: %p key_len: %d", key, key_len); + return -1; + } - if (!key || key_len <= 0) { - errno = EINVAL; - ntfs_log_perror("key: %p key_len: %d", key, key_len); - return -1; - } - - ir = ntfs_ir_lookup(ni, icx->name, icx->name_len, &icx->actx); - if (!ir) { - if (errno == ENOENT) - errno = EIO; - return -1; - } - - icx->block_size = le32_to_cpu(ir->index_block_size); - if (icx->block_size < NTFS_BLOCK_SIZE) { - errno = EINVAL; - ntfs_log_perror("Index block size (%d) is smaller than the " - "sector size (%d)", icx->block_size, NTFS_BLOCK_SIZE); - goto err_out; - } - - if (ni->vol->cluster_size <= icx->block_size) - icx->vcn_size_bits = ni->vol->cluster_size_bits; - else - icx->vcn_size_bits = ni->vol->sector_size_bits; - - icx->cr = ir->collation_rule; - if (!ntfs_is_collation_rule_supported(icx->cr)) { - err = errno = EOPNOTSUPP; - ntfs_log_perror("Unknown collation rule 0x%x", - (unsigned)le32_to_cpu(icx->cr)); - goto err_out; - } - - old_vcn = VCN_INDEX_ROOT_PARENT; - /* - * FIXME: check for both ir and ib that the first index entry is - * within the index block. - */ - ret = ntfs_ie_lookup(key, key_len, icx, &ir->index, &vcn, &ie); - if (ret == STATUS_ERROR) { - err = errno; - goto err_out; - } - - icx->ir = ir; - - if (ret != STATUS_KEEP_SEARCHING) { - /* STATUS_OK or STATUS_NOT_FOUND */ - err = errno; - icx->is_in_root = TRUE; - icx->parent_vcn[icx->pindex] = old_vcn; - goto done; - } - - /* Child node present, descend into it. */ - - icx->ia_na = ntfs_ia_open(icx, ni); - if (!icx->ia_na) - goto err_out; - - ib = ntfs_malloc(icx->block_size); - if (!ib) { - err = errno; - goto err_out; - } + ir = ntfs_ir_lookup(ni, icx->name, icx->name_len, &icx->actx); + if (!ir) { + if (errno == ENOENT) + errno = EIO; + return -1; + } + + icx->block_size = le32_to_cpu(ir->index_block_size); + if (icx->block_size < NTFS_BLOCK_SIZE) { + errno = EINVAL; + ntfs_log_perror("Index block size (%d) is smaller than the " + "sector size (%d)", icx->block_size, NTFS_BLOCK_SIZE); + goto err_out; + } + if (ni->vol->cluster_size <= icx->block_size) + icx->vcn_size_bits = ni->vol->cluster_size_bits; + else + icx->vcn_size_bits = ni->vol->sector_size_bits; + + icx->cr = ir->collation_rule; + if (!ntfs_is_collation_rule_supported(icx->cr)) { + err = errno = EOPNOTSUPP; + ntfs_log_perror("Unknown collation rule 0x%x", + (unsigned)le32_to_cpu(icx->cr)); + goto err_out; + } + + old_vcn = VCN_INDEX_ROOT_PARENT; + /* + * FIXME: check for both ir and ib that the first index entry is + * within the index block. + */ + ret = ntfs_ie_lookup(key, key_len, icx, &ir->index, &vcn, &ie); + if (ret == STATUS_ERROR) { + err = errno; + goto err_out; + } + + icx->ir = ir; + + if (ret != STATUS_KEEP_SEARCHING) { + /* STATUS_OK or STATUS_NOT_FOUND */ + err = errno; + icx->is_in_root = TRUE; + icx->parent_vcn[icx->pindex] = old_vcn; + goto done; + } + + /* Child node present, descend into it. */ + + icx->ia_na = ntfs_ia_open(icx, ni); + if (!icx->ia_na) + goto err_out; + + ib = ntfs_malloc(icx->block_size); + if (!ib) { + err = errno; + goto err_out; + } + descend_into_child_node: - icx->parent_vcn[icx->pindex] = old_vcn; - if (ntfs_icx_parent_inc(icx)) { - err = errno; - goto err_out; - } - old_vcn = vcn; + icx->parent_vcn[icx->pindex] = old_vcn; + if (ntfs_icx_parent_inc(icx)) { + err = errno; + goto err_out; + } + old_vcn = vcn; - ntfs_log_debug("Descend into node with VCN %lld\n", (long long)vcn); + ntfs_log_debug("Descend into node with VCN %lld\n", (long long)vcn); + + if (ntfs_ib_read(icx, vcn, ib)) + goto err_out; + + ret = ntfs_ie_lookup(key, key_len, icx, &ib->index, &vcn, &ie); + if (ret != STATUS_KEEP_SEARCHING) { + err = errno; + if (ret == STATUS_ERROR) + goto err_out; + + /* STATUS_OK or STATUS_NOT_FOUND */ + icx->is_in_root = FALSE; + icx->ib = ib; + icx->parent_vcn[icx->pindex] = vcn; + goto done; + } - if (ntfs_ib_read(icx, vcn, ib)) - goto err_out; - - ret = ntfs_ie_lookup(key, key_len, icx, &ib->index, &vcn, &ie); - if (ret != STATUS_KEEP_SEARCHING) { - err = errno; - if (ret == STATUS_ERROR) - goto err_out; - - /* STATUS_OK or STATUS_NOT_FOUND */ - icx->is_in_root = FALSE; - icx->ib = ib; - icx->parent_vcn[icx->pindex] = vcn; - goto done; - } - - if ((ib->index.ih_flags & NODE_MASK) == LEAF_NODE) { - ntfs_log_error("Index entry with child node found in a leaf " - "node in inode 0x%llx.\n", - (unsigned long long)ni->mft_no); - goto err_out; - } - - goto descend_into_child_node; + if ((ib->index.ih_flags & NODE_MASK) == LEAF_NODE) { + ntfs_log_error("Index entry with child node found in a leaf " + "node in inode 0x%llx.\n", + (unsigned long long)ni->mft_no); + goto err_out; + } + + goto descend_into_child_node; err_out: - free(ib); - if (!err) - err = EIO; - errno = err; - return -1; + free(ib); + if (!err) + err = EIO; + errno = err; + return -1; done: - icx->entry = ie; - icx->data = (u8 *)ie + offsetof(INDEX_ENTRY, key); - icx->data_len = le16_to_cpu(ie->key_length); - ntfs_log_trace("Done.\n"); - if (err) { - errno = err; - return -1; - } - return 0; + icx->entry = ie; + icx->data = (u8 *)ie + offsetof(INDEX_ENTRY, key); + icx->data_len = le16_to_cpu(ie->key_length); + ntfs_log_trace("Done.\n"); + if (err) { + errno = err; + return -1; + } + return 0; } -static INDEX_BLOCK *ntfs_ib_alloc(VCN ib_vcn, u32 ib_size, - INDEX_HEADER_FLAGS node_type) { - INDEX_BLOCK *ib; - int ih_size = sizeof(INDEX_HEADER); +static INDEX_BLOCK *ntfs_ib_alloc(VCN ib_vcn, u32 ib_size, + INDEX_HEADER_FLAGS node_type) +{ + INDEX_BLOCK *ib; + int ih_size = sizeof(INDEX_HEADER); + + ntfs_log_trace("ib_vcn: %lld ib_size: %u\n", (long long)ib_vcn, ib_size); + + ib = ntfs_calloc(ib_size); + if (!ib) + return NULL; + + ib->magic = magic_INDX; + ib->usa_ofs = cpu_to_le16(sizeof(INDEX_BLOCK)); + ib->usa_count = cpu_to_le16(ib_size / NTFS_BLOCK_SIZE + 1); + /* Set USN to 1 */ + *(u16 *)((char *)ib + le16_to_cpu(ib->usa_ofs)) = cpu_to_le16(1); + ib->lsn = cpu_to_le64(0); + + ib->index_block_vcn = cpu_to_sle64(ib_vcn); + + ib->index.entries_offset = cpu_to_le32((ih_size + + le16_to_cpu(ib->usa_count) * 2 + 7) & ~7); + ib->index.index_length = 0; + ib->index.allocated_size = cpu_to_le32(ib_size - + (sizeof(INDEX_BLOCK) - ih_size)); + ib->index.ih_flags = node_type; + + return ib; +} - ntfs_log_trace("ib_vcn: %lld ib_size: %u\n", (long long)ib_vcn, ib_size); - - ib = ntfs_calloc(ib_size); - if (!ib) - return NULL; - - ib->magic = magic_INDX; - ib->usa_ofs = cpu_to_le16(sizeof(INDEX_BLOCK)); - ib->usa_count = cpu_to_le16(ib_size / NTFS_BLOCK_SIZE + 1); - /* Set USN to 1 */ - *(u16 *)((char *)ib + le16_to_cpu(ib->usa_ofs)) = cpu_to_le16(1); - ib->lsn = cpu_to_le64(0); - - ib->index_block_vcn = cpu_to_sle64(ib_vcn); - - ib->index.entries_offset = cpu_to_le32((ih_size + - le16_to_cpu(ib->usa_count) * 2 + 7) & ~7); - ib->index.index_length = 0; - ib->index.allocated_size = cpu_to_le32(ib_size - - (sizeof(INDEX_BLOCK) - ih_size)); - ib->index.ih_flags = node_type; - - return ib; -} - -/** +/** * Find the median by going through all the entries */ -static INDEX_ENTRY *ntfs_ie_get_median(INDEX_HEADER *ih) { - INDEX_ENTRY *ie, *ie_start; - u8 *ie_end; - int i = 0, median; - - ntfs_log_trace("Entering\n"); - - ie = ie_start = ntfs_ie_get_first(ih); - ie_end = (u8 *)ntfs_ie_get_end(ih); - - while ((u8 *)ie < ie_end && !ntfs_ie_end(ie)) { - ie = ntfs_ie_get_next(ie); - i++; - } - /* - * NOTE: this could be also the entry at the half of the index block. - */ - median = i / 2 - 1; - - ntfs_log_trace("Entries: %d median: %d\n", i, median); - - for (i = 0, ie = ie_start; i <= median; i++) - ie = ntfs_ie_get_next(ie); - - return ie; +static INDEX_ENTRY *ntfs_ie_get_median(INDEX_HEADER *ih) +{ + INDEX_ENTRY *ie, *ie_start; + u8 *ie_end; + int i = 0, median; + + ntfs_log_trace("Entering\n"); + + ie = ie_start = ntfs_ie_get_first(ih); + ie_end = (u8 *)ntfs_ie_get_end(ih); + + while ((u8 *)ie < ie_end && !ntfs_ie_end(ie)) { + ie = ntfs_ie_get_next(ie); + i++; + } + /* + * NOTE: this could be also the entry at the half of the index block. + */ + median = i / 2 - 1; + + ntfs_log_trace("Entries: %d median: %d\n", i, median); + + for (i = 0, ie = ie_start; i <= median; i++) + ie = ntfs_ie_get_next(ie); + + return ie; } -static s64 ntfs_ibm_vcn_to_pos(ntfs_index_context *icx, VCN vcn) { - return ntfs_ib_vcn_to_pos(icx, vcn) / icx->block_size; +static s64 ntfs_ibm_vcn_to_pos(ntfs_index_context *icx, VCN vcn) +{ + return ntfs_ib_vcn_to_pos(icx, vcn) / icx->block_size; } -static s64 ntfs_ibm_pos_to_vcn(ntfs_index_context *icx, s64 pos) { - return ntfs_ib_pos_to_vcn(icx, pos * icx->block_size); +static s64 ntfs_ibm_pos_to_vcn(ntfs_index_context *icx, s64 pos) +{ + return ntfs_ib_pos_to_vcn(icx, pos * icx->block_size); } -static int ntfs_ibm_add(ntfs_index_context *icx) { - u8 bmp[8]; +static int ntfs_ibm_add(ntfs_index_context *icx) +{ + u8 bmp[8]; - ntfs_log_trace("Entering\n"); - - if (ntfs_attr_exist(icx->ni, AT_BITMAP, icx->name, icx->name_len)) - return STATUS_OK; - /* - * AT_BITMAP must be at least 8 bytes. - */ - memset(bmp, 0, sizeof(bmp)); - if (ntfs_attr_add(icx->ni, AT_BITMAP, icx->name, icx->name_len, - bmp, sizeof(bmp))) { - ntfs_log_perror("Failed to add AT_BITMAP"); - return STATUS_ERROR; - } - - return STATUS_OK; + ntfs_log_trace("Entering\n"); + + if (ntfs_attr_exist(icx->ni, AT_BITMAP, icx->name, icx->name_len)) + return STATUS_OK; + /* + * AT_BITMAP must be at least 8 bytes. + */ + memset(bmp, 0, sizeof(bmp)); + if (ntfs_attr_add(icx->ni, AT_BITMAP, icx->name, icx->name_len, + bmp, sizeof(bmp))) { + ntfs_log_perror("Failed to add AT_BITMAP"); + return STATUS_ERROR; + } + + return STATUS_OK; } -static int ntfs_ibm_modify(ntfs_index_context *icx, VCN vcn, int set) { - u8 byte; - s64 pos = ntfs_ibm_vcn_to_pos(icx, vcn); - u32 bpos = pos / 8; - u32 bit = 1 << (pos % 8); - ntfs_attr *na; - int ret = STATUS_ERROR; +static int ntfs_ibm_modify(ntfs_index_context *icx, VCN vcn, int set) +{ + u8 byte; + s64 pos = ntfs_ibm_vcn_to_pos(icx, vcn); + u32 bpos = pos / 8; + u32 bit = 1 << (pos % 8); + ntfs_attr *na; + int ret = STATUS_ERROR; - ntfs_log_trace("%s vcn: %lld\n", set ? "set" : "clear", (long long)vcn); + ntfs_log_trace("%s vcn: %lld\n", set ? "set" : "clear", (long long)vcn); + + na = ntfs_attr_open(icx->ni, AT_BITMAP, icx->name, icx->name_len); + if (!na) { + ntfs_log_perror("Failed to open $BITMAP attribute"); + return -1; + } - na = ntfs_attr_open(icx->ni, AT_BITMAP, icx->name, icx->name_len); - if (!na) { - ntfs_log_perror("Failed to open $BITMAP attribute"); - return -1; - } + if (set) { + if (na->data_size < bpos + 1) { + if (ntfs_attr_truncate(na, (na->data_size + 8) & ~7)) { + ntfs_log_perror("Failed to truncate AT_BITMAP"); + goto err_na; + } + } + } + + if (ntfs_attr_pread(na, bpos, 1, &byte) != 1) { + ntfs_log_perror("Failed to read $BITMAP"); + goto err_na; + } - if (set) { - if (na->data_size < bpos + 1) { - if (ntfs_attr_truncate(na, (na->data_size + 8) & ~7)) { - ntfs_log_perror("Failed to truncate AT_BITMAP"); - goto err_na; - } - } - } + if (set) + byte |= bit; + else + byte &= ~bit; + + if (ntfs_attr_pwrite(na, bpos, 1, &byte) != 1) { + ntfs_log_perror("Failed to write $Bitmap"); + goto err_na; + } - if (ntfs_attr_pread(na, bpos, 1, &byte) != 1) { - ntfs_log_perror("Failed to read $BITMAP"); - goto err_na; - } - - if (set) - byte |= bit; - else - byte &= ~bit; - - if (ntfs_attr_pwrite(na, bpos, 1, &byte) != 1) { - ntfs_log_perror("Failed to write $Bitmap"); - goto err_na; - } - - ret = STATUS_OK; + ret = STATUS_OK; err_na: - ntfs_attr_close(na); - return ret; + ntfs_attr_close(na); + return ret; } -static int ntfs_ibm_set(ntfs_index_context *icx, VCN vcn) { - return ntfs_ibm_modify(icx, vcn, 1); +static int ntfs_ibm_set(ntfs_index_context *icx, VCN vcn) +{ + return ntfs_ibm_modify(icx, vcn, 1); } -static int ntfs_ibm_clear(ntfs_index_context *icx, VCN vcn) { - return ntfs_ibm_modify(icx, vcn, 0); +static int ntfs_ibm_clear(ntfs_index_context *icx, VCN vcn) +{ + return ntfs_ibm_modify(icx, vcn, 0); } -static VCN ntfs_ibm_get_free(ntfs_index_context *icx) { - u8 *bm; - int bit; - s64 vcn, byte, size; +static VCN ntfs_ibm_get_free(ntfs_index_context *icx) +{ + u8 *bm; + int bit; + s64 vcn, byte, size; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); + + bm = ntfs_attr_readall(icx->ni, AT_BITMAP, icx->name, icx->name_len, + &size); + if (!bm) + return (VCN)-1; + + for (byte = 0; byte < size; byte++) { + + if (bm[byte] == 255) + continue; + + for (bit = 0; bit < 8; bit++) { + if (!(bm[byte] & (1 << bit))) { + vcn = ntfs_ibm_pos_to_vcn(icx, byte * 8 + bit); + goto out; + } + } + } + + vcn = ntfs_ibm_pos_to_vcn(icx, size * 8); +out: + ntfs_log_trace("allocated vcn: %lld\n", (long long)vcn); - bm = ntfs_attr_readall(icx->ni, AT_BITMAP, icx->name, icx->name_len, - &size); - if (!bm) - return (VCN)-1; - - for (byte = 0; byte < size; byte++) { - - if (bm[byte] == 255) - continue; - - for (bit = 0; bit < 8; bit++) { - if (!(bm[byte] & (1 << bit))) { - vcn = ntfs_ibm_pos_to_vcn(icx, byte * 8 + bit); - goto out; - } - } - } - - vcn = ntfs_ibm_pos_to_vcn(icx, size * 8); -out: - ntfs_log_trace("allocated vcn: %lld\n", (long long)vcn); - - if (ntfs_ibm_set(icx, vcn)) - vcn = (VCN)-1; - - free(bm); - return vcn; + if (ntfs_ibm_set(icx, vcn)) + vcn = (VCN)-1; + + free(bm); + return vcn; } -static INDEX_BLOCK *ntfs_ir_to_ib(INDEX_ROOT *ir, VCN ib_vcn) { - INDEX_BLOCK *ib; - INDEX_ENTRY *ie_last; - char *ies_start, *ies_end; - int i; - - ntfs_log_trace("Entering\n"); - - ib = ntfs_ib_alloc(ib_vcn, le32_to_cpu(ir->index_block_size), LEAF_NODE); - if (!ib) - return NULL; - - ies_start = (char *)ntfs_ie_get_first(&ir->index); - ies_end = (char *)ntfs_ie_get_end(&ir->index); - ie_last = ntfs_ie_get_last((INDEX_ENTRY *)ies_start, ies_end); - /* - * Copy all entries, including the termination entry - * as well, which can never have any data. - */ - i = (char *)ie_last - ies_start + le16_to_cpu(ie_last->length); - memcpy(ntfs_ie_get_first(&ib->index), ies_start, i); - - ib->index.ih_flags = ir->index.ih_flags; - ib->index.index_length = cpu_to_le32(i + - le32_to_cpu(ib->index.entries_offset)); - return ib; +static INDEX_BLOCK *ntfs_ir_to_ib(INDEX_ROOT *ir, VCN ib_vcn) +{ + INDEX_BLOCK *ib; + INDEX_ENTRY *ie_last; + char *ies_start, *ies_end; + int i; + + ntfs_log_trace("Entering\n"); + + ib = ntfs_ib_alloc(ib_vcn, le32_to_cpu(ir->index_block_size), LEAF_NODE); + if (!ib) + return NULL; + + ies_start = (char *)ntfs_ie_get_first(&ir->index); + ies_end = (char *)ntfs_ie_get_end(&ir->index); + ie_last = ntfs_ie_get_last((INDEX_ENTRY *)ies_start, ies_end); + /* + * Copy all entries, including the termination entry + * as well, which can never have any data. + */ + i = (char *)ie_last - ies_start + le16_to_cpu(ie_last->length); + memcpy(ntfs_ie_get_first(&ib->index), ies_start, i); + + ib->index.ih_flags = ir->index.ih_flags; + ib->index.index_length = cpu_to_le32(i + + le32_to_cpu(ib->index.entries_offset)); + return ib; } -static void ntfs_ir_nill(INDEX_ROOT *ir) { - INDEX_ENTRY *ie_last; - char *ies_start, *ies_end; - - ntfs_log_trace("Entering\n"); - /* - * TODO: This function could be much simpler. - */ - ies_start = (char *)ntfs_ie_get_first(&ir->index); - ies_end = (char *)ntfs_ie_get_end(&ir->index); - ie_last = ntfs_ie_get_last((INDEX_ENTRY *)ies_start, ies_end); - /* - * Move the index root termination entry forward - */ - if ((char *)ie_last > ies_start) { - memmove(ies_start, (char *)ie_last, le16_to_cpu(ie_last->length)); - ie_last = (INDEX_ENTRY *)ies_start; - } +static void ntfs_ir_nill(INDEX_ROOT *ir) +{ + INDEX_ENTRY *ie_last; + char *ies_start, *ies_end; + + ntfs_log_trace("Entering\n"); + /* + * TODO: This function could be much simpler. + */ + ies_start = (char *)ntfs_ie_get_first(&ir->index); + ies_end = (char *)ntfs_ie_get_end(&ir->index); + ie_last = ntfs_ie_get_last((INDEX_ENTRY *)ies_start, ies_end); + /* + * Move the index root termination entry forward + */ + if ((char *)ie_last > ies_start) { + memmove(ies_start, (char *)ie_last, le16_to_cpu(ie_last->length)); + ie_last = (INDEX_ENTRY *)ies_start; + } } static int ntfs_ib_copy_tail(ntfs_index_context *icx, INDEX_BLOCK *src, - INDEX_ENTRY *median, VCN new_vcn) { - u8 *ies_end; - INDEX_ENTRY *ie_head; /* first entry after the median */ - int tail_size, ret; - INDEX_BLOCK *dst; + INDEX_ENTRY *median, VCN new_vcn) +{ + u8 *ies_end; + INDEX_ENTRY *ie_head; /* first entry after the median */ + int tail_size, ret; + INDEX_BLOCK *dst; + + ntfs_log_trace("Entering\n"); + + dst = ntfs_ib_alloc(new_vcn, icx->block_size, + src->index.ih_flags & NODE_MASK); + if (!dst) + return STATUS_ERROR; + + ie_head = ntfs_ie_get_next(median); + + ies_end = (u8 *)ntfs_ie_get_end(&src->index); + tail_size = ies_end - (u8 *)ie_head; + memcpy(ntfs_ie_get_first(&dst->index), ie_head, tail_size); + + dst->index.index_length = cpu_to_le32(tail_size + + le32_to_cpu(dst->index.entries_offset)); + ret = ntfs_ib_write(icx, dst); - ntfs_log_trace("Entering\n"); - - dst = ntfs_ib_alloc(new_vcn, icx->block_size, - src->index.ih_flags & NODE_MASK); - if (!dst) - return STATUS_ERROR; - - ie_head = ntfs_ie_get_next(median); - - ies_end = (u8 *)ntfs_ie_get_end(&src->index); - tail_size = ies_end - (u8 *)ie_head; - memcpy(ntfs_ie_get_first(&dst->index), ie_head, tail_size); - - dst->index.index_length = cpu_to_le32(tail_size + - le32_to_cpu(dst->index.entries_offset)); - ret = ntfs_ib_write(icx, dst); - - free(dst); - return ret; + free(dst); + return ret; } static int ntfs_ib_cut_tail(ntfs_index_context *icx, INDEX_BLOCK *ib, - INDEX_ENTRY *ie) { - char *ies_start, *ies_end; - INDEX_ENTRY *ie_last; + INDEX_ENTRY *ie) +{ + char *ies_start, *ies_end; + INDEX_ENTRY *ie_last; + + ntfs_log_trace("Entering\n"); + + ies_start = (char *)ntfs_ie_get_first(&ib->index); + ies_end = (char *)ntfs_ie_get_end(&ib->index); + + ie_last = ntfs_ie_get_last((INDEX_ENTRY *)ies_start, ies_end); + if (ie_last->ie_flags & INDEX_ENTRY_NODE) + ntfs_ie_set_vcn(ie_last, ntfs_ie_get_vcn(ie)); + + memcpy(ie, ie_last, le16_to_cpu(ie_last->length)); + + ib->index.index_length = cpu_to_le32(((char *)ie - ies_start) + + le16_to_cpu(ie->length) + le32_to_cpu(ib->index.entries_offset)); + + if (ntfs_ib_write(icx, ib)) + return STATUS_ERROR; + + return STATUS_OK; +} + +static int ntfs_ia_add(ntfs_index_context *icx) +{ + ntfs_log_trace("Entering\n"); - ntfs_log_trace("Entering\n"); + if (ntfs_ibm_add(icx)) + return -1; + + if (!ntfs_attr_exist(icx->ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len)) { + + if (ntfs_attr_add(icx->ni, AT_INDEX_ALLOCATION, icx->name, + icx->name_len, NULL, 0)) { + ntfs_log_perror("Failed to add AT_INDEX_ALLOCATION"); + return -1; + } + } + + icx->ia_na = ntfs_ia_open(icx, icx->ni); + if (!icx->ia_na) + return -1; - ies_start = (char *)ntfs_ie_get_first(&ib->index); - ies_end = (char *)ntfs_ie_get_end(&ib->index); - - ie_last = ntfs_ie_get_last((INDEX_ENTRY *)ies_start, ies_end); - if (ie_last->ie_flags & INDEX_ENTRY_NODE) - ntfs_ie_set_vcn(ie_last, ntfs_ie_get_vcn(ie)); - - memcpy(ie, ie_last, le16_to_cpu(ie_last->length)); - - ib->index.index_length = cpu_to_le32(((char *)ie - ies_start) + - le16_to_cpu(ie->length) + le32_to_cpu(ib->index.entries_offset)); - - if (ntfs_ib_write(icx, ib)) - return STATUS_ERROR; - - return STATUS_OK; + return 0; } -static int ntfs_ia_add(ntfs_index_context *icx) { - ntfs_log_trace("Entering\n"); +static int ntfs_ir_reparent(ntfs_index_context *icx) +{ + ntfs_attr_search_ctx *ctx = NULL; + INDEX_ROOT *ir; + INDEX_ENTRY *ie; + INDEX_BLOCK *ib = NULL; + VCN new_ib_vcn; + int ret = STATUS_ERROR; - if (ntfs_ibm_add(icx)) - return -1; - - if (!ntfs_attr_exist(icx->ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len)) { - - if (ntfs_attr_add(icx->ni, AT_INDEX_ALLOCATION, icx->name, - icx->name_len, NULL, 0)) { - ntfs_log_perror("Failed to add AT_INDEX_ALLOCATION"); - return -1; - } - } - - icx->ia_na = ntfs_ia_open(icx, icx->ni); - if (!icx->ia_na) - return -1; - - return 0; -} - -static int ntfs_ir_reparent(ntfs_index_context *icx) { - ntfs_attr_search_ctx *ctx = NULL; - INDEX_ROOT *ir; - INDEX_ENTRY *ie; - INDEX_BLOCK *ib = NULL; - VCN new_ib_vcn; - int ret = STATUS_ERROR; - - ntfs_log_trace("Entering\n"); - - ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!ir) - goto out; - - if ((ir->index.ih_flags & NODE_MASK) == SMALL_INDEX) - if (ntfs_ia_add(icx)) - goto out; - - new_ib_vcn = ntfs_ibm_get_free(icx); - if (new_ib_vcn == -1) - goto out; - - ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!ir) - goto clear_bmp; - - ib = ntfs_ir_to_ib(ir, new_ib_vcn); - if (ib == NULL) { - ntfs_log_perror("Failed to move index root to index block"); - goto clear_bmp; - } - - if (ntfs_ib_write(icx, ib)) - goto clear_bmp; - - ir = ntfs_ir_lookup(icx->ni, icx->name, icx->name_len, &ctx); - if (!ir) - goto clear_bmp; - - ntfs_ir_nill(ir); - - ie = ntfs_ie_get_first(&ir->index); - ie->ie_flags |= INDEX_ENTRY_NODE; - ie->length = cpu_to_le16(sizeof(INDEX_ENTRY_HEADER) + sizeof(VCN)); - - ir->index.ih_flags = LARGE_INDEX; - ir->index.index_length = cpu_to_le32(le32_to_cpu(ir->index.entries_offset) - + le16_to_cpu(ie->length)); - ir->index.allocated_size = ir->index.index_length; - - if (ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, - sizeof(INDEX_ROOT) - sizeof(INDEX_HEADER) + - le32_to_cpu(ir->index.allocated_size))) - /* FIXME: revert index root */ - goto clear_bmp; - /* - * FIXME: do it earlier if we have enough space in IR (should always), - * so in error case we wouldn't lose the IB. - */ - ntfs_ie_set_vcn(ie, new_ib_vcn); - - ret = STATUS_OK; + ntfs_log_trace("Entering\n"); + + ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); + if (!ir) + goto out; + + if ((ir->index.ih_flags & NODE_MASK) == SMALL_INDEX) + if (ntfs_ia_add(icx)) + goto out; + + new_ib_vcn = ntfs_ibm_get_free(icx); + if (new_ib_vcn == -1) + goto out; + + ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); + if (!ir) + goto clear_bmp; + + ib = ntfs_ir_to_ib(ir, new_ib_vcn); + if (ib == NULL) { + ntfs_log_perror("Failed to move index root to index block"); + goto clear_bmp; + } + + if (ntfs_ib_write(icx, ib)) + goto clear_bmp; + + ir = ntfs_ir_lookup(icx->ni, icx->name, icx->name_len, &ctx); + if (!ir) + goto clear_bmp; + + ntfs_ir_nill(ir); + + ie = ntfs_ie_get_first(&ir->index); + ie->ie_flags |= INDEX_ENTRY_NODE; + ie->length = cpu_to_le16(sizeof(INDEX_ENTRY_HEADER) + sizeof(VCN)); + + ir->index.ih_flags = LARGE_INDEX; + ir->index.index_length = cpu_to_le32(le32_to_cpu(ir->index.entries_offset) + + le16_to_cpu(ie->length)); + ir->index.allocated_size = ir->index.index_length; + + if (ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, + sizeof(INDEX_ROOT) - sizeof(INDEX_HEADER) + + le32_to_cpu(ir->index.allocated_size))) + /* FIXME: revert index root */ + goto clear_bmp; + /* + * FIXME: do it earlier if we have enough space in IR (should always), + * so in error case we wouldn't lose the IB. + */ + ntfs_ie_set_vcn(ie, new_ib_vcn); + + ret = STATUS_OK; err_out: - free(ib); - ntfs_attr_put_search_ctx(ctx); + free(ib); + ntfs_attr_put_search_ctx(ctx); out: - return ret; + return ret; clear_bmp: - ntfs_ibm_clear(icx, new_ib_vcn); - goto err_out; + ntfs_ibm_clear(icx, new_ib_vcn); + goto err_out; } /** * ntfs_ir_truncate - Truncate index root attribute - * + * * Returns STATUS_OK, STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT or STATUS_ERROR. */ -static int ntfs_ir_truncate(ntfs_index_context *icx, int data_size) { - ntfs_attr *na; - int ret; +static int ntfs_ir_truncate(ntfs_index_context *icx, int data_size) +{ + ntfs_attr *na; + int ret; - ntfs_log_trace("Entering\n"); - - na = ntfs_attr_open(icx->ni, AT_INDEX_ROOT, icx->name, icx->name_len); - if (!na) { - ntfs_log_perror("Failed to open INDEX_ROOT"); - return STATUS_ERROR; - } - /* - * INDEX_ROOT must be resident and its entries can be moved to - * INDEX_BLOCK, so ENOSPC isn't a real error. - */ - ret = ntfs_attr_truncate(na, data_size + offsetof(INDEX_ROOT, index)); - if (ret == STATUS_OK) { - - icx->ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!icx->ir) - return STATUS_ERROR; - - icx->ir->index.allocated_size = cpu_to_le32(data_size); - - } else if (ret == STATUS_ERROR) - ntfs_log_perror("Failed to truncate INDEX_ROOT"); - - ntfs_attr_close(na); - return ret; + ntfs_log_trace("Entering\n"); + + na = ntfs_attr_open(icx->ni, AT_INDEX_ROOT, icx->name, icx->name_len); + if (!na) { + ntfs_log_perror("Failed to open INDEX_ROOT"); + return STATUS_ERROR; + } + /* + * INDEX_ROOT must be resident and its entries can be moved to + * INDEX_BLOCK, so ENOSPC isn't a real error. + */ + ret = ntfs_attr_truncate(na, data_size + offsetof(INDEX_ROOT, index)); + if (ret == STATUS_OK) { + + icx->ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); + if (!icx->ir) + return STATUS_ERROR; + + icx->ir->index.allocated_size = cpu_to_le32(data_size); + + } else if (ret == STATUS_ERROR) + ntfs_log_perror("Failed to truncate INDEX_ROOT"); + + ntfs_attr_close(na); + return ret; } - + /** * ntfs_ir_make_space - Make more space for the index root attribute - * + * * On success return STATUS_OK or STATUS_KEEP_SEARCHING. * On error return STATUS_ERROR. */ -static int ntfs_ir_make_space(ntfs_index_context *icx, int data_size) { - int ret; +static int ntfs_ir_make_space(ntfs_index_context *icx, int data_size) +{ + int ret; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); - ret = ntfs_ir_truncate(icx, data_size); - if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { + ret = ntfs_ir_truncate(icx, data_size); + if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { + + ret = ntfs_ir_reparent(icx); + if (ret == STATUS_OK) + ret = STATUS_KEEP_SEARCHING; + else + ntfs_log_perror("Failed to nodify INDEX_ROOT"); + } - ret = ntfs_ir_reparent(icx); - if (ret == STATUS_OK) - ret = STATUS_KEEP_SEARCHING; - else - ntfs_log_perror("Failed to nodify INDEX_ROOT"); - } - - return ret; + return ret; } /* * NOTE: 'ie' must be a copy of a real index entry. */ -static int ntfs_ie_add_vcn(INDEX_ENTRY **ie) { - INDEX_ENTRY *p, *old = *ie; +static int ntfs_ie_add_vcn(INDEX_ENTRY **ie) +{ + INDEX_ENTRY *p, *old = *ie; + + old->length = cpu_to_le16(le16_to_cpu(old->length) + sizeof(VCN)); + p = realloc(old, le16_to_cpu(old->length)); + if (!p) + return STATUS_ERROR; + + p->ie_flags |= INDEX_ENTRY_NODE; + *ie = p; - old->length = cpu_to_le16(le16_to_cpu(old->length) + sizeof(VCN)); - p = realloc(old, le16_to_cpu(old->length)); - if (!p) - return STATUS_ERROR; - - p->ie_flags |= INDEX_ENTRY_NODE; - *ie = p; - - return STATUS_OK; + return STATUS_OK; } -static int ntfs_ih_insert(INDEX_HEADER *ih, INDEX_ENTRY *orig_ie, VCN new_vcn, - int pos) { - INDEX_ENTRY *ie_node, *ie; - int ret = STATUS_ERROR; - VCN old_vcn; +static int ntfs_ih_insert(INDEX_HEADER *ih, INDEX_ENTRY *orig_ie, VCN new_vcn, + int pos) +{ + INDEX_ENTRY *ie_node, *ie; + int ret = STATUS_ERROR; + VCN old_vcn; + + ntfs_log_trace("Entering\n"); + + ie = ntfs_ie_dup(orig_ie); + if (!ie) + return STATUS_ERROR; + + if (!(ie->ie_flags & INDEX_ENTRY_NODE)) + if (ntfs_ie_add_vcn(&ie)) + goto out; - ntfs_log_trace("Entering\n"); - - ie = ntfs_ie_dup(orig_ie); - if (!ie) - return STATUS_ERROR; - - if (!(ie->ie_flags & INDEX_ENTRY_NODE)) - if (ntfs_ie_add_vcn(&ie)) - goto out; - - ie_node = ntfs_ie_get_by_pos(ih, pos); - old_vcn = ntfs_ie_get_vcn(ie_node); - ntfs_ie_set_vcn(ie_node, new_vcn); - - ntfs_ie_insert(ih, ie, ie_node); - ntfs_ie_set_vcn(ie_node, old_vcn); - ret = STATUS_OK; -out: - free(ie); - - return ret; + ie_node = ntfs_ie_get_by_pos(ih, pos); + old_vcn = ntfs_ie_get_vcn(ie_node); + ntfs_ie_set_vcn(ie_node, new_vcn); + + ntfs_ie_insert(ih, ie, ie_node); + ntfs_ie_set_vcn(ie_node, old_vcn); + ret = STATUS_OK; +out: + free(ie); + + return ret; } -static VCN ntfs_icx_parent_vcn(ntfs_index_context *icx) { - return icx->parent_vcn[icx->pindex]; +static VCN ntfs_icx_parent_vcn(ntfs_index_context *icx) +{ + return icx->parent_vcn[icx->pindex]; } -static VCN ntfs_icx_parent_pos(ntfs_index_context *icx) { - return icx->parent_pos[icx->pindex]; +static VCN ntfs_icx_parent_pos(ntfs_index_context *icx) +{ + return icx->parent_pos[icx->pindex]; } static int ntfs_ir_insert_median(ntfs_index_context *icx, INDEX_ENTRY *median, - VCN new_vcn) { - u32 new_size; - int ret; + VCN new_vcn) +{ + u32 new_size; + int ret; + + ntfs_log_trace("Entering\n"); + + icx->ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); + if (!icx->ir) + return STATUS_ERROR; - ntfs_log_trace("Entering\n"); + new_size = le32_to_cpu(icx->ir->index.index_length) + + le16_to_cpu(median->length); + if (!(median->ie_flags & INDEX_ENTRY_NODE)) + new_size += sizeof(VCN); - icx->ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!icx->ir) - return STATUS_ERROR; + ret = ntfs_ir_make_space(icx, new_size); + if (ret != STATUS_OK) + return ret; + + icx->ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); + if (!icx->ir) + return STATUS_ERROR; - new_size = le32_to_cpu(icx->ir->index.index_length) + - le16_to_cpu(median->length); - if (!(median->ie_flags & INDEX_ENTRY_NODE)) - new_size += sizeof(VCN); - - ret = ntfs_ir_make_space(icx, new_size); - if (ret != STATUS_OK) - return ret; - - icx->ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!icx->ir) - return STATUS_ERROR; - - return ntfs_ih_insert(&icx->ir->index, median, new_vcn, - ntfs_icx_parent_pos(icx)); + return ntfs_ih_insert(&icx->ir->index, median, new_vcn, + ntfs_icx_parent_pos(icx)); } static int ntfs_ib_split(ntfs_index_context *icx, INDEX_BLOCK *ib); @@ -1278,146 +1338,149 @@ static int ntfs_ib_split(ntfs_index_context *icx, INDEX_BLOCK *ib); * On success return STATUS_OK or STATUS_KEEP_SEARCHING. * On error return STATUS_ERROR. */ -static int ntfs_ib_insert(ntfs_index_context *icx, INDEX_ENTRY *ie, VCN new_vcn) { - INDEX_BLOCK *ib; - u32 idx_size, allocated_size; - int err = STATUS_ERROR; - VCN old_vcn; +static int ntfs_ib_insert(ntfs_index_context *icx, INDEX_ENTRY *ie, VCN new_vcn) +{ + INDEX_BLOCK *ib; + u32 idx_size, allocated_size; + int err = STATUS_ERROR; + VCN old_vcn; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); + + ib = ntfs_malloc(icx->block_size); + if (!ib) + return -1; + + old_vcn = ntfs_icx_parent_vcn(icx); + + if (ntfs_ib_read(icx, old_vcn, ib)) + goto err_out; - ib = ntfs_malloc(icx->block_size); - if (!ib) - return -1; - - old_vcn = ntfs_icx_parent_vcn(icx); - - if (ntfs_ib_read(icx, old_vcn, ib)) - goto err_out; - - idx_size = le32_to_cpu(ib->index.index_length); - allocated_size = le32_to_cpu(ib->index.allocated_size); - /* FIXME: sizeof(VCN) should be included only if ie has no VCN */ - if (idx_size + le16_to_cpu(ie->length) + sizeof(VCN) > allocated_size) { - err = ntfs_ib_split(icx, ib); - if (err == STATUS_OK) - err = STATUS_KEEP_SEARCHING; - goto err_out; - } - - if (ntfs_ih_insert(&ib->index, ie, new_vcn, ntfs_icx_parent_pos(icx))) - goto err_out; - - if (ntfs_ib_write(icx, ib)) - goto err_out; - - err = STATUS_OK; -err_out: - free(ib); - return err; + idx_size = le32_to_cpu(ib->index.index_length); + allocated_size = le32_to_cpu(ib->index.allocated_size); + /* FIXME: sizeof(VCN) should be included only if ie has no VCN */ + if (idx_size + le16_to_cpu(ie->length) + sizeof(VCN) > allocated_size) { + err = ntfs_ib_split(icx, ib); + if (err == STATUS_OK) + err = STATUS_KEEP_SEARCHING; + goto err_out; + } + + if (ntfs_ih_insert(&ib->index, ie, new_vcn, ntfs_icx_parent_pos(icx))) + goto err_out; + + if (ntfs_ib_write(icx, ib)) + goto err_out; + + err = STATUS_OK; +err_out: + free(ib); + return err; } /** * ntfs_ib_split - Split an index block - * + * * On success return STATUS_OK or STATUS_KEEP_SEARCHING. * On error return is STATUS_ERROR. */ -static int ntfs_ib_split(ntfs_index_context *icx, INDEX_BLOCK *ib) { - INDEX_ENTRY *median; - VCN new_vcn; - int ret; +static int ntfs_ib_split(ntfs_index_context *icx, INDEX_BLOCK *ib) +{ + INDEX_ENTRY *median; + VCN new_vcn; + int ret; - ntfs_log_trace("Entering\n"); - - if (ntfs_icx_parent_dec(icx)) - return STATUS_ERROR; - - median = ntfs_ie_get_median(&ib->index); - new_vcn = ntfs_ibm_get_free(icx); - if (new_vcn == -1) - return STATUS_ERROR; - - if (ntfs_ib_copy_tail(icx, ib, median, new_vcn)) { - ntfs_ibm_clear(icx, new_vcn); - return STATUS_ERROR; - } - - if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) - ret = ntfs_ir_insert_median(icx, median, new_vcn); - else - ret = ntfs_ib_insert(icx, median, new_vcn); - - if (ret != STATUS_OK) { - ntfs_ibm_clear(icx, new_vcn); - return ret; - } - - ret = ntfs_ib_cut_tail(icx, ib, median); - - return ret; + ntfs_log_trace("Entering\n"); + + if (ntfs_icx_parent_dec(icx)) + return STATUS_ERROR; + + median = ntfs_ie_get_median(&ib->index); + new_vcn = ntfs_ibm_get_free(icx); + if (new_vcn == -1) + return STATUS_ERROR; + + if (ntfs_ib_copy_tail(icx, ib, median, new_vcn)) { + ntfs_ibm_clear(icx, new_vcn); + return STATUS_ERROR; + } + + if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) + ret = ntfs_ir_insert_median(icx, median, new_vcn); + else + ret = ntfs_ib_insert(icx, median, new_vcn); + + if (ret != STATUS_OK) { + ntfs_ibm_clear(icx, new_vcn); + return ret; + } + + ret = ntfs_ib_cut_tail(icx, ib, median); + + return ret; } /* JPA static */ -int ntfs_ie_add(ntfs_index_context *icx, INDEX_ENTRY *ie) { - INDEX_HEADER *ih; - int allocated_size, new_size; - int ret = STATUS_ERROR; - +int ntfs_ie_add(ntfs_index_context *icx, INDEX_ENTRY *ie) +{ + INDEX_HEADER *ih; + int allocated_size, new_size; + int ret = STATUS_ERROR; + #ifdef DEBUG - /* removed by JPA to make function usable for security indexes - char *fn; - fn = ntfs_ie_filename_get(ie); - ntfs_log_trace("file: '%s'\n", fn); - ntfs_attr_name_free(&fn); - */ +/* removed by JPA to make function usable for security indexes + char *fn; + fn = ntfs_ie_filename_get(ie); + ntfs_log_trace("file: '%s'\n", fn); + ntfs_attr_name_free(&fn); +*/ #endif - - while (1) { - - if (!ntfs_index_lookup(&ie->key, le16_to_cpu(ie->key_length), icx)) { - errno = EEXIST; - ntfs_log_perror("Index already have such entry"); - goto err_out; - } - if (errno != ENOENT) { - ntfs_log_perror("Failed to find place for new entry"); - goto err_out; - } - - if (icx->is_in_root) - ih = &icx->ir->index; - else - ih = &icx->ib->index; - - allocated_size = le32_to_cpu(ih->allocated_size); - new_size = le32_to_cpu(ih->index_length) + le16_to_cpu(ie->length); - - if (new_size <= allocated_size) - break; - - ntfs_log_trace("index block sizes: allocated: %d needed: %d\n", - allocated_size, new_size); - - if (icx->is_in_root) { - if (ntfs_ir_make_space(icx, new_size) == STATUS_ERROR) - goto err_out; - } else { - if (ntfs_ib_split(icx, icx->ib) == STATUS_ERROR) - goto err_out; - } - - ntfs_inode_mark_dirty(icx->actx->ntfs_ino); - ntfs_index_ctx_reinit(icx); - } - - ntfs_ie_insert(ih, ie, icx->entry); - ntfs_index_entry_mark_dirty(icx); - - ret = STATUS_OK; + + while (1) { + + if (!ntfs_index_lookup(&ie->key, le16_to_cpu(ie->key_length), icx)) { + errno = EEXIST; + ntfs_log_perror("Index already have such entry"); + goto err_out; + } + if (errno != ENOENT) { + ntfs_log_perror("Failed to find place for new entry"); + goto err_out; + } + + if (icx->is_in_root) + ih = &icx->ir->index; + else + ih = &icx->ib->index; + + allocated_size = le32_to_cpu(ih->allocated_size); + new_size = le32_to_cpu(ih->index_length) + le16_to_cpu(ie->length); + + if (new_size <= allocated_size) + break; + + ntfs_log_trace("index block sizes: allocated: %d needed: %d\n", + allocated_size, new_size); + + if (icx->is_in_root) { + if (ntfs_ir_make_space(icx, new_size) == STATUS_ERROR) + goto err_out; + } else { + if (ntfs_ib_split(icx, icx->ib) == STATUS_ERROR) + goto err_out; + } + + ntfs_inode_mark_dirty(icx->actx->ntfs_ino); + ntfs_index_ctx_reinit(icx); + } + + ntfs_ie_insert(ih, ie, icx->entry); + ntfs_index_entry_mark_dirty(icx); + + ret = STATUS_OK; err_out: - ntfs_log_trace("%s\n", ret ? "Failed" : "Done"); - return ret; + ntfs_log_trace("%s\n", ret ? "Failed" : "Done"); + return ret; } /** @@ -1428,368 +1491,376 @@ err_out: * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_index_add_filename(ntfs_inode *ni, FILE_NAME_ATTR *fn, MFT_REF mref) { - INDEX_ENTRY *ie; - ntfs_index_context *icx; - int fn_size, ie_size, err, ret = -1; +int ntfs_index_add_filename(ntfs_inode *ni, FILE_NAME_ATTR *fn, MFT_REF mref) +{ + INDEX_ENTRY *ie; + ntfs_index_context *icx; + int fn_size, ie_size, err, ret = -1; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); + + if (!ni || !fn) { + ntfs_log_error("Invalid arguments.\n"); + errno = EINVAL; + return -1; + } + + fn_size = (fn->file_name_length * sizeof(ntfschar)) + + sizeof(FILE_NAME_ATTR); + ie_size = (sizeof(INDEX_ENTRY_HEADER) + fn_size + 7) & ~7; + + ie = ntfs_calloc(ie_size); + if (!ie) + return -1; - if (!ni || !fn) { - ntfs_log_error("Invalid arguments.\n"); - errno = EINVAL; - return -1; - } - - fn_size = (fn->file_name_length * sizeof(ntfschar)) + - sizeof(FILE_NAME_ATTR); - ie_size = (sizeof(INDEX_ENTRY_HEADER) + fn_size + 7) & ~7; - - ie = ntfs_calloc(ie_size); - if (!ie) - return -1; - - ie->indexed_file = cpu_to_le64(mref); - ie->length = cpu_to_le16(ie_size); - ie->key_length = cpu_to_le16(fn_size); - memcpy(&ie->key, fn, fn_size); - - icx = ntfs_index_ctx_get(ni, NTFS_INDEX_I30, 4); - if (!icx) - goto out; - - ret = ntfs_ie_add(icx, ie); - err = errno; - ntfs_index_ctx_put(icx); - errno = err; + ie->indexed_file = cpu_to_le64(mref); + ie->length = cpu_to_le16(ie_size); + ie->key_length = cpu_to_le16(fn_size); + memcpy(&ie->key, fn, fn_size); + + icx = ntfs_index_ctx_get(ni, NTFS_INDEX_I30, 4); + if (!icx) + goto out; + + ret = ntfs_ie_add(icx, ie); + err = errno; + ntfs_index_ctx_put(icx); + errno = err; out: - free(ie); - return ret; + free(ie); + return ret; } static int ntfs_ih_takeout(ntfs_index_context *icx, INDEX_HEADER *ih, - INDEX_ENTRY *ie, INDEX_BLOCK *ib) { - INDEX_ENTRY *ie_roam; - int ret = STATUS_ERROR; + INDEX_ENTRY *ie, INDEX_BLOCK *ib) +{ + INDEX_ENTRY *ie_roam; + int ret = STATUS_ERROR; + + ntfs_log_trace("Entering\n"); + + ie_roam = ntfs_ie_dup_novcn(ie); + if (!ie_roam) + return STATUS_ERROR; - ntfs_log_trace("Entering\n"); + ntfs_ie_delete(ih, ie); - ie_roam = ntfs_ie_dup_novcn(ie); - if (!ie_roam) - return STATUS_ERROR; + if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) + ntfs_inode_mark_dirty(icx->actx->ntfs_ino); + else + if (ntfs_ib_write(icx, ib)) + goto out; + + ntfs_index_ctx_reinit(icx); - ntfs_ie_delete(ih, ie); - - if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) - ntfs_inode_mark_dirty(icx->actx->ntfs_ino); - else - if (ntfs_ib_write(icx, ib)) - goto out; - - ntfs_index_ctx_reinit(icx); - - ret = ntfs_ie_add(icx, ie_roam); + ret = ntfs_ie_add(icx, ie_roam); out: - free(ie_roam); - return ret; + free(ie_roam); + return ret; } /** * Used if an empty index block to be deleted has END entry as the parent * in the INDEX_ROOT which is the only one there. */ -static void ntfs_ir_leafify(ntfs_index_context *icx, INDEX_HEADER *ih) { - INDEX_ENTRY *ie; - - ntfs_log_trace("Entering\n"); - - ie = ntfs_ie_get_first(ih); - ie->ie_flags &= ~INDEX_ENTRY_NODE; - ie->length = cpu_to_le16(le16_to_cpu(ie->length) - sizeof(VCN)); - - ih->index_length = cpu_to_le32(le32_to_cpu(ih->index_length) - sizeof(VCN)); - ih->ih_flags &= ~LARGE_INDEX; - - /* Not fatal error */ - ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length)); +static void ntfs_ir_leafify(ntfs_index_context *icx, INDEX_HEADER *ih) +{ + INDEX_ENTRY *ie; + + ntfs_log_trace("Entering\n"); + + ie = ntfs_ie_get_first(ih); + ie->ie_flags &= ~INDEX_ENTRY_NODE; + ie->length = cpu_to_le16(le16_to_cpu(ie->length) - sizeof(VCN)); + + ih->index_length = cpu_to_le32(le32_to_cpu(ih->index_length) - sizeof(VCN)); + ih->ih_flags &= ~LARGE_INDEX; + + /* Not fatal error */ + ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length)); } /** - * Used if an empty index block to be deleted has END entry as the parent + * Used if an empty index block to be deleted has END entry as the parent * in the INDEX_ROOT which is not the only one there. */ static int ntfs_ih_reparent_end(ntfs_index_context *icx, INDEX_HEADER *ih, - INDEX_BLOCK *ib) { - INDEX_ENTRY *ie, *ie_prev; - - ntfs_log_trace("Entering\n"); - - ie = ntfs_ie_get_by_pos(ih, ntfs_icx_parent_pos(icx)); - ie_prev = ntfs_ie_prev(ih, ie); - - ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(ie_prev)); - - return ntfs_ih_takeout(icx, ih, ie_prev, ib); + INDEX_BLOCK *ib) +{ + INDEX_ENTRY *ie, *ie_prev; + + ntfs_log_trace("Entering\n"); + + ie = ntfs_ie_get_by_pos(ih, ntfs_icx_parent_pos(icx)); + ie_prev = ntfs_ie_prev(ih, ie); + + ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(ie_prev)); + + return ntfs_ih_takeout(icx, ih, ie_prev, ib); } -static int ntfs_index_rm_leaf(ntfs_index_context *icx) { - INDEX_BLOCK *ib = NULL; - INDEX_HEADER *parent_ih; - INDEX_ENTRY *ie; - int ret = STATUS_ERROR; +static int ntfs_index_rm_leaf(ntfs_index_context *icx) +{ + INDEX_BLOCK *ib = NULL; + INDEX_HEADER *parent_ih; + INDEX_ENTRY *ie; + int ret = STATUS_ERROR; + + ntfs_log_trace("pindex: %d\n", icx->pindex); + + if (ntfs_icx_parent_dec(icx)) + return STATUS_ERROR; - ntfs_log_trace("pindex: %d\n", icx->pindex); - - if (ntfs_icx_parent_dec(icx)) - return STATUS_ERROR; - - if (ntfs_ibm_clear(icx, icx->parent_vcn[icx->pindex + 1])) - return STATUS_ERROR; - - if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) - parent_ih = &icx->ir->index; - else { - ib = ntfs_malloc(icx->block_size); - if (!ib) - return STATUS_ERROR; - - if (ntfs_ib_read(icx, ntfs_icx_parent_vcn(icx), ib)) - goto out; - - parent_ih = &ib->index; - } - - ie = ntfs_ie_get_by_pos(parent_ih, ntfs_icx_parent_pos(icx)); - if (!ntfs_ie_end(ie)) { - ret = ntfs_ih_takeout(icx, parent_ih, ie, ib); - goto out; - } - - if (ntfs_ih_zero_entry(parent_ih)) { - - if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) { - ntfs_ir_leafify(icx, parent_ih); - goto ok; - } - - ret = ntfs_index_rm_leaf(icx); - goto out; - } - - if (ntfs_ih_reparent_end(icx, parent_ih, ib)) - goto out; -ok: - ret = STATUS_OK; + if (ntfs_ibm_clear(icx, icx->parent_vcn[icx->pindex + 1])) + return STATUS_ERROR; + + if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) + parent_ih = &icx->ir->index; + else { + ib = ntfs_malloc(icx->block_size); + if (!ib) + return STATUS_ERROR; + + if (ntfs_ib_read(icx, ntfs_icx_parent_vcn(icx), ib)) + goto out; + + parent_ih = &ib->index; + } + + ie = ntfs_ie_get_by_pos(parent_ih, ntfs_icx_parent_pos(icx)); + if (!ntfs_ie_end(ie)) { + ret = ntfs_ih_takeout(icx, parent_ih, ie, ib); + goto out; + } + + if (ntfs_ih_zero_entry(parent_ih)) { + + if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) { + ntfs_ir_leafify(icx, parent_ih); + goto ok; + } + + ret = ntfs_index_rm_leaf(icx); + goto out; + } + + if (ntfs_ih_reparent_end(icx, parent_ih, ib)) + goto out; +ok: + ret = STATUS_OK; out: - free(ib); - return ret; + free(ib); + return ret; } -static int ntfs_index_rm_node(ntfs_index_context *icx) { - int entry_pos, pindex; - VCN vcn; - INDEX_BLOCK *ib = NULL; - INDEX_ENTRY *ie_succ, *ie, *entry = icx->entry; - INDEX_HEADER *ih; - u32 new_size; - int delta, ret = STATUS_ERROR; +static int ntfs_index_rm_node(ntfs_index_context *icx) +{ + int entry_pos, pindex; + VCN vcn; + INDEX_BLOCK *ib = NULL; + INDEX_ENTRY *ie_succ, *ie, *entry = icx->entry; + INDEX_HEADER *ih; + u32 new_size; + int delta, ret = STATUS_ERROR; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); + + if (!icx->ia_na) { + icx->ia_na = ntfs_ia_open(icx, icx->ni); + if (!icx->ia_na) + return STATUS_ERROR; + } - if (!icx->ia_na) { - icx->ia_na = ntfs_ia_open(icx, icx->ni); - if (!icx->ia_na) - return STATUS_ERROR; - } - - ib = ntfs_malloc(icx->block_size); - if (!ib) - return STATUS_ERROR; - - ie_succ = ntfs_ie_get_next(icx->entry); - entry_pos = icx->parent_pos[icx->pindex]++; - pindex = icx->pindex; + ib = ntfs_malloc(icx->block_size); + if (!ib) + return STATUS_ERROR; + + ie_succ = ntfs_ie_get_next(icx->entry); + entry_pos = icx->parent_pos[icx->pindex]++; + pindex = icx->pindex; descend: - vcn = ntfs_ie_get_vcn(ie_succ); - if (ntfs_ib_read(icx, vcn, ib)) - goto out; + vcn = ntfs_ie_get_vcn(ie_succ); + if (ntfs_ib_read(icx, vcn, ib)) + goto out; + + ie_succ = ntfs_ie_get_first(&ib->index); - ie_succ = ntfs_ie_get_first(&ib->index); + if (ntfs_icx_parent_inc(icx)) + goto out; + + icx->parent_vcn[icx->pindex] = vcn; + icx->parent_pos[icx->pindex] = 0; - if (ntfs_icx_parent_inc(icx)) - goto out; + if ((ib->index.ih_flags & NODE_MASK) == INDEX_NODE) + goto descend; - icx->parent_vcn[icx->pindex] = vcn; - icx->parent_pos[icx->pindex] = 0; + if (ntfs_ih_zero_entry(&ib->index)) { + errno = EIO; + ntfs_log_perror("Empty index block"); + goto out; + } - if ((ib->index.ih_flags & NODE_MASK) == INDEX_NODE) - goto descend; + ie = ntfs_ie_dup(ie_succ); + if (!ie) + goto out; + + if (ntfs_ie_add_vcn(&ie)) + goto out2; - if (ntfs_ih_zero_entry(&ib->index)) { - errno = EIO; - ntfs_log_perror("Empty index block"); - goto out; - } + ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(icx->entry)); - ie = ntfs_ie_dup(ie_succ); - if (!ie) - goto out; + if (icx->is_in_root) + ih = &icx->ir->index; + else + ih = &icx->ib->index; - if (ntfs_ie_add_vcn(&ie)) - goto out2; + delta = le16_to_cpu(ie->length) - le16_to_cpu(icx->entry->length); + new_size = le32_to_cpu(ih->index_length) + delta; + if (delta > 0) { + if (icx->is_in_root) { + ret = ntfs_ir_make_space(icx, new_size); + if (ret != STATUS_OK) + goto out2; + + ih = &icx->ir->index; + entry = ntfs_ie_get_by_pos(ih, entry_pos); + + } else if (new_size > le32_to_cpu(ih->allocated_size)) { + icx->pindex = pindex; + ret = ntfs_ib_split(icx, icx->ib); + if (ret == STATUS_OK) + ret = STATUS_KEEP_SEARCHING; + goto out2; + } + } - ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(icx->entry)); + ntfs_ie_delete(ih, entry); + ntfs_ie_insert(ih, ie, entry); + + if (icx->is_in_root) { + if (ntfs_ir_truncate(icx, new_size)) + goto out2; + } else + if (ntfs_icx_ib_write(icx)) + goto out2; + + ntfs_ie_delete(&ib->index, ie_succ); + + if (ntfs_ih_zero_entry(&ib->index)) { + if (ntfs_index_rm_leaf(icx)) + goto out2; + } else + if (ntfs_ib_write(icx, ib)) + goto out2; - if (icx->is_in_root) - ih = &icx->ir->index; - else - ih = &icx->ib->index; - - delta = le16_to_cpu(ie->length) - le16_to_cpu(icx->entry->length); - new_size = le32_to_cpu(ih->index_length) + delta; - if (delta > 0) { - if (icx->is_in_root) { - ret = ntfs_ir_make_space(icx, new_size); - if (ret != STATUS_OK) - goto out2; - - ih = &icx->ir->index; - entry = ntfs_ie_get_by_pos(ih, entry_pos); - - } else if (new_size > le32_to_cpu(ih->allocated_size)) { - icx->pindex = pindex; - ret = ntfs_ib_split(icx, icx->ib); - if (ret == STATUS_OK) - ret = STATUS_KEEP_SEARCHING; - goto out2; - } - } - - ntfs_ie_delete(ih, entry); - ntfs_ie_insert(ih, ie, entry); - - if (icx->is_in_root) { - if (ntfs_ir_truncate(icx, new_size)) - goto out2; - } else - if (ntfs_icx_ib_write(icx)) - goto out2; - - ntfs_ie_delete(&ib->index, ie_succ); - - if (ntfs_ih_zero_entry(&ib->index)) { - if (ntfs_index_rm_leaf(icx)) - goto out2; - } else - if (ntfs_ib_write(icx, ib)) - goto out2; - - ret = STATUS_OK; + ret = STATUS_OK; out2: - free(ie); + free(ie); out: - free(ib); - return ret; + free(ib); + return ret; } /** * ntfs_index_rm - remove entry from the index * @icx: index context describing entry to delete * - * Delete entry described by @icx from the index. Index context is always - * reinitialized after use of this function, so it can be used for index + * Delete entry described by @icx from the index. Index context is always + * reinitialized after use of this function, so it can be used for index * lookup once again. * * Return 0 on success or -1 on error with errno set to the error code. */ /*static JPA*/ -int ntfs_index_rm(ntfs_index_context *icx) { - INDEX_HEADER *ih; - int err, ret = STATUS_OK; +int ntfs_index_rm(ntfs_index_context *icx) +{ + INDEX_HEADER *ih; + int err, ret = STATUS_OK; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); + + if (!icx || (!icx->ib && !icx->ir) || ntfs_ie_end(icx->entry)) { + ntfs_log_error("Invalid arguments.\n"); + errno = EINVAL; + goto err_out; + } + if (icx->is_in_root) + ih = &icx->ir->index; + else + ih = &icx->ib->index; + + if (icx->entry->ie_flags & INDEX_ENTRY_NODE) { + + ret = ntfs_index_rm_node(icx); - if (!icx || (!icx->ib && !icx->ir) || ntfs_ie_end(icx->entry)) { - ntfs_log_error("Invalid arguments.\n"); - errno = EINVAL; - goto err_out; - } - if (icx->is_in_root) - ih = &icx->ir->index; - else - ih = &icx->ib->index; - - if (icx->entry->ie_flags & INDEX_ENTRY_NODE) { - - ret = ntfs_index_rm_node(icx); - - } else if (icx->is_in_root || !ntfs_ih_one_entry(ih)) { - - ntfs_ie_delete(ih, icx->entry); - - if (icx->is_in_root) { - err = ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length)); - if (err != STATUS_OK) - goto err_out; - } else - if (ntfs_icx_ib_write(icx)) - goto err_out; - } else { - if (ntfs_index_rm_leaf(icx)) - goto err_out; - } + } else if (icx->is_in_root || !ntfs_ih_one_entry(ih)) { + + ntfs_ie_delete(ih, icx->entry); + + if (icx->is_in_root) { + err = ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length)); + if (err != STATUS_OK) + goto err_out; + } else + if (ntfs_icx_ib_write(icx)) + goto err_out; + } else { + if (ntfs_index_rm_leaf(icx)) + goto err_out; + } out: - return ret; + return ret; err_out: - ret = STATUS_ERROR; - goto out; + ret = STATUS_ERROR; + goto out; } int ntfs_index_remove(ntfs_inode *dir_ni, ntfs_inode *ni, - const void *key, const int keylen) { - int ret = STATUS_ERROR; - ntfs_index_context *icx; + const void *key, const int keylen) +{ + int ret = STATUS_ERROR; + ntfs_index_context *icx; - icx = ntfs_index_ctx_get(dir_ni, NTFS_INDEX_I30, 4); - if (!icx) - return -1; + icx = ntfs_index_ctx_get(dir_ni, NTFS_INDEX_I30, 4); + if (!icx) + return -1; - while (1) { + while (1) { + + if (ntfs_index_lookup(key, keylen, icx)) + goto err_out; - if (ntfs_index_lookup(key, keylen, icx)) - goto err_out; + if ((((FILE_NAME_ATTR *)icx->data)->file_attributes & + FILE_ATTR_REPARSE_POINT) + && !ntfs_possible_symlink(ni)) { + errno = EOPNOTSUPP; + goto err_out; + } - if ((((FILE_NAME_ATTR *)icx->data)->file_attributes & - FILE_ATTR_REPARSE_POINT) - && !ntfs_possible_symlink(ni)) { - errno = EOPNOTSUPP; - goto err_out; - } + ret = ntfs_index_rm(icx); + if (ret == STATUS_ERROR) + goto err_out; + else if (ret == STATUS_OK) + break; + + ntfs_inode_mark_dirty(icx->actx->ntfs_ino); + ntfs_index_ctx_reinit(icx); + } - ret = ntfs_index_rm(icx); - if (ret == STATUS_ERROR) - goto err_out; - else if (ret == STATUS_OK) - break; - - ntfs_inode_mark_dirty(icx->actx->ntfs_ino); - ntfs_index_ctx_reinit(icx); - } - - ntfs_inode_mark_dirty(icx->actx->ntfs_ino); -out: - ntfs_index_ctx_put(icx); - return ret; + ntfs_inode_mark_dirty(icx->actx->ntfs_ino); +out: + ntfs_index_ctx_put(icx); + return ret; err_out: - ret = STATUS_ERROR; - ntfs_log_perror("Delete failed"); - goto out; + ret = STATUS_ERROR; + ntfs_log_perror("Delete failed"); + goto out; } /** * ntfs_index_root_get - read the index root of an attribute * @ni: open ntfs inode in which the ntfs attribute resides - * @attr: attribute for which we want its index root + * @attr: attribute for which we want its index root * * This function will read the related index root an ntfs attribute. * @@ -1798,25 +1869,26 @@ err_out: * * On error NULL is returned with errno set to the error code. */ -INDEX_ROOT *ntfs_index_root_get(ntfs_inode *ni, ATTR_RECORD *attr) { - ntfs_attr_search_ctx *ctx; - ntfschar *name; - INDEX_ROOT *root = NULL; +INDEX_ROOT *ntfs_index_root_get(ntfs_inode *ni, ATTR_RECORD *attr) +{ + ntfs_attr_search_ctx *ctx; + ntfschar *name; + INDEX_ROOT *root = NULL; - name = (ntfschar *)((u8 *)attr + le16_to_cpu(attr->name_offset)); + name = (ntfschar *)((u8 *)attr + le16_to_cpu(attr->name_offset)); - if (!ntfs_ir_lookup(ni, name, attr->name_length, &ctx)) - return NULL; - - root = ntfs_malloc(sizeof(INDEX_ROOT)); - if (!root) - goto out; - - *root = *((INDEX_ROOT *)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset))); -out: - ntfs_attr_put_search_ctx(ctx); - return root; + if (!ntfs_ir_lookup(ni, name, attr->name_length, &ctx)) + return NULL; + + root = ntfs_malloc(sizeof(INDEX_ROOT)); + if (!root) + goto out; + + *root = *((INDEX_ROOT *)((u8 *)ctx->attr + + le16_to_cpu(ctx->attr->value_offset))); +out: + ntfs_attr_put_search_ctx(ctx); + return root; } @@ -1827,36 +1899,37 @@ out: */ static INDEX_ENTRY *ntfs_index_walk_down(INDEX_ENTRY *ie, - ntfs_index_context *ictx) { - INDEX_ENTRY *entry; - s64 vcn; + ntfs_index_context *ictx) +{ + INDEX_ENTRY *entry; + s64 vcn; - entry = ie; - do { - vcn = ntfs_ie_get_vcn(entry); - if (ictx->is_in_root) { + entry = ie; + do { + vcn = ntfs_ie_get_vcn(entry); + if (ictx->is_in_root) { - /* down from level zero */ + /* down from level zero */ - ictx->ir = (INDEX_ROOT*)NULL; - ictx->ib = (INDEX_BLOCK*)ntfs_malloc(ictx->block_size); - ictx->pindex = 1; - ictx->is_in_root = FALSE; - } else { + ictx->ir = (INDEX_ROOT*)NULL; + ictx->ib = (INDEX_BLOCK*)ntfs_malloc(ictx->block_size); + ictx->pindex = 1; + ictx->is_in_root = FALSE; + } else { - /* down from non-zero level */ - - ictx->pindex++; - } - ictx->parent_pos[ictx->pindex] = 0; - ictx->parent_vcn[ictx->pindex] = vcn; - if (!ntfs_ib_read(ictx,vcn,ictx->ib)) { - ictx->entry = ntfs_ie_get_first(&ictx->ib->index); - entry = ictx->entry; - } else - entry = (INDEX_ENTRY*)NULL; - } while (entry && (entry->ie_flags & INDEX_ENTRY_NODE)); - return (entry); + /* down from non-zero level */ + + ictx->pindex++; + } + ictx->parent_pos[ictx->pindex] = 0; + ictx->parent_vcn[ictx->pindex] = vcn; + if (!ntfs_ib_read(ictx,vcn,ictx->ib)) { + ictx->entry = ntfs_ie_get_first(&ictx->ib->index); + entry = ictx->entry; + } else + entry = (INDEX_ENTRY*)NULL; + } while (entry && (entry->ie_flags & INDEX_ENTRY_NODE)); + return (entry); } /* @@ -1866,49 +1939,50 @@ static INDEX_ENTRY *ntfs_index_walk_down(INDEX_ENTRY *ie, */ static INDEX_ENTRY *ntfs_index_walk_up(INDEX_ENTRY *ie, - ntfs_index_context *ictx) { - INDEX_ENTRY *entry; - s64 vcn; + ntfs_index_context *ictx) +{ + INDEX_ENTRY *entry; + s64 vcn; - entry = ie; - if (ictx->pindex > 0) { - do { - ictx->pindex--; - if (!ictx->pindex) { + entry = ie; + if (ictx->pindex > 0) { + do { + ictx->pindex--; + if (!ictx->pindex) { - /* we have reached the root */ + /* we have reached the root */ - free(ictx->ib); - ictx->ib = (INDEX_BLOCK*)NULL; - ictx->is_in_root = TRUE; - /* a new search context is to be allocated */ - if (ictx->actx) - free(ictx->actx); - ictx->ir = ntfs_ir_lookup(ictx->ni, - ictx->name, ictx->name_len, - &ictx->actx); - if (ictx->ir) - entry = ntfs_ie_get_by_pos( - &ictx->ir->index, - ictx->parent_pos[ictx->pindex]); - else - entry = (INDEX_ENTRY*)NULL; - } else { - /* up into non-root node */ - vcn = ictx->parent_vcn[ictx->pindex]; - if (!ntfs_ib_read(ictx,vcn,ictx->ib)) { - entry = ntfs_ie_get_by_pos( - &ictx->ib->index, - ictx->parent_pos[ictx->pindex]); - } else - entry = (INDEX_ENTRY*)NULL; - } - ictx->entry = entry; - } while (entry && (ictx->pindex > 0) - && (entry->ie_flags & INDEX_ENTRY_END)); - } else - entry = (INDEX_ENTRY*)NULL; - return (entry); + free(ictx->ib); + ictx->ib = (INDEX_BLOCK*)NULL; + ictx->is_in_root = TRUE; + /* a new search context is to be allocated */ + if (ictx->actx) + free(ictx->actx); + ictx->ir = ntfs_ir_lookup(ictx->ni, + ictx->name, ictx->name_len, + &ictx->actx); + if (ictx->ir) + entry = ntfs_ie_get_by_pos( + &ictx->ir->index, + ictx->parent_pos[ictx->pindex]); + else + entry = (INDEX_ENTRY*)NULL; + } else { + /* up into non-root node */ + vcn = ictx->parent_vcn[ictx->pindex]; + if (!ntfs_ib_read(ictx,vcn,ictx->ib)) { + entry = ntfs_ie_get_by_pos( + &ictx->ib->index, + ictx->parent_pos[ictx->pindex]); + } else + entry = (INDEX_ENTRY*)NULL; + } + ictx->entry = entry; + } while (entry && (ictx->pindex > 0) + && (entry->ie_flags & INDEX_ENTRY_END)); + } else + entry = (INDEX_ENTRY*)NULL; + return (entry); } /* @@ -1938,46 +2012,47 @@ static INDEX_ENTRY *ntfs_index_walk_up(INDEX_ENTRY *ie, * +---+---+---+---+---+---+---+---+ */ -INDEX_ENTRY *ntfs_index_next(INDEX_ENTRY *ie, ntfs_index_context *ictx) { - INDEX_ENTRY *next; - int flags; +INDEX_ENTRY *ntfs_index_next(INDEX_ENTRY *ie, ntfs_index_context *ictx) +{ + INDEX_ENTRY *next; + int flags; - /* - * lookup() may have returned an invalid node - * when searching for a partial key - * if this happens, walk up - */ + /* + * lookup() may have returned an invalid node + * when searching for a partial key + * if this happens, walk up + */ - if (ie->ie_flags & INDEX_ENTRY_END) - next = ntfs_index_walk_up(ie, ictx); - else { - /* - * get next entry in same node - * there is always one after any entry with data - */ + if (ie->ie_flags & INDEX_ENTRY_END) + next = ntfs_index_walk_up(ie, ictx); + else { + /* + * get next entry in same node + * there is always one after any entry with data + */ - next = (INDEX_ENTRY*)((char*)ie + le16_to_cpu(ie->length)); - ++ictx->parent_pos[ictx->pindex]; - flags = next->ie_flags; + next = (INDEX_ENTRY*)((char*)ie + le16_to_cpu(ie->length)); + ++ictx->parent_pos[ictx->pindex]; + flags = next->ie_flags; - /* walk down if it has a subnode */ + /* walk down if it has a subnode */ - if (flags & INDEX_ENTRY_NODE) { - next = ntfs_index_walk_down(next,ictx); - } else { + if (flags & INDEX_ENTRY_NODE) { + next = ntfs_index_walk_down(next,ictx); + } else { - /* walk up it has no subnode, nor data */ + /* walk up it has no subnode, nor data */ - if (flags & INDEX_ENTRY_END) { - next = ntfs_index_walk_up(next, ictx); - } - } - } - /* return NULL if stuck at end of a block */ + if (flags & INDEX_ENTRY_END) { + next = ntfs_index_walk_up(next, ictx); + } + } + } + /* return NULL if stuck at end of a block */ - if (next && (next->ie_flags & INDEX_ENTRY_END)) - next = (INDEX_ENTRY*)NULL; - return (next); + if (next && (next->ie_flags & INDEX_ENTRY_END)) + next = (INDEX_ENTRY*)NULL; + return (next); } diff --git a/source/libntfs/index.h b/source/libntfs/index.h index 58ea5dbd..75e7b106 100644 --- a/source/libntfs/index.h +++ b/source/libntfs/index.h @@ -31,7 +31,7 @@ * ... code requiring gcc 2.8 or later ... * #endif * Note - they won't work for gcc1 or glibc1, since the _MINOR macros - * were not defined then. + * were not defined then. */ #ifndef __GNUC_PREREQ @@ -110,41 +110,41 @@ * to disk. */ typedef struct { - ntfs_inode *ni; - ntfschar *name; - u32 name_len; - INDEX_ENTRY *entry; - void *data; - u16 data_len; - COLLATION_RULES cr; - BOOL is_in_root; - INDEX_ROOT *ir; - ntfs_attr_search_ctx *actx; - INDEX_BLOCK *ib; - ntfs_attr *ia_na; - int parent_pos[MAX_PARENT_VCN]; /* parent entries' positions */ - VCN parent_vcn[MAX_PARENT_VCN]; /* entry's parent nodes */ - int pindex; /* maximum it's the number of the parent nodes */ - BOOL ib_dirty; - u32 block_size; - u8 vcn_size_bits; + ntfs_inode *ni; + ntfschar *name; + u32 name_len; + INDEX_ENTRY *entry; + void *data; + u16 data_len; + COLLATION_RULES cr; + BOOL is_in_root; + INDEX_ROOT *ir; + ntfs_attr_search_ctx *actx; + INDEX_BLOCK *ib; + ntfs_attr *ia_na; + int parent_pos[MAX_PARENT_VCN]; /* parent entries' positions */ + VCN parent_vcn[MAX_PARENT_VCN]; /* entry's parent nodes */ + int pindex; /* maximum it's the number of the parent nodes */ + BOOL ib_dirty; + u32 block_size; + u8 vcn_size_bits; } ntfs_index_context; extern ntfs_index_context *ntfs_index_ctx_get(ntfs_inode *ni, - ntfschar *name, u32 name_len); + ntfschar *name, u32 name_len); extern void ntfs_index_ctx_put(ntfs_index_context *ictx); extern void ntfs_index_ctx_reinit(ntfs_index_context *ictx); extern int ntfs_index_lookup(const void *key, const int key_len, - ntfs_index_context *ictx) __attribute_warn_unused_result__; + ntfs_index_context *ictx) __attribute_warn_unused_result__; extern INDEX_ENTRY *ntfs_index_next(INDEX_ENTRY *ie, - ntfs_index_context *ictx); + ntfs_index_context *ictx); extern int ntfs_index_add_filename(ntfs_inode *ni, FILE_NAME_ATTR *fn, - MFT_REF mref); + MFT_REF mref); extern int ntfs_index_remove(ntfs_inode *dir_ni, ntfs_inode *ni, - const void *key, const int keylen); + const void *key, const int keylen); extern INDEX_ROOT *ntfs_index_root_get(ntfs_inode *ni, ATTR_RECORD *attr); diff --git a/source/libntfs/inode.c b/source/libntfs/inode.c index 115f02a9..ad554b36 100644 --- a/source/libntfs/inode.c +++ b/source/libntfs/inode.c @@ -54,10 +54,11 @@ #include "logging.h" #include "misc.h" -ntfs_inode *ntfs_inode_base(ntfs_inode *ni) { - if (ni->nr_extents == -1) - return ni->base_ni; - return ni; +ntfs_inode *ntfs_inode_base(ntfs_inode *ni) +{ + if (ni->nr_extents == -1) + return ni->base_ni; + return ni; } /** @@ -70,10 +71,11 @@ ntfs_inode *ntfs_inode_base(ntfs_inode *ni) { * * This function cannot fail. */ -void ntfs_inode_mark_dirty(ntfs_inode *ni) { - NInoSetDirty(ni); - if (ni->nr_extents == -1) - NInoSetDirty(ni->base_ni); +void ntfs_inode_mark_dirty(ntfs_inode *ni) +{ + NInoSetDirty(ni); + if (ni->nr_extents == -1) + NInoSetDirty(ni->base_ni); } /** @@ -84,13 +86,14 @@ void ntfs_inode_mark_dirty(ntfs_inode *ni) { * * Returns: */ -static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol) { - ntfs_inode *ni; +static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol) +{ + ntfs_inode *ni; - ni = (ntfs_inode*)ntfs_calloc(sizeof(ntfs_inode)); - if (ni) - ni->vol = vol; - return ni; + ni = (ntfs_inode*)ntfs_calloc(sizeof(ntfs_inode)); + if (ni) + ni->vol = vol; + return ni; } /** @@ -101,8 +104,9 @@ static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol) { * * Returns: */ -ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol) { - return __ntfs_inode_allocate(vol); +ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol) +{ + return __ntfs_inode_allocate(vol); } /** @@ -113,15 +117,16 @@ ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol) { * * Returns: */ -static void __ntfs_inode_release(ntfs_inode *ni) { - if (NInoDirty(ni)) - ntfs_log_error("Releasing dirty inode %lld!\n", - (long long)ni->mft_no); - if (NInoAttrList(ni) && ni->attr_list) - free(ni->attr_list); - free(ni->mrec); - free(ni); - return; +static void __ntfs_inode_release(ntfs_inode *ni) +{ + if (NInoDirty(ni)) + ntfs_log_error("Releasing dirty inode %lld!\n", + (long long)ni->mft_no); + if (NInoAttrList(ni) && ni->attr_list) + free(ni->attr_list); + free(ni->mrec); + free(ni); + return; } /** @@ -147,131 +152,132 @@ static void __ntfs_inode_release(ntfs_inode *ni) { * Return a pointer to the ntfs_inode structure on success or NULL on error, * with errno set to the error code. */ -ntfs_inode *ntfs_inode_open(ntfs_volume *vol, const MFT_REF mref) { - s64 l; - ntfs_inode *ni = NULL; - ntfs_attr_search_ctx *ctx; - STANDARD_INFORMATION *std_info; - le32 lthle; - int olderrno; +ntfs_inode *ntfs_inode_open(ntfs_volume *vol, const MFT_REF mref) +{ + s64 l; + ntfs_inode *ni = NULL; + ntfs_attr_search_ctx *ctx; + STANDARD_INFORMATION *std_info; + le32 lthle; + int olderrno; - ntfs_log_enter("Entering for inode %lld\n", (long long)MREF(mref)); - if (!vol) { - errno = EINVAL; - goto out; - } - ni = __ntfs_inode_allocate(vol); - if (!ni) - goto out; - if (ntfs_file_record_read(vol, mref, &ni->mrec, NULL)) - goto err_out; - if (!(ni->mrec->flags & MFT_RECORD_IN_USE)) { - errno = ENOENT; - goto err_out; - } - ni->mft_no = MREF(mref); - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - goto err_out; - /* Receive some basic information about inode. */ - if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED, - 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (!ni->mrec->base_mft_record) - ntfs_log_perror("No STANDARD_INFORMATION in base record" - " %lld", (long long)MREF(mref)); - goto put_err_out; - } - std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - ni->flags = std_info->file_attributes; - ni->creation_time = ntfs2utc(std_info->creation_time); - ni->last_data_change_time = ntfs2utc(std_info->last_data_change_time); - ni->last_mft_change_time = ntfs2utc(std_info->last_mft_change_time); - ni->last_access_time = ntfs2utc(std_info->last_access_time); - /* JPA insert v3 extensions if present */ - /* length may be seen as 72 (v1.x) or 96 (v3.x) */ - lthle = ctx->attr->length; - if (le32_to_cpu(lthle) > sizeof(STANDARD_INFORMATION)) { - set_nino_flag(ni, v3_Extensions); - ni->owner_id = std_info->owner_id; - ni->security_id = std_info->security_id; - ni->quota_charged = std_info->quota_charged; - ni->usn = std_info->usn; - } else { - clear_nino_flag(ni, v3_Extensions); - ni->owner_id = 0; - ni->security_id = 0; - } - /* Set attribute list information. */ - olderrno = errno; - if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, 0, 0, NULL, 0, - ctx)) { - if (errno != ENOENT) - goto put_err_out; - /* Attribute list attribute does not present. */ - /* restore previous errno to avoid misinterpretation */ - errno = olderrno; - goto get_size; - } - NInoSetAttrList(ni); - l = ntfs_get_attribute_value_length(ctx->attr); - if (!l) - goto put_err_out; - if (l > 0x40000) { - errno = EIO; - ntfs_log_perror("Too large attrlist attribute (%lld), inode " - "%lld", (long long)l, (long long)MREF(mref)); - goto put_err_out; - } - ni->attr_list_size = l; - ni->attr_list = ntfs_malloc(ni->attr_list_size); - if (!ni->attr_list) - goto put_err_out; - l = ntfs_get_attribute_value(vol, ctx->attr, ni->attr_list); - if (!l) - goto put_err_out; - if (l != ni->attr_list_size) { - errno = EIO; - ntfs_log_perror("Unexpected attrlist size (%lld <> %u), inode " - "%lld", (long long)l, ni->attr_list_size, - (long long)MREF(mref)); - goto put_err_out; - } + ntfs_log_enter("Entering for inode %lld\n", (long long)MREF(mref)); + if (!vol) { + errno = EINVAL; + goto out; + } + ni = __ntfs_inode_allocate(vol); + if (!ni) + goto out; + if (ntfs_file_record_read(vol, mref, &ni->mrec, NULL)) + goto err_out; + if (!(ni->mrec->flags & MFT_RECORD_IN_USE)) { + errno = ENOENT; + goto err_out; + } + ni->mft_no = MREF(mref); + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + goto err_out; + /* Receive some basic information about inode. */ + if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED, + 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (!ni->mrec->base_mft_record) + ntfs_log_perror("No STANDARD_INFORMATION in base record" + " %lld", (long long)MREF(mref)); + goto put_err_out; + } + std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + ni->flags = std_info->file_attributes; + ni->creation_time = ntfs2utc(std_info->creation_time); + ni->last_data_change_time = ntfs2utc(std_info->last_data_change_time); + ni->last_mft_change_time = ntfs2utc(std_info->last_mft_change_time); + ni->last_access_time = ntfs2utc(std_info->last_access_time); + /* JPA insert v3 extensions if present */ + /* length may be seen as 72 (v1.x) or 96 (v3.x) */ + lthle = ctx->attr->length; + if (le32_to_cpu(lthle) > sizeof(STANDARD_INFORMATION)) { + set_nino_flag(ni, v3_Extensions); + ni->owner_id = std_info->owner_id; + ni->security_id = std_info->security_id; + ni->quota_charged = std_info->quota_charged; + ni->usn = std_info->usn; + } else { + clear_nino_flag(ni, v3_Extensions); + ni->owner_id = 0; + ni->security_id = 0; + } + /* Set attribute list information. */ + olderrno = errno; + if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, 0, 0, NULL, 0, + ctx)) { + if (errno != ENOENT) + goto put_err_out; + /* Attribute list attribute does not present. */ + /* restore previous errno to avoid misinterpretation */ + errno = olderrno; + goto get_size; + } + NInoSetAttrList(ni); + l = ntfs_get_attribute_value_length(ctx->attr); + if (!l) + goto put_err_out; + if (l > 0x40000) { + errno = EIO; + ntfs_log_perror("Too large attrlist attribute (%lld), inode " + "%lld", (long long)l, (long long)MREF(mref)); + goto put_err_out; + } + ni->attr_list_size = l; + ni->attr_list = ntfs_malloc(ni->attr_list_size); + if (!ni->attr_list) + goto put_err_out; + l = ntfs_get_attribute_value(vol, ctx->attr, ni->attr_list); + if (!l) + goto put_err_out; + if (l != ni->attr_list_size) { + errno = EIO; + ntfs_log_perror("Unexpected attrlist size (%lld <> %u), inode " + "%lld", (long long)l, ni->attr_list_size, + (long long)MREF(mref)); + goto put_err_out; + } get_size: - olderrno = errno; - if (ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx)) { - if (errno != ENOENT) - goto put_err_out; - /* Directory or special file. */ - /* restore previous errno to avoid misinterpretation */ - errno = olderrno; - ni->data_size = ni->allocated_size = 0; - } else { - if (ctx->attr->non_resident) { - ni->data_size = sle64_to_cpu(ctx->attr->data_size); - if (ctx->attr->flags & - (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) - ni->allocated_size = sle64_to_cpu( - ctx->attr->compressed_size); - else - ni->allocated_size = sle64_to_cpu( - ctx->attr->allocated_size); - } else { - ni->data_size = le32_to_cpu(ctx->attr->value_length); - ni->allocated_size = (ni->data_size + 7) & ~7; - } - } - ntfs_attr_put_search_ctx(ctx); -out: - ntfs_log_leave("\n"); - return ni; + olderrno = errno; + if (ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx)) { + if (errno != ENOENT) + goto put_err_out; + /* Directory or special file. */ + /* restore previous errno to avoid misinterpretation */ + errno = olderrno; + ni->data_size = ni->allocated_size = 0; + } else { + if (ctx->attr->non_resident) { + ni->data_size = sle64_to_cpu(ctx->attr->data_size); + if (ctx->attr->flags & + (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) + ni->allocated_size = sle64_to_cpu( + ctx->attr->compressed_size); + else + ni->allocated_size = sle64_to_cpu( + ctx->attr->allocated_size); + } else { + ni->data_size = le32_to_cpu(ctx->attr->value_length); + ni->allocated_size = (ni->data_size + 7) & ~7; + } + } + ntfs_attr_put_search_ctx(ctx); +out: + ntfs_log_leave("\n"); + return ni; put_err_out: - ntfs_attr_put_search_ctx(ctx); + ntfs_attr_put_search_ctx(ctx); err_out: - __ntfs_inode_release(ni); - ni = NULL; - goto out; + __ntfs_inode_release(ni); + ni = NULL; + goto out; } /** @@ -298,86 +304,87 @@ err_out: * EINVAL @ni is invalid (probably it is an extent inode). * EIO I/O error while trying to write inode to disk. */ -int ntfs_inode_close(ntfs_inode *ni) { - int ret = -1; +int ntfs_inode_close(ntfs_inode *ni) +{ + int ret = -1; + + if (!ni) + return 0; - if (!ni) - return 0; + ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no); - ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no); + /* If we have dirty metadata, write it out. */ + if (NInoDirty(ni) || NInoAttrListDirty(ni)) { + if (ntfs_inode_sync(ni)) { + if (errno != EIO) + errno = EBUSY; + goto err; + } + } + /* Is this a base inode with mapped extent inodes? */ + if (ni->nr_extents > 0) { + while (ni->nr_extents > 0) { + if (ntfs_inode_close(ni->extent_nis[0])) { + if (errno != EIO) + errno = EBUSY; + goto err; + } + } + } else if (ni->nr_extents == -1) { + ntfs_inode **tmp_nis; + ntfs_inode *base_ni; + s32 i; - /* If we have dirty metadata, write it out. */ - if (NInoDirty(ni) || NInoAttrListDirty(ni)) { - if (ntfs_inode_sync(ni)) { - if (errno != EIO) - errno = EBUSY; - goto err; - } - } - /* Is this a base inode with mapped extent inodes? */ - if (ni->nr_extents > 0) { - while (ni->nr_extents > 0) { - if (ntfs_inode_close(ni->extent_nis[0])) { - if (errno != EIO) - errno = EBUSY; - goto err; - } - } - } else if (ni->nr_extents == -1) { - ntfs_inode **tmp_nis; - ntfs_inode *base_ni; - s32 i; - - /* - * If the inode is an extent inode, disconnect it from the - * base inode before destroying it. - */ - base_ni = ni->base_ni; - for (i = 0; i < base_ni->nr_extents; ++i) { - tmp_nis = base_ni->extent_nis; - if (tmp_nis[i] != ni) - continue; - /* Found it. Disconnect. */ - memmove(tmp_nis + i, tmp_nis + i + 1, - (base_ni->nr_extents - i - 1) * - sizeof(ntfs_inode *)); - /* Buffer should be for multiple of four extents. */ - if ((--base_ni->nr_extents) & 3) { - i = -1; - break; - } - /* - * ElectricFence is unhappy with realloc(x,0) as free(x) - * thus we explicitly separate these two cases. - */ - if (base_ni->nr_extents) { - /* Resize the memory buffer. */ - tmp_nis = realloc(tmp_nis, base_ni->nr_extents * - sizeof(ntfs_inode *)); - /* Ignore errors, they don't really matter. */ - if (tmp_nis) - base_ni->extent_nis = tmp_nis; - } else if (tmp_nis) - free(tmp_nis); - /* Allow for error checking. */ - i = -1; - break; - } - - /* - * We could successfully sync, so only log this error - * and try to sync other inode extents too. - */ - if (i != -1) - ntfs_log_error("Extent inode %lld was not found\n", - (long long)ni->mft_no); - } - - __ntfs_inode_release(ni); - ret = 0; + /* + * If the inode is an extent inode, disconnect it from the + * base inode before destroying it. + */ + base_ni = ni->base_ni; + for (i = 0; i < base_ni->nr_extents; ++i) { + tmp_nis = base_ni->extent_nis; + if (tmp_nis[i] != ni) + continue; + /* Found it. Disconnect. */ + memmove(tmp_nis + i, tmp_nis + i + 1, + (base_ni->nr_extents - i - 1) * + sizeof(ntfs_inode *)); + /* Buffer should be for multiple of four extents. */ + if ((--base_ni->nr_extents) & 3) { + i = -1; + break; + } + /* + * ElectricFence is unhappy with realloc(x,0) as free(x) + * thus we explicitly separate these two cases. + */ + if (base_ni->nr_extents) { + /* Resize the memory buffer. */ + tmp_nis = realloc(tmp_nis, base_ni->nr_extents * + sizeof(ntfs_inode *)); + /* Ignore errors, they don't really matter. */ + if (tmp_nis) + base_ni->extent_nis = tmp_nis; + } else if (tmp_nis) + free(tmp_nis); + /* Allow for error checking. */ + i = -1; + break; + } + + /* + * We could successfully sync, so only log this error + * and try to sync other inode extents too. + */ + if (i != -1) + ntfs_log_error("Extent inode %lld was not found\n", + (long long)ni->mft_no); + } + + __ntfs_inode_release(ni); + ret = 0; err: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } /** @@ -405,75 +412,76 @@ err: * Note, extent inodes are never closed directly. They are automatically * disposed off by the closing of the base inode. */ -ntfs_inode *ntfs_extent_inode_open(ntfs_inode *base_ni, const MFT_REF mref) { - u64 mft_no = MREF_LE(mref); - ntfs_inode *ni = NULL; - ntfs_inode **extent_nis; - int i; +ntfs_inode *ntfs_extent_inode_open(ntfs_inode *base_ni, const MFT_REF mref) +{ + u64 mft_no = MREF_LE(mref); + ntfs_inode *ni = NULL; + ntfs_inode **extent_nis; + int i; - if (!base_ni) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return NULL; - } + if (!base_ni) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return NULL; + } + + ntfs_log_enter("Opening extent inode %lld (base mft record %lld).\n", + (unsigned long long)mft_no, + (unsigned long long)base_ni->mft_no); + + /* Is the extent inode already open and attached to the base inode? */ + if (base_ni->nr_extents > 0) { + extent_nis = base_ni->extent_nis; + for (i = 0; i < base_ni->nr_extents; i++) { + u16 seq_no; - ntfs_log_enter("Opening extent inode %lld (base mft record %lld).\n", - (unsigned long long)mft_no, - (unsigned long long)base_ni->mft_no); + ni = extent_nis[i]; + if (mft_no != ni->mft_no) + continue; + /* Verify the sequence number if given. */ + seq_no = MSEQNO_LE(mref); + if (seq_no && seq_no != le16_to_cpu( + ni->mrec->sequence_number)) { + errno = EIO; + ntfs_log_perror("Found stale extent mft " + "reference mft=%lld", + (long long)ni->mft_no); + goto out; + } + goto out; + } + } + /* Wasn't there, we need to load the extent inode. */ + ni = __ntfs_inode_allocate(base_ni->vol); + if (!ni) + goto out; + if (ntfs_file_record_read(base_ni->vol, le64_to_cpu(mref), &ni->mrec, NULL)) + goto err_out; + ni->mft_no = mft_no; + ni->nr_extents = -1; + ni->base_ni = base_ni; + /* Attach extent inode to base inode, reallocating memory if needed. */ + if (!(base_ni->nr_extents & 3)) { + i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *); - /* Is the extent inode already open and attached to the base inode? */ - if (base_ni->nr_extents > 0) { - extent_nis = base_ni->extent_nis; - for (i = 0; i < base_ni->nr_extents; i++) { - u16 seq_no; - - ni = extent_nis[i]; - if (mft_no != ni->mft_no) - continue; - /* Verify the sequence number if given. */ - seq_no = MSEQNO_LE(mref); - if (seq_no && seq_no != le16_to_cpu( - ni->mrec->sequence_number)) { - errno = EIO; - ntfs_log_perror("Found stale extent mft " - "reference mft=%lld", - (long long)ni->mft_no); - goto out; - } - goto out; - } - } - /* Wasn't there, we need to load the extent inode. */ - ni = __ntfs_inode_allocate(base_ni->vol); - if (!ni) - goto out; - if (ntfs_file_record_read(base_ni->vol, le64_to_cpu(mref), &ni->mrec, NULL)) - goto err_out; - ni->mft_no = mft_no; - ni->nr_extents = -1; - ni->base_ni = base_ni; - /* Attach extent inode to base inode, reallocating memory if needed. */ - if (!(base_ni->nr_extents & 3)) { - i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *); - - extent_nis = ntfs_malloc(i); - if (!extent_nis) - goto err_out; - if (base_ni->nr_extents) { - memcpy(extent_nis, base_ni->extent_nis, - i - 4 * sizeof(ntfs_inode *)); - free(base_ni->extent_nis); - } - base_ni->extent_nis = extent_nis; - } - base_ni->extent_nis[base_ni->nr_extents++] = ni; + extent_nis = ntfs_malloc(i); + if (!extent_nis) + goto err_out; + if (base_ni->nr_extents) { + memcpy(extent_nis, base_ni->extent_nis, + i - 4 * sizeof(ntfs_inode *)); + free(base_ni->extent_nis); + } + base_ni->extent_nis = extent_nis; + } + base_ni->extent_nis[base_ni->nr_extents++] = ni; out: - ntfs_log_leave("\n"); - return ni; + ntfs_log_leave("\n"); + return ni; err_out: - __ntfs_inode_release(ni); - ni = NULL; - goto out; + __ntfs_inode_release(ni); + ni = NULL; + goto out; } /** @@ -482,46 +490,47 @@ err_out: * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_inode_attach_all_extents(ntfs_inode *ni) { - ATTR_LIST_ENTRY *ale; - u64 prev_attached = 0; +int ntfs_inode_attach_all_extents(ntfs_inode *ni) +{ + ATTR_LIST_ENTRY *ale; + u64 prev_attached = 0; - if (!ni) { - ntfs_log_trace("Invalid arguments.\n"); - errno = EINVAL; - return -1; - } + if (!ni) { + ntfs_log_trace("Invalid arguments.\n"); + errno = EINVAL; + return -1; + } - if (ni->nr_extents == -1) - ni = ni->base_ni; + if (ni->nr_extents == -1) + ni = ni->base_ni; - ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no); + ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no); - /* Inode haven't got attribute list, thus nothing to attach. */ - if (!NInoAttrList(ni)) - return 0; + /* Inode haven't got attribute list, thus nothing to attach. */ + if (!NInoAttrList(ni)) + return 0; - if (!ni->attr_list) { - ntfs_log_trace("Corrupt in-memory struct.\n"); - errno = EINVAL; - return -1; - } + if (!ni->attr_list) { + ntfs_log_trace("Corrupt in-memory struct.\n"); + errno = EINVAL; + return -1; + } - /* Walk through attribute list and attach all extents. */ - errno = 0; - ale = (ATTR_LIST_ENTRY *)ni->attr_list; - while ((u8*)ale < ni->attr_list + ni->attr_list_size) { - if (ni->mft_no != MREF_LE(ale->mft_reference) && - prev_attached != MREF_LE(ale->mft_reference)) { - if (!ntfs_extent_inode_open(ni, ale->mft_reference)) { - ntfs_log_trace("Couldn't attach extent inode.\n"); - return -1; - } - prev_attached = MREF_LE(ale->mft_reference); - } - ale = (ATTR_LIST_ENTRY *)((u8*)ale + le16_to_cpu(ale->length)); - } - return 0; + /* Walk through attribute list and attach all extents. */ + errno = 0; + ale = (ATTR_LIST_ENTRY *)ni->attr_list; + while ((u8*)ale < ni->attr_list + ni->attr_list_size) { + if (ni->mft_no != MREF_LE(ale->mft_reference) && + prev_attached != MREF_LE(ale->mft_reference)) { + if (!ntfs_extent_inode_open(ni, ale->mft_reference)) { + ntfs_log_trace("Couldn't attach extent inode.\n"); + return -1; + } + prev_attached = MREF_LE(ale->mft_reference); + } + ale = (ATTR_LIST_ENTRY *)((u8*)ale + le16_to_cpu(ale->length)); + } + return 0; } /** @@ -530,51 +539,52 @@ int ntfs_inode_attach_all_extents(ntfs_inode *ni) { * * Return 0 on success or -1 on error with errno set to the error code. */ -static int ntfs_inode_sync_standard_information(ntfs_inode *ni) { - ntfs_attr_search_ctx *ctx; - STANDARD_INFORMATION *std_info; - u32 lth; - le32 lthle; +static int ntfs_inode_sync_standard_information(ntfs_inode *ni) +{ + ntfs_attr_search_ctx *ctx; + STANDARD_INFORMATION *std_info; + u32 lth; + le32 lthle; - ntfs_log_trace("Entering for inode %lld\n", (long long)ni->mft_no); + ntfs_log_trace("Entering for inode %lld\n", (long long)ni->mft_no); - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; - if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED, - 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { - ntfs_log_perror("Failed to sync standard info (inode %lld)", - (long long)ni->mft_no); - ntfs_attr_put_search_ctx(ctx); - return -1; - } - std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - std_info->file_attributes = ni->flags; - if (test_nino_flag(ni, TimesDirty)) { - std_info->creation_time = utc2ntfs(ni->creation_time); - std_info->last_data_change_time = utc2ntfs(ni->last_data_change_time); - std_info->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); - std_info->last_access_time = utc2ntfs(ni->last_access_time); - } + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return -1; + if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED, + 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { + ntfs_log_perror("Failed to sync standard info (inode %lld)", + (long long)ni->mft_no); + ntfs_attr_put_search_ctx(ctx); + return -1; + } + std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + std_info->file_attributes = ni->flags; + if (test_nino_flag(ni, TimesDirty)) { + std_info->creation_time = utc2ntfs(ni->creation_time); + std_info->last_data_change_time = utc2ntfs(ni->last_data_change_time); + std_info->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); + std_info->last_access_time = utc2ntfs(ni->last_access_time); + } - /* JPA update v3.x extensions, ensuring consistency */ + /* JPA update v3.x extensions, ensuring consistency */ - lthle = ctx->attr->length; - lth = le32_to_cpu(lthle); - if (test_nino_flag(ni, v3_Extensions) - && (lth <= sizeof(STANDARD_INFORMATION))) - ntfs_log_error("bad sync of standard information\n"); + lthle = ctx->attr->length; + lth = le32_to_cpu(lthle); + if (test_nino_flag(ni, v3_Extensions) + && (lth <= sizeof(STANDARD_INFORMATION))) + ntfs_log_error("bad sync of standard information\n"); - if (lth > sizeof(STANDARD_INFORMATION)) { - std_info->owner_id = ni->owner_id; - std_info->security_id = ni->security_id; - std_info->quota_charged = ni->quota_charged; - std_info->usn = ni->usn; - } - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - return 0; + if (lth > sizeof(STANDARD_INFORMATION)) { + std_info->owner_id = ni->owner_id; + std_info->security_id = ni->security_id; + std_info->quota_charged = ni->quota_charged; + std_info->usn = ni->usn; + } + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + return 0; } /** @@ -585,103 +595,104 @@ static int ntfs_inode_sync_standard_information(ntfs_inode *ni) { * * Return 0 on success or -1 on error with errno set to the error code. */ -static int ntfs_inode_sync_file_name(ntfs_inode *ni) { - ntfs_attr_search_ctx *ctx = NULL; - ntfs_index_context *ictx; - ntfs_inode *index_ni; - FILE_NAME_ATTR *fn; - int err = 0; +static int ntfs_inode_sync_file_name(ntfs_inode *ni) +{ + ntfs_attr_search_ctx *ctx = NULL; + ntfs_index_context *ictx; + ntfs_inode *index_ni; + FILE_NAME_ATTR *fn; + int err = 0; - ntfs_log_trace("Entering for inode %lld\n", (long long)ni->mft_no); + ntfs_log_trace("Entering for inode %lld\n", (long long)ni->mft_no); - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) { - err = errno; - goto err_out; - } - /* Walk through all FILE_NAME attributes and update them. */ - while (!ntfs_attr_lookup(AT_FILE_NAME, NULL, 0, 0, 0, NULL, 0, ctx)) { - fn = (FILE_NAME_ATTR *)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - if (MREF_LE(fn->parent_directory) == ni->mft_no) { - /* - * WARNING: We cheat here and obtain 2 attribute - * search contexts for one inode (first we obtained - * above, second will be obtained inside - * ntfs_index_lookup), it's acceptable for library, - * but will deadlock in the kernel. - */ - index_ni = ni; - } else - index_ni = ntfs_inode_open(ni->vol, - le64_to_cpu(fn->parent_directory)); - if (!index_ni) { - if (!err) - err = errno; - ntfs_log_perror("Failed to open inode %lld with index", - (long long)le64_to_cpu(fn->parent_directory)); - continue; - } - ictx = ntfs_index_ctx_get(index_ni, NTFS_INDEX_I30, 4); - if (!ictx) { - if (!err) - err = errno; - ntfs_log_perror("Failed to get index ctx, inode %lld", - (long long)index_ni->mft_no); - if (ni != index_ni && ntfs_inode_close(index_ni) && !err) - err = errno; - continue; - } - if (ntfs_index_lookup(fn, sizeof(FILE_NAME_ATTR), ictx)) { - if (!err) { - if (errno == ENOENT) - err = EIO; - else - err = errno; - } - ntfs_log_perror("Index lookup failed, inode %lld", - (long long)index_ni->mft_no); - ntfs_index_ctx_put(ictx); - if (ni != index_ni && ntfs_inode_close(index_ni) && !err) - err = errno; - continue; - } - /* Update flags and file size. */ - fn = (FILE_NAME_ATTR *)ictx->data; - fn->file_attributes = - (fn->file_attributes & ~FILE_ATTR_VALID_FLAGS) | - (ni->flags & FILE_ATTR_VALID_FLAGS); - fn->allocated_size = cpu_to_sle64(ni->allocated_size); - fn->data_size = cpu_to_sle64(ni->data_size); - if (test_nino_flag(ni, TimesDirty)) { - fn->creation_time = utc2ntfs(ni->creation_time); - fn->last_data_change_time = utc2ntfs(ni->last_data_change_time); - fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); - fn->last_access_time = utc2ntfs(ni->last_access_time); - } - ntfs_index_entry_mark_dirty(ictx); - ntfs_index_ctx_put(ictx); - if ((ni != index_ni) && ntfs_inode_close(index_ni) && !err) - err = errno; - } - /* Check for real error occurred. */ - if (errno != ENOENT) { - err = errno; - ntfs_log_perror("Attribute lookup failed, inode %lld", - (long long)ni->mft_no); - goto err_out; - } - ntfs_attr_put_search_ctx(ctx); - if (err) { - errno = err; - return -1; - } - return 0; + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) { + err = errno; + goto err_out; + } + /* Walk through all FILE_NAME attributes and update them. */ + while (!ntfs_attr_lookup(AT_FILE_NAME, NULL, 0, 0, 0, NULL, 0, ctx)) { + fn = (FILE_NAME_ATTR *)((u8 *)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + if (MREF_LE(fn->parent_directory) == ni->mft_no) { + /* + * WARNING: We cheat here and obtain 2 attribute + * search contexts for one inode (first we obtained + * above, second will be obtained inside + * ntfs_index_lookup), it's acceptable for library, + * but will deadlock in the kernel. + */ + index_ni = ni; + } else + index_ni = ntfs_inode_open(ni->vol, + le64_to_cpu(fn->parent_directory)); + if (!index_ni) { + if (!err) + err = errno; + ntfs_log_perror("Failed to open inode %lld with index", + (long long)le64_to_cpu(fn->parent_directory)); + continue; + } + ictx = ntfs_index_ctx_get(index_ni, NTFS_INDEX_I30, 4); + if (!ictx) { + if (!err) + err = errno; + ntfs_log_perror("Failed to get index ctx, inode %lld", + (long long)index_ni->mft_no); + if (ni != index_ni && ntfs_inode_close(index_ni) && !err) + err = errno; + continue; + } + if (ntfs_index_lookup(fn, sizeof(FILE_NAME_ATTR), ictx)) { + if (!err) { + if (errno == ENOENT) + err = EIO; + else + err = errno; + } + ntfs_log_perror("Index lookup failed, inode %lld", + (long long)index_ni->mft_no); + ntfs_index_ctx_put(ictx); + if (ni != index_ni && ntfs_inode_close(index_ni) && !err) + err = errno; + continue; + } + /* Update flags and file size. */ + fn = (FILE_NAME_ATTR *)ictx->data; + fn->file_attributes = + (fn->file_attributes & ~FILE_ATTR_VALID_FLAGS) | + (ni->flags & FILE_ATTR_VALID_FLAGS); + fn->allocated_size = cpu_to_sle64(ni->allocated_size); + fn->data_size = cpu_to_sle64(ni->data_size); + if (test_nino_flag(ni, TimesDirty)) { + fn->creation_time = utc2ntfs(ni->creation_time); + fn->last_data_change_time = utc2ntfs(ni->last_data_change_time); + fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time); + fn->last_access_time = utc2ntfs(ni->last_access_time); + } + ntfs_index_entry_mark_dirty(ictx); + ntfs_index_ctx_put(ictx); + if ((ni != index_ni) && ntfs_inode_close(index_ni) && !err) + err = errno; + } + /* Check for real error occurred. */ + if (errno != ENOENT) { + err = errno; + ntfs_log_perror("Attribute lookup failed, inode %lld", + (long long)ni->mft_no); + goto err_out; + } + ntfs_attr_put_search_ctx(ctx); + if (err) { + errno = err; + return -1; + } + return 0; err_out: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + errno = err; + return -1; } /** @@ -703,132 +714,133 @@ err_out: * EBUSY - Inode and/or one of its extents is busy, try again later. * EIO - I/O error while writing the inode (or one of its extents). */ -int ntfs_inode_sync(ntfs_inode *ni) { - int ret = 0; - int err = 0; +int ntfs_inode_sync(ntfs_inode *ni) +{ + int ret = 0; + int err = 0; - if (!ni) { - errno = EINVAL; - ntfs_log_error("Failed to sync NULL inode\n"); - return -1; - } + if (!ni) { + errno = EINVAL; + ntfs_log_error("Failed to sync NULL inode\n"); + return -1; + } - ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no); + ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no); - /* Update STANDARD_INFORMATION. */ - if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 && - ntfs_inode_sync_standard_information(ni)) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - } - } + /* Update STANDARD_INFORMATION. */ + if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 && + ntfs_inode_sync_standard_information(ni)) { + if (!err || errno == EIO) { + err = errno; + if (err != EIO) + err = EBUSY; + } + } - /* Update FILE_NAME's in the index. */ - if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 && - NInoFileNameTestAndClearDirty(ni) && - ntfs_inode_sync_file_name(ni)) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - } - ntfs_log_perror("Failed to sync FILE_NAME (inode %lld)", - (long long)ni->mft_no); - NInoFileNameSetDirty(ni); - } + /* Update FILE_NAME's in the index. */ + if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 && + NInoFileNameTestAndClearDirty(ni) && + ntfs_inode_sync_file_name(ni)) { + if (!err || errno == EIO) { + err = errno; + if (err != EIO) + err = EBUSY; + } + ntfs_log_perror("Failed to sync FILE_NAME (inode %lld)", + (long long)ni->mft_no); + NInoFileNameSetDirty(ni); + } - /* Write out attribute list from cache to disk. */ - if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 && - NInoAttrList(ni) && NInoAttrListTestAndClearDirty(ni)) { - ntfs_attr *na; - - na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); - if (!na) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - ntfs_log_perror("Attribute list sync failed " - "(open, inode %lld)", - (long long)ni->mft_no); - } - NInoAttrListSetDirty(ni); - goto sync_inode; - } - - if (na->data_size == ni->attr_list_size) { - if (ntfs_attr_pwrite(na, 0, ni->attr_list_size, - ni->attr_list) != ni->attr_list_size) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - ntfs_log_perror("Attribute list sync " - "failed (write, inode %lld)", - (long long)ni->mft_no); - } - NInoAttrListSetDirty(ni); - } - } else { - err = EIO; - ntfs_log_error("Attribute list sync failed (bad size, " - "inode %lld)\n", (long long)ni->mft_no); - NInoAttrListSetDirty(ni); - } - ntfs_attr_close(na); - } + /* Write out attribute list from cache to disk. */ + if ((ni->mrec->flags & MFT_RECORD_IN_USE) && ni->nr_extents != -1 && + NInoAttrList(ni) && NInoAttrListTestAndClearDirty(ni)) { + ntfs_attr *na; + na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); + if (!na) { + if (!err || errno == EIO) { + err = errno; + if (err != EIO) + err = EBUSY; + ntfs_log_perror("Attribute list sync failed " + "(open, inode %lld)", + (long long)ni->mft_no); + } + NInoAttrListSetDirty(ni); + goto sync_inode; + } + + if (na->data_size == ni->attr_list_size) { + if (ntfs_attr_pwrite(na, 0, ni->attr_list_size, + ni->attr_list) != ni->attr_list_size) { + if (!err || errno == EIO) { + err = errno; + if (err != EIO) + err = EBUSY; + ntfs_log_perror("Attribute list sync " + "failed (write, inode %lld)", + (long long)ni->mft_no); + } + NInoAttrListSetDirty(ni); + } + } else { + err = EIO; + ntfs_log_error("Attribute list sync failed (bad size, " + "inode %lld)\n", (long long)ni->mft_no); + NInoAttrListSetDirty(ni); + } + ntfs_attr_close(na); + } + sync_inode: - /* Write this inode out to the $MFT (and $MFTMirr if applicable). */ - if (NInoTestAndClearDirty(ni)) { - if (ntfs_mft_record_write(ni->vol, ni->mft_no, ni->mrec)) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - } - NInoSetDirty(ni); - ntfs_log_perror("MFT record sync failed, inode %lld", - (long long)ni->mft_no); - } - } + /* Write this inode out to the $MFT (and $MFTMirr if applicable). */ + if (NInoTestAndClearDirty(ni)) { + if (ntfs_mft_record_write(ni->vol, ni->mft_no, ni->mrec)) { + if (!err || errno == EIO) { + err = errno; + if (err != EIO) + err = EBUSY; + } + NInoSetDirty(ni); + ntfs_log_perror("MFT record sync failed, inode %lld", + (long long)ni->mft_no); + } + } - /* If this is a base inode with extents write all dirty extents, too. */ - if (ni->nr_extents > 0) { - s32 i; + /* If this is a base inode with extents write all dirty extents, too. */ + if (ni->nr_extents > 0) { + s32 i; - for (i = 0; i < ni->nr_extents; ++i) { - ntfs_inode *eni; + for (i = 0; i < ni->nr_extents; ++i) { + ntfs_inode *eni; - eni = ni->extent_nis[i]; - if (!NInoTestAndClearDirty(eni)) - continue; + eni = ni->extent_nis[i]; + if (!NInoTestAndClearDirty(eni)) + continue; + + if (ntfs_mft_record_write(eni->vol, eni->mft_no, + eni->mrec)) { + if (!err || errno == EIO) { + err = errno; + if (err != EIO) + err = EBUSY; + } + NInoSetDirty(eni); + ntfs_log_perror("Extent MFT record sync failed," + " inode %lld/%lld", + (long long)ni->mft_no, + (long long)eni->mft_no); + } + } + } - if (ntfs_mft_record_write(eni->vol, eni->mft_no, - eni->mrec)) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - } - NInoSetDirty(eni); - ntfs_log_perror("Extent MFT record sync failed," - " inode %lld/%lld", - (long long)ni->mft_no, - (long long)eni->mft_no); - } - } - } - - if (err) { - errno = err; - ret = -1; - } - - ntfs_log_leave("\n"); - return ret; + if (err) { + errno = err; + ret = -1; + } + + ntfs_log_leave("\n"); + return ret; } /** @@ -842,181 +854,182 @@ sync_inode: * EIO - Input/Ouput error occurred. * ENOMEM - Not enough memory to perform add. */ -int ntfs_inode_add_attrlist(ntfs_inode *ni) { - int err; - ntfs_attr_search_ctx *ctx; - u8 *al = NULL, *aln; - int al_len = 0; - ATTR_LIST_ENTRY *ale = NULL; - ntfs_attr *na; +int ntfs_inode_add_attrlist(ntfs_inode *ni) +{ + int err; + ntfs_attr_search_ctx *ctx; + u8 *al = NULL, *aln; + int al_len = 0; + ATTR_LIST_ENTRY *ale = NULL; + ntfs_attr *na; - if (!ni) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } + if (!ni) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } - ntfs_log_trace("inode %llu\n", (unsigned long long) ni->mft_no); + ntfs_log_trace("inode %llu\n", (unsigned long long) ni->mft_no); - if (NInoAttrList(ni) || ni->nr_extents) { - errno = EEXIST; - ntfs_log_perror("Inode already has attribute list"); - return -1; - } + if (NInoAttrList(ni) || ni->nr_extents) { + errno = EEXIST; + ntfs_log_perror("Inode already has attribute list"); + return -1; + } - /* Form attribute list. */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) { - err = errno; - goto err_out; - } - /* Walk through all attributes. */ - while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) { + /* Form attribute list. */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) { + err = errno; + goto err_out; + } + /* Walk through all attributes. */ + while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) { + + int ale_size; + + if (ctx->attr->type == AT_ATTRIBUTE_LIST) { + err = EIO; + ntfs_log_perror("Attribute list already present"); + goto put_err_out; + } + + ale_size = (sizeof(ATTR_LIST_ENTRY) + sizeof(ntfschar) * + ctx->attr->name_length + 7) & ~7; + al_len += ale_size; + + aln = realloc(al, al_len); + if (!aln) { + err = errno; + ntfs_log_perror("Failed to realloc %d bytes", al_len); + goto put_err_out; + } + ale = (ATTR_LIST_ENTRY *)(aln + ((u8 *)ale - al)); + al = aln; + + memset(ale, 0, ale_size); + + /* Add attribute to attribute list. */ + ale->type = ctx->attr->type; + ale->length = cpu_to_le16((sizeof(ATTR_LIST_ENTRY) + + sizeof(ntfschar) * ctx->attr->name_length + 7) & ~7); + ale->name_length = ctx->attr->name_length; + ale->name_offset = (u8 *)ale->name - (u8 *)ale; + if (ctx->attr->non_resident) + ale->lowest_vcn = ctx->attr->lowest_vcn; + else + ale->lowest_vcn = 0; + ale->mft_reference = MK_LE_MREF(ni->mft_no, + le16_to_cpu(ni->mrec->sequence_number)); + ale->instance = ctx->attr->instance; + memcpy(ale->name, (u8 *)ctx->attr + + le16_to_cpu(ctx->attr->name_offset), + ctx->attr->name_length * sizeof(ntfschar)); + ale = (ATTR_LIST_ENTRY *)(al + al_len); + } + /* Check for real error occurred. */ + if (errno != ENOENT) { + err = errno; + ntfs_log_perror("%s: Attribute lookup failed, inode %lld", + __FUNCTION__, (long long)ni->mft_no); + goto put_err_out; + } - int ale_size; + /* Set in-memory attribute list. */ + ni->attr_list = al; + ni->attr_list_size = al_len; + NInoSetAttrList(ni); + NInoAttrListSetDirty(ni); - if (ctx->attr->type == AT_ATTRIBUTE_LIST) { - err = EIO; - ntfs_log_perror("Attribute list already present"); - goto put_err_out; - } + /* Free space if there is not enough it for $ATTRIBUTE_LIST. */ + if (le32_to_cpu(ni->mrec->bytes_allocated) - + le32_to_cpu(ni->mrec->bytes_in_use) < + offsetof(ATTR_RECORD, resident_end)) { + if (ntfs_inode_free_space(ni, + offsetof(ATTR_RECORD, resident_end))) { + /* Failed to free space. */ + err = errno; + ntfs_log_perror("Failed to free space for attrlist"); + goto rollback; + } + } - ale_size = (sizeof(ATTR_LIST_ENTRY) + sizeof(ntfschar) * - ctx->attr->name_length + 7) & ~7; - al_len += ale_size; + /* Add $ATTRIBUTE_LIST to mft record. */ + if (ntfs_resident_attr_record_add(ni, + AT_ATTRIBUTE_LIST, NULL, 0, NULL, 0, 0) < 0) { + err = errno; + ntfs_log_perror("Couldn't add $ATTRIBUTE_LIST to MFT"); + goto rollback; + } - aln = realloc(al, al_len); - if (!aln) { - err = errno; - ntfs_log_perror("Failed to realloc %d bytes", al_len); - goto put_err_out; - } - ale = (ATTR_LIST_ENTRY *)(aln + ((u8 *)ale - al)); - al = aln; - - memset(ale, 0, ale_size); - - /* Add attribute to attribute list. */ - ale->type = ctx->attr->type; - ale->length = cpu_to_le16((sizeof(ATTR_LIST_ENTRY) + - sizeof(ntfschar) * ctx->attr->name_length + 7) & ~7); - ale->name_length = ctx->attr->name_length; - ale->name_offset = (u8 *)ale->name - (u8 *)ale; - if (ctx->attr->non_resident) - ale->lowest_vcn = ctx->attr->lowest_vcn; - else - ale->lowest_vcn = 0; - ale->mft_reference = MK_LE_MREF(ni->mft_no, - le16_to_cpu(ni->mrec->sequence_number)); - ale->instance = ctx->attr->instance; - memcpy(ale->name, (u8 *)ctx->attr + - le16_to_cpu(ctx->attr->name_offset), - ctx->attr->name_length * sizeof(ntfschar)); - ale = (ATTR_LIST_ENTRY *)(al + al_len); - } - /* Check for real error occurred. */ - if (errno != ENOENT) { - err = errno; - ntfs_log_perror("%s: Attribute lookup failed, inode %lld", - __FUNCTION__, (long long)ni->mft_no); - goto put_err_out; - } - - /* Set in-memory attribute list. */ - ni->attr_list = al; - ni->attr_list_size = al_len; - NInoSetAttrList(ni); - NInoAttrListSetDirty(ni); - - /* Free space if there is not enough it for $ATTRIBUTE_LIST. */ - if (le32_to_cpu(ni->mrec->bytes_allocated) - - le32_to_cpu(ni->mrec->bytes_in_use) < - offsetof(ATTR_RECORD, resident_end)) { - if (ntfs_inode_free_space(ni, - offsetof(ATTR_RECORD, resident_end))) { - /* Failed to free space. */ - err = errno; - ntfs_log_perror("Failed to free space for attrlist"); - goto rollback; - } - } - - /* Add $ATTRIBUTE_LIST to mft record. */ - if (ntfs_resident_attr_record_add(ni, - AT_ATTRIBUTE_LIST, NULL, 0, NULL, 0, 0) < 0) { - err = errno; - ntfs_log_perror("Couldn't add $ATTRIBUTE_LIST to MFT"); - goto rollback; - } - - /* Resize it. */ - na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); - if (!na) { - err = errno; - ntfs_log_perror("Failed to open just added $ATTRIBUTE_LIST"); - goto remove_attrlist_record; - } - if (ntfs_attr_truncate(na, al_len)) { - err = errno; - ntfs_log_perror("Failed to resize just added $ATTRIBUTE_LIST"); - ntfs_attr_close(na); - goto remove_attrlist_record;; - } - - ntfs_attr_put_search_ctx(ctx); - ntfs_attr_close(na); - return 0; + /* Resize it. */ + na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); + if (!na) { + err = errno; + ntfs_log_perror("Failed to open just added $ATTRIBUTE_LIST"); + goto remove_attrlist_record; + } + if (ntfs_attr_truncate(na, al_len)) { + err = errno; + ntfs_log_perror("Failed to resize just added $ATTRIBUTE_LIST"); + ntfs_attr_close(na); + goto remove_attrlist_record;; + } + + ntfs_attr_put_search_ctx(ctx); + ntfs_attr_close(na); + return 0; remove_attrlist_record: - /* Prevent ntfs_attr_recorm_rm from freeing attribute list. */ - ni->attr_list = NULL; - NInoClearAttrList(ni); - /* Remove $ATTRIBUTE_LIST record. */ - ntfs_attr_reinit_search_ctx(ctx); - if (!ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (ntfs_attr_record_rm(ctx)) - ntfs_log_perror("Rollback failed to remove attrlist"); - } else - ntfs_log_perror("Rollback failed to find attrlist"); - /* Setup back in-memory runlist. */ - ni->attr_list = al; - ni->attr_list_size = al_len; - NInoSetAttrList(ni); + /* Prevent ntfs_attr_recorm_rm from freeing attribute list. */ + ni->attr_list = NULL; + NInoClearAttrList(ni); + /* Remove $ATTRIBUTE_LIST record. */ + ntfs_attr_reinit_search_ctx(ctx); + if (!ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, + CASE_SENSITIVE, 0, NULL, 0, ctx)) { + if (ntfs_attr_record_rm(ctx)) + ntfs_log_perror("Rollback failed to remove attrlist"); + } else + ntfs_log_perror("Rollback failed to find attrlist"); + /* Setup back in-memory runlist. */ + ni->attr_list = al; + ni->attr_list_size = al_len; + NInoSetAttrList(ni); rollback: - /* - * Scan attribute list for attributes that placed not in the base MFT - * record and move them to it. - */ - ntfs_attr_reinit_search_ctx(ctx); - ale = (ATTR_LIST_ENTRY*)al; - while ((u8*)ale < al + al_len) { - if (MREF_LE(ale->mft_reference) != ni->mft_no) { - if (!ntfs_attr_lookup(ale->type, ale->name, - ale->name_length, - CASE_SENSITIVE, - sle64_to_cpu(ale->lowest_vcn), - NULL, 0, ctx)) { - if (ntfs_attr_record_move_to(ctx, ni)) - ntfs_log_perror("Rollback failed to " - "move attribute"); - } else - ntfs_log_perror("Rollback failed to find attr"); - ntfs_attr_reinit_search_ctx(ctx); - } - ale = (ATTR_LIST_ENTRY*)((u8*)ale + le16_to_cpu(ale->length)); - } - /* Remove in-memory attribute list. */ - ni->attr_list = NULL; - ni->attr_list_size = 0; - NInoClearAttrList(ni); - NInoAttrListClearDirty(ni); + /* + * Scan attribute list for attributes that placed not in the base MFT + * record and move them to it. + */ + ntfs_attr_reinit_search_ctx(ctx); + ale = (ATTR_LIST_ENTRY*)al; + while ((u8*)ale < al + al_len) { + if (MREF_LE(ale->mft_reference) != ni->mft_no) { + if (!ntfs_attr_lookup(ale->type, ale->name, + ale->name_length, + CASE_SENSITIVE, + sle64_to_cpu(ale->lowest_vcn), + NULL, 0, ctx)) { + if (ntfs_attr_record_move_to(ctx, ni)) + ntfs_log_perror("Rollback failed to " + "move attribute"); + } else + ntfs_log_perror("Rollback failed to find attr"); + ntfs_attr_reinit_search_ctx(ctx); + } + ale = (ATTR_LIST_ENTRY*)((u8*)ale + le16_to_cpu(ale->length)); + } + /* Remove in-memory attribute list. */ + ni->attr_list = NULL; + ni->attr_list_size = 0; + NInoClearAttrList(ni); + NInoAttrListClearDirty(ni); put_err_out: - ntfs_attr_put_search_ctx(ctx); + ntfs_attr_put_search_ctx(ctx); err_out: - free(al); - errno = err; - return -1; + free(al); + errno = err; + return -1; } /** @@ -1026,83 +1039,84 @@ err_out: * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_inode_free_space(ntfs_inode *ni, int size) { - ntfs_attr_search_ctx *ctx; - int freed; +int ntfs_inode_free_space(ntfs_inode *ni, int size) +{ + ntfs_attr_search_ctx *ctx; + int freed; - if (!ni || size < 0) { - errno = EINVAL; - ntfs_log_perror("%s: ni=%p size=%d", __FUNCTION__, ni, size); - return -1; - } + if (!ni || size < 0) { + errno = EINVAL; + ntfs_log_perror("%s: ni=%p size=%d", __FUNCTION__, ni, size); + return -1; + } - ntfs_log_trace("Entering for inode %lld, size %d\n", - (unsigned long long)ni->mft_no, size); + ntfs_log_trace("Entering for inode %lld, size %d\n", + (unsigned long long)ni->mft_no, size); - freed = (le32_to_cpu(ni->mrec->bytes_allocated) - - le32_to_cpu(ni->mrec->bytes_in_use)); + freed = (le32_to_cpu(ni->mrec->bytes_allocated) - + le32_to_cpu(ni->mrec->bytes_in_use)); - if (size <= freed) - return 0; + if (size <= freed) + return 0; - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; - /* - * $STANDARD_INFORMATION and $ATTRIBUTE_LIST must stay in the base MFT - * record, so position search context on the first attribute after them. - */ - if (ntfs_attr_position(AT_FILE_NAME, ctx)) - goto put_err_out; + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + return -1; + /* + * $STANDARD_INFORMATION and $ATTRIBUTE_LIST must stay in the base MFT + * record, so position search context on the first attribute after them. + */ + if (ntfs_attr_position(AT_FILE_NAME, ctx)) + goto put_err_out; - while (1) { - int record_size; - /* - * Check whether attribute is from different MFT record. If so, - * find next, because we don't need such. - */ - while (ctx->ntfs_ino->mft_no != ni->mft_no) { -retry: - if (ntfs_attr_position(AT_UNUSED, ctx)) - goto put_err_out; - } + while (1) { + int record_size; + /* + * Check whether attribute is from different MFT record. If so, + * find next, because we don't need such. + */ + while (ctx->ntfs_ino->mft_no != ni->mft_no) { +retry: + if (ntfs_attr_position(AT_UNUSED, ctx)) + goto put_err_out; + } - if (ntfs_inode_base(ctx->ntfs_ino)->mft_no == FILE_MFT && - ctx->attr->type == AT_DATA) - goto retry; + if (ntfs_inode_base(ctx->ntfs_ino)->mft_no == FILE_MFT && + ctx->attr->type == AT_DATA) + goto retry; - if (ctx->attr->type == AT_INDEX_ROOT) - goto retry; + if (ctx->attr->type == AT_INDEX_ROOT) + goto retry; - record_size = le32_to_cpu(ctx->attr->length); + record_size = le32_to_cpu(ctx->attr->length); - if (ntfs_attr_record_move_away(ctx, 0)) { - ntfs_log_perror("Failed to move out attribute #2"); - break; - } - freed += record_size; + if (ntfs_attr_record_move_away(ctx, 0)) { + ntfs_log_perror("Failed to move out attribute #2"); + break; + } + freed += record_size; - /* Check whether we are done. */ - if (size <= freed) { - ntfs_attr_put_search_ctx(ctx); - return 0; - } - /* - * Reposition to first attribute after $STANDARD_INFORMATION - * and $ATTRIBUTE_LIST instead of simply skipping this attribute - * because in the case when we have got only in-memory attribute - * list then ntfs_attr_lookup will fail when it tries to find - * $ATTRIBUTE_LIST. - */ - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_position(AT_FILE_NAME, ctx)) - break; - } + /* Check whether we are done. */ + if (size <= freed) { + ntfs_attr_put_search_ctx(ctx); + return 0; + } + /* + * Reposition to first attribute after $STANDARD_INFORMATION + * and $ATTRIBUTE_LIST instead of simply skipping this attribute + * because in the case when we have got only in-memory attribute + * list then ntfs_attr_lookup will fail when it tries to find + * $ATTRIBUTE_LIST. + */ + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_position(AT_FILE_NAME, ctx)) + break; + } put_err_out: - ntfs_attr_put_search_ctx(ctx); - if (errno == ENOSPC) - ntfs_log_trace("No attributes left that could be moved out.\n"); - return -1; + ntfs_attr_put_search_ctx(ctx); + if (errno == ENOSPC) + ntfs_log_trace("No attributes left that could be moved out.\n"); + return -1; } /** @@ -1113,29 +1127,30 @@ put_err_out: * This function updates time fields to current time. Fields to update are * selected using @mask (see enum @ntfs_time_update_flags for posssible values). */ -void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask) { - time_t now; +void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask) +{ + time_t now; - if (!ni) { - ntfs_log_error("%s(): Invalid arguments.\n", __FUNCTION__); - return; - } + if (!ni) { + ntfs_log_error("%s(): Invalid arguments.\n", __FUNCTION__); + return; + } - if ((ni->mft_no < FILE_first_user && ni->mft_no != FILE_root) || - NVolReadOnly(ni->vol) || !mask) - return; + if ((ni->mft_no < FILE_first_user && ni->mft_no != FILE_root) || + NVolReadOnly(ni->vol) || !mask) + return; - now = time(NULL); - if (mask & NTFS_UPDATE_ATIME) - ni->last_access_time = now; - if (mask & NTFS_UPDATE_MTIME) - ni->last_data_change_time = now; - if (mask & NTFS_UPDATE_CTIME) - ni->last_mft_change_time = now; - - set_nino_flag(ni, TimesDirty); - NInoFileNameSetDirty(ni); - NInoSetDirty(ni); + now = time(NULL); + if (mask & NTFS_UPDATE_ATIME) + ni->last_access_time = now; + if (mask & NTFS_UPDATE_MTIME) + ni->last_data_change_time = now; + if (mask & NTFS_UPDATE_CTIME) + ni->last_mft_change_time = now; + + set_nino_flag(ni, TimesDirty); + NInoFileNameSetDirty(ni); + NInoSetDirty(ni); } /** @@ -1146,39 +1161,40 @@ void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask) { * Check if the mft record given by @mft_no and @attr contains the bad sector * list. Please note that mft record numbers describing $Badclus extent inodes * will not match the current $Badclus:$Bad check. - * + * * On success return 1 if the file is $Badclus:$Bad, otherwise return 0. * On error return -1 with errno set to the error code. */ -int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *attr) { - int len, ret = 0; - ntfschar *ustr; +int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *attr) +{ + int len, ret = 0; + ntfschar *ustr; - if (!attr) { - ntfs_log_error("Invalid argument.\n"); - errno = EINVAL; - return -1; - } + if (!attr) { + ntfs_log_error("Invalid argument.\n"); + errno = EINVAL; + return -1; + } + + if (mft_no != FILE_BadClus) + return 0; - if (mft_no != FILE_BadClus) - return 0; + if (attr->type != AT_DATA) + return 0; - if (attr->type != AT_DATA) - return 0; + if ((ustr = ntfs_str2ucs("$Bad", &len)) == NULL) { + ntfs_log_perror("Couldn't convert '$Bad' to Unicode"); + return -1; + } - if ((ustr = ntfs_str2ucs("$Bad", &len)) == NULL) { - ntfs_log_perror("Couldn't convert '$Bad' to Unicode"); - return -1; - } + if (ustr && ntfs_names_are_equal(ustr, len, + (ntfschar *)((u8 *)attr + le16_to_cpu(attr->name_offset)), + attr->name_length, 0, NULL, 0)) + ret = 1; - if (ustr && ntfs_names_are_equal(ustr, len, - (ntfschar *)((u8 *)attr + le16_to_cpu(attr->name_offset)), - attr->name_length, 0, NULL, 0)) - ret = 1; + ntfs_ucsfree(ustr); - ntfs_ucsfree(ustr); - - return ret; + return ret; } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -1194,47 +1210,48 @@ int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *attr) { */ int ntfs_inode_get_times(const char *path __attribute__((unused)), - char *value, size_t size, ntfs_inode *ni) { - ntfs_attr_search_ctx *ctx; - STANDARD_INFORMATION *std_info; - u64 *times; - int ret; + char *value, size_t size, ntfs_inode *ni) +{ + ntfs_attr_search_ctx *ctx; + STANDARD_INFORMATION *std_info; + u64 *times; + int ret; - ret = 0; - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (ctx) { - if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED, - 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { - ntfs_log_perror("Failed to get standard info (inode %lld)", - (long long)ni->mft_no); - } else { - std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - if (value && (size >= 8)) { - times = (u64*)value; - times[0] = le64_to_cpu(std_info->creation_time); - ret = 8; - if (size >= 16) { - times[1] = le64_to_cpu(std_info->last_data_change_time); - ret = 16; - } - if (size >= 24) { - times[2] = le64_to_cpu(std_info->last_access_time); - ret = 24; - } - if (size >= 32) { - times[3] = le64_to_cpu(std_info->last_mft_change_time); - ret = 32; - } - } else - if (!size) - ret = 32; - else - ret = -ERANGE; - } - ntfs_attr_put_search_ctx(ctx); - } - return (ret ? ret : -errno); + ret = 0; + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (ctx) { + if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, AT_UNNAMED, + 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { + ntfs_log_perror("Failed to get standard info (inode %lld)", + (long long)ni->mft_no); + } else { + std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + if (value && (size >= 8)) { + times = (u64*)value; + times[0] = le64_to_cpu(std_info->creation_time); + ret = 8; + if (size >= 16) { + times[1] = le64_to_cpu(std_info->last_data_change_time); + ret = 16; + } + if (size >= 24) { + times[2] = le64_to_cpu(std_info->last_access_time); + ret = 24; + } + if (size >= 32) { + times[3] = le64_to_cpu(std_info->last_mft_change_time); + ret = 32; + } + } else + if (!size) + ret = 32; + else + ret = -ERANGE; + } + ntfs_attr_put_search_ctx(ctx); + } + return (ret ? ret : -errno); } /* @@ -1252,81 +1269,82 @@ int ntfs_inode_get_times(const char *path __attribute__((unused)), */ int ntfs_inode_set_times(const char *path __attribute__((unused)), - const char *value, size_t size, - int flags, ntfs_inode *ni) { - ntfs_attr_search_ctx *ctx; - STANDARD_INFORMATION *std_info; - FILE_NAME_ATTR *fn; - const u64 *times; - le64 now; - int cnt; - int ret; + const char *value, size_t size, + int flags, ntfs_inode *ni) +{ + ntfs_attr_search_ctx *ctx; + STANDARD_INFORMATION *std_info; + FILE_NAME_ATTR *fn; + const u64 *times; + le64 now; + int cnt; + int ret; - ret = -1; - if ((size >= 8) && !(flags & XATTR_CREATE)) { - times = (const u64*)value; - now = utc2ntfs(time((time_t*)NULL)); - /* update the standard information attribute */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (ctx) { - if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, - AT_UNNAMED, 0, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - ntfs_log_perror("Failed to get standard info (inode %lld)", - (long long)ni->mft_no); - } else { - std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - /* - * Do not mark times dirty to avoid - * overwriting them when the inode is closed. - */ - std_info->creation_time = cpu_to_le64(times[0]); - if (size >= 16) - std_info->last_data_change_time = cpu_to_le64(times[1]); - if (size >= 24) - std_info->last_access_time = cpu_to_le64(times[2]); - std_info->last_mft_change_time = now; - ntfs_inode_mark_dirty(ctx->ntfs_ino); + ret = -1; + if ((size >= 8) && !(flags & XATTR_CREATE)) { + times = (const u64*)value; + now = utc2ntfs(time((time_t*)NULL)); + /* update the standard information attribute */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (ctx) { + if (ntfs_attr_lookup(AT_STANDARD_INFORMATION, + AT_UNNAMED, 0, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + ntfs_log_perror("Failed to get standard info (inode %lld)", + (long long)ni->mft_no); + } else { + std_info = (STANDARD_INFORMATION *)((u8 *)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + /* + * Do not mark times dirty to avoid + * overwriting them when the inode is closed. + */ + std_info->creation_time = cpu_to_le64(times[0]); + if (size >= 16) + std_info->last_data_change_time = cpu_to_le64(times[1]); + if (size >= 24) + std_info->last_access_time = cpu_to_le64(times[2]); + std_info->last_mft_change_time = now; + ntfs_inode_mark_dirty(ctx->ntfs_ino); - /* update the file names attributes */ - ntfs_attr_reinit_search_ctx(ctx); - cnt = 0; - while (!ntfs_attr_lookup(AT_FILE_NAME, - AT_UNNAMED, 0, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - fn = (FILE_NAME_ATTR*)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - /* - * Do not mark times dirty to avoid - * overwriting them when the inode is closed. - */ - fn->creation_time - = cpu_to_le64(times[0]); - if (size >= 16) - fn->last_data_change_time - = cpu_to_le64(times[1]); - if (size >= 24) - fn->last_access_time - = cpu_to_le64(times[2]); - fn->last_mft_change_time = now; - cnt++; - } - if (cnt) - ret = 0; - else { - ntfs_log_perror("Failed to get file names (inode %lld)", - (long long)ni->mft_no); - } - } - ntfs_attr_put_search_ctx(ctx); - } - } else - if (size < 8) - errno = ERANGE; - else - errno = EEXIST; - return (ret); + /* update the file names attributes */ + ntfs_attr_reinit_search_ctx(ctx); + cnt = 0; + while (!ntfs_attr_lookup(AT_FILE_NAME, + AT_UNNAMED, 0, CASE_SENSITIVE, + 0, NULL, 0, ctx)) { + fn = (FILE_NAME_ATTR*)((u8 *)ctx->attr + + le16_to_cpu(ctx->attr->value_offset)); + /* + * Do not mark times dirty to avoid + * overwriting them when the inode is closed. + */ + fn->creation_time + = cpu_to_le64(times[0]); + if (size >= 16) + fn->last_data_change_time + = cpu_to_le64(times[1]); + if (size >= 24) + fn->last_access_time + = cpu_to_le64(times[2]); + fn->last_mft_change_time = now; + cnt++; + } + if (cnt) + ret = 0; + else { + ntfs_log_perror("Failed to get file names (inode %lld)", + (long long)ni->mft_no); + } + } + ntfs_attr_put_search_ctx(ctx); + } + } else + if (size < 8) + errno = ERANGE; + else + errno = EEXIST; + return (ret); } #endif /* HAVE_SETXATTR */ diff --git a/source/libntfs/inode.h b/source/libntfs/inode.h index c9c35130..3abc878c 100644 --- a/source/libntfs/inode.h +++ b/source/libntfs/inode.h @@ -40,16 +40,16 @@ typedef struct _ntfs_inode ntfs_inode; * (f) = files only, (d) = directories only */ typedef enum { - NI_Dirty, /* 1: Mft record needs to be written to disk. */ + NI_Dirty, /* 1: Mft record needs to be written to disk. */ - /* The NI_AttrList* tests only make sense for base inodes. */ - NI_AttrList, /* 1: Mft record contains an attribute list. */ - NI_AttrListDirty, /* 1: Attribute list needs to be written to the + /* The NI_AttrList* tests only make sense for base inodes. */ + NI_AttrList, /* 1: Mft record contains an attribute list. */ + NI_AttrListDirty, /* 1: Attribute list needs to be written to the mft record and then to disk. */ - NI_FileNameDirty, /* 1: FILE_NAME attributes need to be updated + NI_FileNameDirty, /* 1: FILE_NAME attributes need to be updated in the index. */ - NI_v3_Extensions, /* 1: JPA v3.x extensions present. */ - NI_TimesDirty, /* 1: Times need to be updated */ + NI_v3_Extensions, /* 1: JPA v3.x extensions present. */ + NI_TimesDirty, /* 1: Times need to be updated */ } ntfs_inode_state_bits; #define test_nino_flag(ni, flag) test_bit(NI_##flag, (ni)->state) @@ -102,69 +102,69 @@ typedef enum { * inode. */ struct _ntfs_inode { - u64 mft_no; /* Inode / mft record number. */ - MFT_RECORD *mrec; /* The actual mft record of the inode. */ - ntfs_volume *vol; /* Pointer to the ntfs volume of this inode. */ - unsigned long state; /* NTFS specific flags describing this inode. + u64 mft_no; /* Inode / mft record number. */ + MFT_RECORD *mrec; /* The actual mft record of the inode. */ + ntfs_volume *vol; /* Pointer to the ntfs volume of this inode. */ + unsigned long state; /* NTFS specific flags describing this inode. See ntfs_inode_state_bits above. */ - FILE_ATTR_FLAGS flags; /* Flags describing the file. + FILE_ATTR_FLAGS flags; /* Flags describing the file. (Copy from STANDARD_INFORMATION) */ - /* - * Attribute list support (for use by the attribute lookup functions). - * Setup during ntfs_open_inode() for all inodes with attribute lists. - * Only valid if NI_AttrList is set in state. - */ - u32 attr_list_size; /* Length of attribute list value in bytes. */ - u8 *attr_list; /* Attribute list value itself. */ - /* Below fields are always valid. */ - s32 nr_extents; /* For a base mft record, the number of + /* + * Attribute list support (for use by the attribute lookup functions). + * Setup during ntfs_open_inode() for all inodes with attribute lists. + * Only valid if NI_AttrList is set in state. + */ + u32 attr_list_size; /* Length of attribute list value in bytes. */ + u8 *attr_list; /* Attribute list value itself. */ + /* Below fields are always valid. */ + s32 nr_extents; /* For a base mft record, the number of attached extent inodes (0 if none), for extent records this is -1. */ - union { /* This union is only used if nr_extents != 0. */ - ntfs_inode **extent_nis;/* For nr_extents > 0, array of the + union { /* This union is only used if nr_extents != 0. */ + ntfs_inode **extent_nis;/* For nr_extents > 0, array of the ntfs inodes of the extent mft records belonging to this base inode which have been loaded. */ - ntfs_inode *base_ni; /* For nr_extents == -1, the ntfs + ntfs_inode *base_ni; /* For nr_extents == -1, the ntfs inode of the base mft record. */ - }; + }; - /* Below fields are valid only for base inode. */ + /* Below fields are valid only for base inode. */ - /* - * These two fields are used to sync filename index and guaranteed to be - * correct, however value in index itself maybe wrong (windows itself - * do not update them properly). - */ - s64 data_size; /* Data size of unnamed DATA attribute. */ - s64 allocated_size; /* Allocated size stored in the filename + /* + * These two fields are used to sync filename index and guaranteed to be + * correct, however value in index itself maybe wrong (windows itself + * do not update them properly). + */ + s64 data_size; /* Data size of unnamed DATA attribute. */ + s64 allocated_size; /* Allocated size stored in the filename index. (NOTE: Equal to allocated size of the unnamed data attribute for normal or encrypted files and to compressed size of the unnamed data attribute for sparse or compressed files.) */ - /* - * These four fields are copy of relevant fields from - * STANDARD_INFORMATION attribute and used to sync it and FILE_NAME - * attribute in the index. - */ - time_t creation_time; - time_t last_data_change_time; - time_t last_mft_change_time; - time_t last_access_time; - /* NTFS 3.x extensions added by JPA */ - /* only if NI_v3_Extensions is set in state */ - le32 owner_id; - le32 security_id; - le64 quota_charged; - le64 usn; + /* + * These four fields are copy of relevant fields from + * STANDARD_INFORMATION attribute and used to sync it and FILE_NAME + * attribute in the index. + */ + time_t creation_time; + time_t last_data_change_time; + time_t last_mft_change_time; + time_t last_access_time; + /* NTFS 3.x extensions added by JPA */ + /* only if NI_v3_Extensions is set in state */ + le32 owner_id; + le32 security_id; + le64 quota_charged; + le64 usn; }; typedef enum { - NTFS_UPDATE_ATIME = 1 << 0, - NTFS_UPDATE_MTIME = 1 << 1, - NTFS_UPDATE_CTIME = 1 << 2, + NTFS_UPDATE_ATIME = 1 << 0, + NTFS_UPDATE_MTIME = 1 << 1, + NTFS_UPDATE_CTIME = 1 << 2, } ntfs_time_update_flags; #define NTFS_UPDATE_MCTIME (NTFS_UPDATE_MTIME | NTFS_UPDATE_CTIME) @@ -179,7 +179,7 @@ extern ntfs_inode *ntfs_inode_open(ntfs_volume *vol, const MFT_REF mref); extern int ntfs_inode_close(ntfs_inode *ni); extern ntfs_inode *ntfs_extent_inode_open(ntfs_inode *base_ni, - const MFT_REF mref); + const MFT_REF mref); extern int ntfs_inode_attach_all_extents(ntfs_inode *ni); @@ -196,8 +196,8 @@ extern int ntfs_inode_free_space(ntfs_inode *ni, int size); extern int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *a); extern int ntfs_inode_get_times(const char *path, char *value, - size_t size, ntfs_inode *ni); + size_t size, ntfs_inode *ni); extern int ntfs_inode_set_times(const char *path, const char *value, - size_t size, int flags, ntfs_inode *ni); + size_t size, int flags, ntfs_inode *ni); #endif /* defined _NTFS_INODE_H */ diff --git a/source/libntfs/layout.h b/source/libntfs/layout.h index 790bd186..8670557e 100644 --- a/source/libntfs/layout.h +++ b/source/libntfs/layout.h @@ -47,58 +47,51 @@ * struct BIOS_PARAMETER_BLOCK - BIOS parameter block (bpb) structure. */ typedef struct { - u16 bytes_per_sector; /* Size of a sector in bytes. */ - u8 sectors_per_cluster; /* Size of a cluster in sectors. */ - u16 reserved_sectors; /* zero */ - u8 fats; /* zero */ - u16 root_entries; /* zero */ - u16 sectors; /* zero */ - u8 media_type; /* 0xf8 = hard disk */ - u16 sectors_per_fat; /* zero */ - /*0x0d*/ - u16 sectors_per_track; /* Required to boot Windows. */ - /*0x0f*/ - u16 heads; /* Required to boot Windows. */ - /*0x11*/ - u32 hidden_sectors; /* Offset to the start of the partition + u16 bytes_per_sector; /* Size of a sector in bytes. */ + u8 sectors_per_cluster; /* Size of a cluster in sectors. */ + u16 reserved_sectors; /* zero */ + u8 fats; /* zero */ + u16 root_entries; /* zero */ + u16 sectors; /* zero */ + u8 media_type; /* 0xf8 = hard disk */ + u16 sectors_per_fat; /* zero */ +/*0x0d*/u16 sectors_per_track; /* Required to boot Windows. */ +/*0x0f*/u16 heads; /* Required to boot Windows. */ +/*0x11*/u32 hidden_sectors; /* Offset to the start of the partition relative to the disk in sectors. Required to boot Windows. */ - /*0x15*/ - u32 large_sectors; /* zero */ - /* sizeof() = 25 (0x19) bytes */ +/*0x15*/u32 large_sectors; /* zero */ +/* sizeof() = 25 (0x19) bytes */ } __attribute__((__packed__)) BIOS_PARAMETER_BLOCK; /** * struct NTFS_BOOT_SECTOR - NTFS boot sector structure. */ typedef struct { - u8 jump[3]; /* Irrelevant (jump to boot up code).*/ - u64 oem_id; /* Magic "NTFS ". */ - /*0x0b*/ - BIOS_PARAMETER_BLOCK bpb; /* See BIOS_PARAMETER_BLOCK. */ - u8 physical_drive; /* 0x00 floppy, 0x80 hard disk */ - u8 current_head; /* zero */ - u8 extended_boot_signature; /* 0x80 */ - u8 reserved2; /* zero */ - /*0x28*/ - s64 number_of_sectors; /* Number of sectors in volume. Gives + u8 jump[3]; /* Irrelevant (jump to boot up code).*/ + u64 oem_id; /* Magic "NTFS ". */ +/*0x0b*/BIOS_PARAMETER_BLOCK bpb; /* See BIOS_PARAMETER_BLOCK. */ + u8 physical_drive; /* 0x00 floppy, 0x80 hard disk */ + u8 current_head; /* zero */ + u8 extended_boot_signature; /* 0x80 */ + u8 reserved2; /* zero */ +/*0x28*/s64 number_of_sectors; /* Number of sectors in volume. Gives maximum volume size of 2^63 sectors. Assuming standard sector size of 512 bytes, the maximum byte size is approx. 4.7x10^21 bytes. (-; */ - s64 mft_lcn; /* Cluster location of mft data. */ - s64 mftmirr_lcn; /* Cluster location of copy of mft. */ - s8 clusters_per_mft_record; /* Mft record size in clusters. */ - u8 reserved0[3]; /* zero */ - s8 clusters_per_index_record; /* Index block size in clusters. */ - u8 reserved1[3]; /* zero */ - u64 volume_serial_number; /* Irrelevant (serial number). */ - u32 checksum; /* Boot sector checksum. */ - /*0x54*/ - u8 bootstrap[426]; /* Irrelevant (boot up code). */ - u16 end_of_sector_marker; /* End of bootsector magic. Always is + s64 mft_lcn; /* Cluster location of mft data. */ + s64 mftmirr_lcn; /* Cluster location of copy of mft. */ + s8 clusters_per_mft_record; /* Mft record size in clusters. */ + u8 reserved0[3]; /* zero */ + s8 clusters_per_index_record; /* Index block size in clusters. */ + u8 reserved1[3]; /* zero */ + u64 volume_serial_number; /* Irrelevant (serial number). */ + u32 checksum; /* Boot sector checksum. */ +/*0x54*/u8 bootstrap[426]; /* Irrelevant (boot up code). */ + u16 end_of_sector_marker; /* End of bootsector magic. Always is 0xaa55 in little endian. */ - /* sizeof() = 512 (0x200) bytes */ +/* sizeof() = 512 (0x200) bytes */ } __attribute__((__packed__)) NTFS_BOOT_SECTOR; /** @@ -108,28 +101,28 @@ typedef struct { * records (like mft records for example). */ typedef enum { - /* Found in $MFT/$DATA. */ - magic_FILE = const_cpu_to_le32(0x454c4946), /* Mft entry. */ - magic_INDX = const_cpu_to_le32(0x58444e49), /* Index buffer. */ - magic_HOLE = const_cpu_to_le32(0x454c4f48), /* ? (NTFS 3.0+?) */ + /* Found in $MFT/$DATA. */ + magic_FILE = const_cpu_to_le32(0x454c4946), /* Mft entry. */ + magic_INDX = const_cpu_to_le32(0x58444e49), /* Index buffer. */ + magic_HOLE = const_cpu_to_le32(0x454c4f48), /* ? (NTFS 3.0+?) */ - /* Found in $LogFile/$DATA. */ - magic_RSTR = const_cpu_to_le32(0x52545352), /* Restart page. */ - magic_RCRD = const_cpu_to_le32(0x44524352), /* Log record page. */ + /* Found in $LogFile/$DATA. */ + magic_RSTR = const_cpu_to_le32(0x52545352), /* Restart page. */ + magic_RCRD = const_cpu_to_le32(0x44524352), /* Log record page. */ - /* Found in $LogFile/$DATA. (May be found in $MFT/$DATA, also?) */ - magic_CHKD = const_cpu_to_le32(0x444b4843), /* Modified by chkdsk. */ + /* Found in $LogFile/$DATA. (May be found in $MFT/$DATA, also?) */ + magic_CHKD = const_cpu_to_le32(0x444b4843), /* Modified by chkdsk. */ - /* Found in all ntfs record containing records. */ - magic_BAAD = const_cpu_to_le32(0x44414142), /* Failed multi sector + /* Found in all ntfs record containing records. */ + magic_BAAD = const_cpu_to_le32(0x44414142), /* Failed multi sector transfer was detected. */ - /* - * Found in $LogFile/$DATA when a page is full or 0xff bytes and is - * thus not initialized. User has to initialize the page before using - * it. - */ - magic_empty = const_cpu_to_le32(0xffffffff),/* Record is empty and has + /* + * Found in $LogFile/$DATA when a page is full or 0xff bytes and is + * thus not initialized. User has to initialize the page before using + * it. + */ + magic_empty = const_cpu_to_le32(0xffffffff),/* Record is empty and has to be initialized before it can be used. */ } NTFS_RECORD_TYPES; @@ -190,11 +183,11 @@ typedef enum { * (usa_count * 2) has to be less than or equal to 510. */ typedef struct { - NTFS_RECORD_TYPES magic;/* A four-byte magic identifying the + NTFS_RECORD_TYPES magic;/* A four-byte magic identifying the record type and/or status. */ - u16 usa_ofs; /* Offset to the Update Sequence Array (usa) + u16 usa_ofs; /* Offset to the Update Sequence Array (usa) from the start of the ntfs record. */ - u16 usa_count; /* Number of u16 sized entries in the usa + u16 usa_count; /* Number of u16 sized entries in the usa including the Update Sequence Number (usn), thus the number of fixups is the usa_count minus 1. */ @@ -209,41 +202,41 @@ typedef struct { * always equal to their mft record number and it is never modified. */ typedef enum { - FILE_MFT = 0, /* Master file table (mft). Data attribute + FILE_MFT = 0, /* Master file table (mft). Data attribute contains the entries and bitmap attribute records which ones are in use (bit==1). */ - FILE_MFTMirr = 1, /* Mft mirror: copy of first four mft records + FILE_MFTMirr = 1, /* Mft mirror: copy of first four mft records in data attribute. If cluster size > 4kiB, copy of first N mft records, with N = cluster_size / mft_record_size. */ - FILE_LogFile = 2, /* Journalling log in data attribute. */ - FILE_Volume = 3, /* Volume name attribute and volume information + FILE_LogFile = 2, /* Journalling log in data attribute. */ + FILE_Volume = 3, /* Volume name attribute and volume information attribute (flags and ntfs version). Windows refers to this file as volume DASD (Direct Access Storage Device). */ - FILE_AttrDef = 4, /* Array of attribute definitions in data + FILE_AttrDef = 4, /* Array of attribute definitions in data attribute. */ - FILE_root = 5, /* Root directory. */ - FILE_Bitmap = 6, /* Allocation bitmap of all clusters (lcns) in + FILE_root = 5, /* Root directory. */ + FILE_Bitmap = 6, /* Allocation bitmap of all clusters (lcns) in data attribute. */ - FILE_Boot = 7, /* Boot sector (always at cluster 0) in data + FILE_Boot = 7, /* Boot sector (always at cluster 0) in data attribute. */ - FILE_BadClus = 8, /* Contains all bad clusters in the non-resident + FILE_BadClus = 8, /* Contains all bad clusters in the non-resident data attribute. */ - FILE_Secure = 9, /* Shared security descriptors in data attribute + FILE_Secure = 9, /* Shared security descriptors in data attribute and two indexes into the descriptors. Appeared in Windows 2000. Before that, this file was named $Quota but was unused. */ - FILE_UpCase = 10, /* Uppercase equivalents of all 65536 Unicode + FILE_UpCase = 10, /* Uppercase equivalents of all 65536 Unicode characters in data attribute. */ - FILE_Extend = 11, /* Directory containing other system files (eg. + FILE_Extend = 11, /* Directory containing other system files (eg. $ObjId, $Quota, $Reparse and $UsnJrnl). This is new to NTFS3.0. */ - FILE_reserved12 = 12, /* Reserved for future use (records 12-15). */ - FILE_reserved13 = 13, - FILE_reserved14 = 14, - FILE_reserved15 = 15, - FILE_first_user = 16, /* First user file, used as test limit for + FILE_reserved12 = 12, /* Reserved for future use (records 12-15). */ + FILE_reserved13 = 13, + FILE_reserved14 = 14, + FILE_reserved15 = 15, + FILE_first_user = 16, /* First user file, used as test limit for whether to allow opening a file or not. */ } NTFS_SYSTEM_FILES; @@ -252,7 +245,7 @@ typedef enum { * * These are the so far known MFT_RECORD_* flags (16-bit) which contain * information about the mft record in which they are present. - * + * * MFT_RECORD_IS_4 exists on all $Extend sub-files. * It seems that it marks it is a metadata file with MFT record >24, however, * it is unknown if it is limited to metadata files only. @@ -262,11 +255,11 @@ typedef enum { * than "$I30". It is unknown if it is limited to metadata files only. */ typedef enum { - MFT_RECORD_IN_USE = const_cpu_to_le16(0x0001), - MFT_RECORD_IS_DIRECTORY = const_cpu_to_le16(0x0002), - MFT_RECORD_IS_4 = const_cpu_to_le16(0x0004), - MFT_RECORD_IS_VIEW_INDEX = const_cpu_to_le16(0x0008), - MFT_REC_SPACE_FILLER = 0xffff, /* Just to make flags + MFT_RECORD_IN_USE = const_cpu_to_le16(0x0001), + MFT_RECORD_IS_DIRECTORY = const_cpu_to_le16(0x0002), + MFT_RECORD_IS_4 = const_cpu_to_le16(0x0004), + MFT_RECORD_IS_VIEW_INDEX = const_cpu_to_le16(0x0008), + MFT_REC_SPACE_FILLER = 0xffff, /* Just to make flags 16-bit. */ } __attribute__((__packed__)) MFT_RECORD_FLAGS; @@ -343,23 +336,20 @@ typedef u64 MFT_REF; * other members of the attribute structure are present. */ typedef struct { - /*Ofs*/ - /* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ - NTFS_RECORD_TYPES magic;/* Usually the magic is "FILE". */ - u16 usa_ofs; /* See NTFS_RECORD definition above. */ - u16 usa_count; /* See NTFS_RECORD definition above. */ +/*Ofs*/ +/* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ + NTFS_RECORD_TYPES magic;/* Usually the magic is "FILE". */ + u16 usa_ofs; /* See NTFS_RECORD definition above. */ + u16 usa_count; /* See NTFS_RECORD definition above. */ - /* 8*/ - LSN lsn; /* $LogFile sequence number for this record. +/* 8*/ LSN lsn; /* $LogFile sequence number for this record. Changed every time the record is modified. */ - /* 16*/ - u16 sequence_number; /* Number of times this mft record has been +/* 16*/ u16 sequence_number; /* Number of times this mft record has been reused. (See description for MFT_REF above.) NOTE: The increment (skipping zero) is done when the file is deleted. NOTE: If this is zero it is left zero. */ - /* 18*/ - u16 link_count; /* Number of hard links, i.e. the number of +/* 18*/ u16 link_count; /* Number of hard links, i.e. the number of directory entries referencing this record. NOTE: Only used in mft base records. NOTE: When deleting a directory entry we @@ -369,23 +359,18 @@ typedef struct { directory entry from the mft record and decrement the link_count. FIXME: Careful with Win32 + DOS names! */ - /* 20*/ - u16 attrs_offset; /* Byte offset to the first attribute in this +/* 20*/ u16 attrs_offset; /* Byte offset to the first attribute in this mft record from the start of the mft record. NOTE: Must be aligned to 8-byte boundary. */ - /* 22*/ - MFT_RECORD_FLAGS flags; /* Bit array of MFT_RECORD_FLAGS. When a file +/* 22*/ MFT_RECORD_FLAGS flags; /* Bit array of MFT_RECORD_FLAGS. When a file is deleted, the MFT_RECORD_IN_USE flag is set to zero. */ - /* 24*/ - u32 bytes_in_use; /* Number of bytes used in this mft record. +/* 24*/ u32 bytes_in_use; /* Number of bytes used in this mft record. NOTE: Must be aligned to 8-byte boundary. */ - /* 28*/ - u32 bytes_allocated; /* Number of bytes allocated for this mft +/* 28*/ u32 bytes_allocated; /* Number of bytes allocated for this mft record. This should be equal to the mft record size. */ - /* 32*/ - MFT_REF base_mft_record; /* This is zero for base mft records. +/* 32*/ MFT_REF base_mft_record; /* This is zero for base mft records. When it is not zero it is a mft reference pointing to the base mft record to which this record belongs (this is then used to @@ -397,29 +382,26 @@ typedef struct { attribute list also means finding the other potential extents, belonging to the non-base mft record). */ - /* 40*/ - u16 next_attr_instance; /* The instance number that will be +/* 40*/ u16 next_attr_instance; /* The instance number that will be assigned to the next attribute added to this mft record. NOTE: Incremented each time after it is used. NOTE: Every time the mft record is reused this number is set to zero. NOTE: The first instance number is always 0. */ - /* The below fields are specific to NTFS 3.1+ (Windows XP and above): */ - /* 42*/ - u16 reserved; /* Reserved/alignment. */ - /* 44*/ - u32 mft_record_number; /* Number of this mft record. */ - /* sizeof() = 48 bytes */ - /* - * When (re)using the mft record, we place the update sequence array at this - * offset, i.e. before we start with the attributes. This also makes sense, - * otherwise we could run into problems with the update sequence array - * containing in itself the last two bytes of a sector which would mean that - * multi sector transfer protection wouldn't work. As you can't protect data - * by overwriting it since you then can't get it back... - * When reading we obviously use the data from the ntfs record header. - */ +/* The below fields are specific to NTFS 3.1+ (Windows XP and above): */ +/* 42*/ u16 reserved; /* Reserved/alignment. */ +/* 44*/ u32 mft_record_number; /* Number of this mft record. */ +/* sizeof() = 48 bytes */ +/* + * When (re)using the mft record, we place the update sequence array at this + * offset, i.e. before we start with the attributes. This also makes sense, + * otherwise we could run into problems with the update sequence array + * containing in itself the last two bytes of a sector which would mean that + * multi sector transfer protection wouldn't work. As you can't protect data + * by overwriting it since you then can't get it back... + * When reading we obviously use the data from the ntfs record header. + */ } __attribute__((__packed__)) MFT_RECORD; /** @@ -428,23 +410,20 @@ typedef struct { * This is the version without the NTFS 3.1+ specific fields. */ typedef struct { - /*Ofs*/ - /* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ - NTFS_RECORD_TYPES magic;/* Usually the magic is "FILE". */ - u16 usa_ofs; /* See NTFS_RECORD definition above. */ - u16 usa_count; /* See NTFS_RECORD definition above. */ +/*Ofs*/ +/* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ + NTFS_RECORD_TYPES magic;/* Usually the magic is "FILE". */ + u16 usa_ofs; /* See NTFS_RECORD definition above. */ + u16 usa_count; /* See NTFS_RECORD definition above. */ - /* 8*/ - LSN lsn; /* $LogFile sequence number for this record. +/* 8*/ LSN lsn; /* $LogFile sequence number for this record. Changed every time the record is modified. */ - /* 16*/ - u16 sequence_number; /* Number of times this mft record has been +/* 16*/ u16 sequence_number; /* Number of times this mft record has been reused. (See description for MFT_REF above.) NOTE: The increment (skipping zero) is done when the file is deleted. NOTE: If this is zero it is left zero. */ - /* 18*/ - u16 link_count; /* Number of hard links, i.e. the number of +/* 18*/ u16 link_count; /* Number of hard links, i.e. the number of directory entries referencing this record. NOTE: Only used in mft base records. NOTE: When deleting a directory entry we @@ -454,23 +433,18 @@ typedef struct { directory entry from the mft record and decrement the link_count. FIXME: Careful with Win32 + DOS names! */ - /* 20*/ - u16 attrs_offset; /* Byte offset to the first attribute in this +/* 20*/ u16 attrs_offset; /* Byte offset to the first attribute in this mft record from the start of the mft record. NOTE: Must be aligned to 8-byte boundary. */ - /* 22*/ - MFT_RECORD_FLAGS flags; /* Bit array of MFT_RECORD_FLAGS. When a file +/* 22*/ MFT_RECORD_FLAGS flags; /* Bit array of MFT_RECORD_FLAGS. When a file is deleted, the MFT_RECORD_IN_USE flag is set to zero. */ - /* 24*/ - u32 bytes_in_use; /* Number of bytes used in this mft record. +/* 24*/ u32 bytes_in_use; /* Number of bytes used in this mft record. NOTE: Must be aligned to 8-byte boundary. */ - /* 28*/ - u32 bytes_allocated; /* Number of bytes allocated for this mft +/* 28*/ u32 bytes_allocated; /* Number of bytes allocated for this mft record. This should be equal to the mft record size. */ - /* 32*/ - MFT_REF base_mft_record; /* This is zero for base mft records. +/* 32*/ MFT_REF base_mft_record; /* This is zero for base mft records. When it is not zero it is a mft reference pointing to the base mft record to which this record belongs (this is then used to @@ -482,24 +456,23 @@ typedef struct { attribute list also means finding the other potential extents, belonging to the non-base mft record). */ - /* 40*/ - u16 next_attr_instance; /* The instance number that will be +/* 40*/ u16 next_attr_instance; /* The instance number that will be assigned to the next attribute added to this mft record. NOTE: Incremented each time after it is used. NOTE: Every time the mft record is reused this number is set to zero. NOTE: The first instance number is always 0. */ - /* sizeof() = 42 bytes */ - /* - * When (re)using the mft record, we place the update sequence array at this - * offset, i.e. before we start with the attributes. This also makes sense, - * otherwise we could run into problems with the update sequence array - * containing in itself the last two bytes of a sector which would mean that - * multi sector transfer protection wouldn't work. As you can't protect data - * by overwriting it since you then can't get it back... - * When reading we obviously use the data from the ntfs record header. - */ +/* sizeof() = 42 bytes */ +/* + * When (re)using the mft record, we place the update sequence array at this + * offset, i.e. before we start with the attributes. This also makes sense, + * otherwise we could run into problems with the update sequence array + * containing in itself the last two bytes of a sector which would mean that + * multi sector transfer protection wouldn't work. As you can't protect data + * by overwriting it since you then can't get it back... + * When reading we obviously use the data from the ntfs record header. + */ } __attribute__((__packed__)) MFT_RECORD_OLD; /** @@ -508,31 +481,31 @@ typedef struct { * Each attribute type has a corresponding attribute name (Unicode string of * maximum 64 character length) as described by the attribute definitions * present in the data attribute of the $AttrDef system file. - * + * * On NTFS 3.0 volumes the names are just as the types are named in the below * enum exchanging AT_ for the dollar sign ($). If that isn't a revealing * choice of symbol... (-; */ typedef enum { - AT_UNUSED = const_cpu_to_le32( 0), - AT_STANDARD_INFORMATION = const_cpu_to_le32( 0x10), - AT_ATTRIBUTE_LIST = const_cpu_to_le32( 0x20), - AT_FILE_NAME = const_cpu_to_le32( 0x30), - AT_OBJECT_ID = const_cpu_to_le32( 0x40), - AT_SECURITY_DESCRIPTOR = const_cpu_to_le32( 0x50), - AT_VOLUME_NAME = const_cpu_to_le32( 0x60), - AT_VOLUME_INFORMATION = const_cpu_to_le32( 0x70), - AT_DATA = const_cpu_to_le32( 0x80), - AT_INDEX_ROOT = const_cpu_to_le32( 0x90), - AT_INDEX_ALLOCATION = const_cpu_to_le32( 0xa0), - AT_BITMAP = const_cpu_to_le32( 0xb0), - AT_REPARSE_POINT = const_cpu_to_le32( 0xc0), - AT_EA_INFORMATION = const_cpu_to_le32( 0xd0), - AT_EA = const_cpu_to_le32( 0xe0), - AT_PROPERTY_SET = const_cpu_to_le32( 0xf0), - AT_LOGGED_UTILITY_STREAM = const_cpu_to_le32( 0x100), - AT_FIRST_USER_DEFINED_ATTRIBUTE = const_cpu_to_le32( 0x1000), - AT_END = const_cpu_to_le32(0xffffffff), + AT_UNUSED = const_cpu_to_le32( 0), + AT_STANDARD_INFORMATION = const_cpu_to_le32( 0x10), + AT_ATTRIBUTE_LIST = const_cpu_to_le32( 0x20), + AT_FILE_NAME = const_cpu_to_le32( 0x30), + AT_OBJECT_ID = const_cpu_to_le32( 0x40), + AT_SECURITY_DESCRIPTOR = const_cpu_to_le32( 0x50), + AT_VOLUME_NAME = const_cpu_to_le32( 0x60), + AT_VOLUME_INFORMATION = const_cpu_to_le32( 0x70), + AT_DATA = const_cpu_to_le32( 0x80), + AT_INDEX_ROOT = const_cpu_to_le32( 0x90), + AT_INDEX_ALLOCATION = const_cpu_to_le32( 0xa0), + AT_BITMAP = const_cpu_to_le32( 0xb0), + AT_REPARSE_POINT = const_cpu_to_le32( 0xc0), + AT_EA_INFORMATION = const_cpu_to_le32( 0xd0), + AT_EA = const_cpu_to_le32( 0xe0), + AT_PROPERTY_SET = const_cpu_to_le32( 0xf0), + AT_LOGGED_UTILITY_STREAM = const_cpu_to_le32( 0x100), + AT_FIRST_USER_DEFINED_ATTRIBUTE = const_cpu_to_le32( 0x1000), + AT_END = const_cpu_to_le32(0xffffffff), } ATTR_TYPES; /** @@ -573,21 +546,21 @@ typedef enum { * equal then the second u32 values would be compared, etc. */ typedef enum { - COLLATION_BINARY = const_cpu_to_le32(0), /* Collate by binary + COLLATION_BINARY = const_cpu_to_le32(0), /* Collate by binary compare where the first byte is most significant. */ - COLLATION_FILE_NAME = const_cpu_to_le32(1), /* Collate file names + COLLATION_FILE_NAME = const_cpu_to_le32(1), /* Collate file names as Unicode strings. */ - COLLATION_UNICODE_STRING = const_cpu_to_le32(2), /* Collate Unicode + COLLATION_UNICODE_STRING = const_cpu_to_le32(2), /* Collate Unicode strings by comparing their binary Unicode values, except that when a character can be uppercased, the upper case value collates before the lower case one. */ - COLLATION_NTOFS_ULONG = const_cpu_to_le32(16), - COLLATION_NTOFS_SID = const_cpu_to_le32(17), - COLLATION_NTOFS_SECURITY_HASH = const_cpu_to_le32(18), - COLLATION_NTOFS_ULONGS = const_cpu_to_le32(19), + COLLATION_NTOFS_ULONG = const_cpu_to_le32(16), + COLLATION_NTOFS_SID = const_cpu_to_le32(17), + COLLATION_NTOFS_SECURITY_HASH = const_cpu_to_le32(18), + COLLATION_NTOFS_ULONGS = const_cpu_to_le32(19), } COLLATION_RULES; /** @@ -601,25 +574,25 @@ typedef enum { * NT4. */ typedef enum { - ATTR_DEF_INDEXABLE = const_cpu_to_le32(0x02), /* Attribute can be + ATTR_DEF_INDEXABLE = const_cpu_to_le32(0x02), /* Attribute can be indexed. */ - ATTR_DEF_MULTIPLE = const_cpu_to_le32(0x04), /* Attribute type + ATTR_DEF_MULTIPLE = const_cpu_to_le32(0x04), /* Attribute type can be present multiple times in the mft records of an inode. */ - ATTR_DEF_NOT_ZERO = const_cpu_to_le32(0x08), /* Attribute value + ATTR_DEF_NOT_ZERO = const_cpu_to_le32(0x08), /* Attribute value must contain at least one non-zero byte. */ - ATTR_DEF_INDEXED_UNIQUE = const_cpu_to_le32(0x10), /* Attribute must be + ATTR_DEF_INDEXED_UNIQUE = const_cpu_to_le32(0x10), /* Attribute must be indexed and the attribute value must be unique for the attribute type in all of the mft records of an inode. */ - ATTR_DEF_NAMED_UNIQUE = const_cpu_to_le32(0x20), /* Attribute must be + ATTR_DEF_NAMED_UNIQUE = const_cpu_to_le32(0x20), /* Attribute must be named and the name must be unique for the attribute type in all of the mft records of an inode. */ - ATTR_DEF_RESIDENT = const_cpu_to_le32(0x40), /* Attribute must be + ATTR_DEF_RESIDENT = const_cpu_to_le32(0x40), /* Attribute must be resident. */ - ATTR_DEF_ALWAYS_LOG = const_cpu_to_le32(0x80), /* Always log + ATTR_DEF_ALWAYS_LOG = const_cpu_to_le32(0x80), /* Always log modifications to this attribute, regardless of whether it is resident or non-resident. Without this, only log @@ -639,36 +612,29 @@ typedef enum { * actual bits are unknown. */ typedef struct { - /*hex ofs*/ - /* 0*/ - ntfschar name[0x40]; /* Unicode name of the attribute. Zero +/*hex ofs*/ +/* 0*/ ntfschar name[0x40]; /* Unicode name of the attribute. Zero terminated. */ - /* 80*/ - ATTR_TYPES type; /* Type of the attribute. */ - /* 84*/ - u32 display_rule; /* Default display rule. +/* 80*/ ATTR_TYPES type; /* Type of the attribute. */ +/* 84*/ u32 display_rule; /* Default display rule. FIXME: What does it mean? (AIA) */ - /* 88*/ - COLLATION_RULES collation_rule; /* Default collation rule. */ - /* 8c*/ - ATTR_DEF_FLAGS flags; /* Flags describing the attribute. */ - /* 90*/ - s64 min_size; /* Optional minimum attribute size. */ - /* 98*/ - s64 max_size; /* Maximum size of attribute. */ - /* sizeof() = 0xa0 or 160 bytes */ +/* 88*/ COLLATION_RULES collation_rule; /* Default collation rule. */ +/* 8c*/ ATTR_DEF_FLAGS flags; /* Flags describing the attribute. */ +/* 90*/ s64 min_size; /* Optional minimum attribute size. */ +/* 98*/ s64 max_size; /* Maximum size of attribute. */ +/* sizeof() = 0xa0 or 160 bytes */ } __attribute__((__packed__)) ATTR_DEF; /** * enum ATTR_FLAGS - Attribute flags (16-bit). */ typedef enum { - ATTR_IS_COMPRESSED = const_cpu_to_le16(0x0001), - ATTR_COMPRESSION_MASK = const_cpu_to_le16(0x00ff), /* Compression + ATTR_IS_COMPRESSED = const_cpu_to_le16(0x0001), + ATTR_COMPRESSION_MASK = const_cpu_to_le16(0x00ff), /* Compression method mask. Also, first illegal value. */ - ATTR_IS_ENCRYPTED = const_cpu_to_le16(0x4000), - ATTR_IS_SPARSE = const_cpu_to_le16(0x8000), + ATTR_IS_ENCRYPTED = const_cpu_to_le16(0x4000), + ATTR_IS_SPARSE = const_cpu_to_le16(0x8000), } __attribute__((__packed__)) ATTR_FLAGS; /* @@ -742,7 +708,7 @@ typedef enum { * enum RESIDENT_ATTR_FLAGS - Flags of resident attributes (8-bit). */ typedef enum { - RESIDENT_ATTR_IS_INDEXED = 0x01, /* Attribute is referenced in an index + RESIDENT_ATTR_IS_INDEXED = 0x01, /* Attribute is referenced in an index (has implications for deleting and modifying the attribute). */ } __attribute__((__packed__)) RESIDENT_ATTR_FLAGS; @@ -753,21 +719,16 @@ typedef enum { * Always aligned to 8-byte boundary. */ typedef struct { - /*Ofs*/ - /* 0*/ - ATTR_TYPES type; /* The (32-bit) type of the attribute. */ - /* 4*/ - u32 length; /* Byte size of the resident part of the +/*Ofs*/ +/* 0*/ ATTR_TYPES type; /* The (32-bit) type of the attribute. */ +/* 4*/ u32 length; /* Byte size of the resident part of the attribute (aligned to 8-byte boundary). Used to get to the next attribute. */ - /* 8*/ - u8 non_resident; /* If 0, attribute is resident. +/* 8*/ u8 non_resident; /* If 0, attribute is resident. If 1, attribute is non-resident. */ - /* 9*/ - u8 name_length; /* Unicode character size of name of attribute. +/* 9*/ u8 name_length; /* Unicode character size of name of attribute. 0 if unnamed. */ - /* 10*/ - u16 name_offset; /* If name_length != 0, the byte offset to the +/* 10*/ u16 name_offset; /* If name_length != 0, the byte offset to the beginning of the name from the attribute record. Note that the name is stored as a Unicode string. When creating, place offset @@ -776,72 +737,58 @@ typedef struct { array, resident and non-resident attributes respectively, aligning to an 8-byte boundary. */ - /* 12*/ - ATTR_FLAGS flags; /* Flags describing the attribute. */ - /* 14*/ - u16 instance; /* The instance of this attribute record. This +/* 12*/ ATTR_FLAGS flags; /* Flags describing the attribute. */ +/* 14*/ u16 instance; /* The instance of this attribute record. This number is unique within this mft record (see MFT_RECORD/next_attribute_instance notes above for more details). */ - /* 16*/ - union { - /* Resident attributes. */ - struct { - /* 16 */ - u32 value_length; /* Byte size of attribute value. */ - /* 20 */ - u16 value_offset; /* Byte offset of the attribute +/* 16*/ union { + /* Resident attributes. */ + struct { +/* 16 */ u32 value_length; /* Byte size of attribute value. */ +/* 20 */ u16 value_offset; /* Byte offset of the attribute value from the start of the attribute record. When creating, align to 8-byte boundary if we have a name present as this might not have a length of a multiple of 8-bytes. */ - /* 22 */ - RESIDENT_ATTR_FLAGS resident_flags; /* See above. */ - /* 23 */ - s8 reservedR; /* Reserved/alignment to 8-byte +/* 22 */ RESIDENT_ATTR_FLAGS resident_flags; /* See above. */ +/* 23 */ s8 reservedR; /* Reserved/alignment to 8-byte boundary. */ - /* 24 */ - void *resident_end[0]; /* Use offsetof(ATTR_RECORD, +/* 24 */ void *resident_end[0]; /* Use offsetof(ATTR_RECORD, resident_end) to get size of a resident attribute. */ - } __attribute__((__packed__)); - /* Non-resident attributes. */ - struct { - /* 16*/ - VCN lowest_vcn; /* Lowest valid virtual cluster number + } __attribute__((__packed__)); + /* Non-resident attributes. */ + struct { +/* 16*/ VCN lowest_vcn; /* Lowest valid virtual cluster number for this portion of the attribute value or 0 if this is the only extent (usually the case). - Only when an attribute list is used does lowest_vcn != 0 ever occur. */ - /* 24*/ - VCN highest_vcn; /* Highest valid vcn of this extent of +/* 24*/ VCN highest_vcn; /* Highest valid vcn of this extent of the attribute value. - Usually there is only one portion, so this usually equals the attribute value size in clusters minus 1. Can be -1 for zero length files. Can be 0 for "single extent" attributes. */ - /* 32*/ - u16 mapping_pairs_offset; /* Byte offset from the +/* 32*/ u16 mapping_pairs_offset; /* Byte offset from the beginning of the structure to the mapping pairs array which contains the mappings between the vcns and the logical cluster numbers (lcns). When creating, place this at the end of this record header aligned to 8-byte boundary. */ - /* 34*/ - u8 compression_unit; /* The compression unit expressed +/* 34*/ u8 compression_unit; /* The compression unit expressed as the log to the base 2 of the number of clusters in a compression unit. 0 means not compressed. (This effectively limits the compression unit size to be a power of two clusters.) WinNT4 only uses a value of 4. */ - /* 35*/ - u8 reserved1[5]; /* Align to 8-byte boundary. */ - /* The sizes below are only used when lowest_vcn is zero, as otherwise it would - be difficult to keep them up-to-date.*/ - /* 40*/ - s64 allocated_size; /* Byte size of disk space +/* 35*/ u8 reserved1[5]; /* Align to 8-byte boundary. */ +/* The sizes below are only used when lowest_vcn is zero, as otherwise it would + be difficult to keep them up-to-date.*/ +/* 40*/ s64 allocated_size; /* Byte size of disk space allocated to hold the attribute value. Always is a multiple of the cluster size. When a file is compressed, this field is a multiple of the @@ -849,33 +796,28 @@ typedef struct { it represents the logically allocated space rather than the actual on disk usage. For this use the compressed_size (see below). */ - /* 48*/ - s64 data_size; /* Byte size of the attribute +/* 48*/ s64 data_size; /* Byte size of the attribute value. Can be larger than allocated_size if attribute value is compressed or sparse. */ - /* 56*/ - s64 initialized_size; /* Byte size of initialized +/* 56*/ s64 initialized_size; /* Byte size of initialized portion of the attribute value. Usually equals data_size. */ - /* 64 */ - void *non_resident_end[0]; /* Use offsetof(ATTR_RECORD, +/* 64 */ void *non_resident_end[0]; /* Use offsetof(ATTR_RECORD, non_resident_end) to get size of a non resident attribute. */ - /* sizeof(uncompressed attr) = 64*/ - /* 64*/ - s64 compressed_size; /* Byte size of the attribute +/* sizeof(uncompressed attr) = 64*/ +/* 64*/ s64 compressed_size; /* Byte size of the attribute value after compression. Only present when compressed. Always is a multiple of the cluster size. Represents the actual amount of disk space being used on the disk. */ - /* 72 */ - void *compressed_end[0]; - /* Use offsetof(ATTR_RECORD, compressed_end) to - get size of a compressed attribute. */ - /* sizeof(compressed attr) = 72*/ - } __attribute__((__packed__)); - } __attribute__((__packed__)); +/* 72 */ void *compressed_end[0]; + /* Use offsetof(ATTR_RECORD, compressed_end) to + get size of a compressed attribute. */ +/* sizeof(compressed attr) = 72*/ + } __attribute__((__packed__)); + } __attribute__((__packed__)); } __attribute__((__packed__)) ATTR_RECORD; typedef ATTR_RECORD ATTR_REC; @@ -884,66 +826,66 @@ typedef ATTR_RECORD ATTR_REC; * enum FILE_ATTR_FLAGS - File attribute flags (32-bit). */ typedef enum { - /* - * These flags are only present in the STANDARD_INFORMATION attribute - * (in the field file_attributes). - */ - FILE_ATTR_READONLY = const_cpu_to_le32(0x00000001), - FILE_ATTR_HIDDEN = const_cpu_to_le32(0x00000002), - FILE_ATTR_SYSTEM = const_cpu_to_le32(0x00000004), - /* Old DOS volid. Unused in NT. = cpu_to_le32(0x00000008), */ + /* + * These flags are only present in the STANDARD_INFORMATION attribute + * (in the field file_attributes). + */ + FILE_ATTR_READONLY = const_cpu_to_le32(0x00000001), + FILE_ATTR_HIDDEN = const_cpu_to_le32(0x00000002), + FILE_ATTR_SYSTEM = const_cpu_to_le32(0x00000004), + /* Old DOS volid. Unused in NT. = cpu_to_le32(0x00000008), */ - FILE_ATTR_DIRECTORY = const_cpu_to_le32(0x00000010), - /* FILE_ATTR_DIRECTORY is not considered valid in NT. It is reserved - for the DOS SUBDIRECTORY flag. */ - FILE_ATTR_ARCHIVE = const_cpu_to_le32(0x00000020), - FILE_ATTR_DEVICE = const_cpu_to_le32(0x00000040), - FILE_ATTR_NORMAL = const_cpu_to_le32(0x00000080), + FILE_ATTR_DIRECTORY = const_cpu_to_le32(0x00000010), + /* FILE_ATTR_DIRECTORY is not considered valid in NT. It is reserved + for the DOS SUBDIRECTORY flag. */ + FILE_ATTR_ARCHIVE = const_cpu_to_le32(0x00000020), + FILE_ATTR_DEVICE = const_cpu_to_le32(0x00000040), + FILE_ATTR_NORMAL = const_cpu_to_le32(0x00000080), - FILE_ATTR_TEMPORARY = const_cpu_to_le32(0x00000100), - FILE_ATTR_SPARSE_FILE = const_cpu_to_le32(0x00000200), - FILE_ATTR_REPARSE_POINT = const_cpu_to_le32(0x00000400), - FILE_ATTR_COMPRESSED = const_cpu_to_le32(0x00000800), + FILE_ATTR_TEMPORARY = const_cpu_to_le32(0x00000100), + FILE_ATTR_SPARSE_FILE = const_cpu_to_le32(0x00000200), + FILE_ATTR_REPARSE_POINT = const_cpu_to_le32(0x00000400), + FILE_ATTR_COMPRESSED = const_cpu_to_le32(0x00000800), - FILE_ATTR_OFFLINE = const_cpu_to_le32(0x00001000), - FILE_ATTR_NOT_CONTENT_INDEXED = const_cpu_to_le32(0x00002000), - FILE_ATTR_ENCRYPTED = const_cpu_to_le32(0x00004000), + FILE_ATTR_OFFLINE = const_cpu_to_le32(0x00001000), + FILE_ATTR_NOT_CONTENT_INDEXED = const_cpu_to_le32(0x00002000), + FILE_ATTR_ENCRYPTED = const_cpu_to_le32(0x00004000), - FILE_ATTR_VALID_FLAGS = const_cpu_to_le32(0x00007fb7), - /* FILE_ATTR_VALID_FLAGS masks out the old DOS VolId and the - FILE_ATTR_DEVICE and preserves everything else. This mask - is used to obtain all flags that are valid for reading. */ - FILE_ATTR_VALID_SET_FLAGS = const_cpu_to_le32(0x000031a7), - /* FILE_ATTR_VALID_SET_FLAGS masks out the old DOS VolId, the - FILE_ATTR_DEVICE, FILE_ATTR_DIRECTORY, FILE_ATTR_SPARSE_FILE, - FILE_ATTR_REPARSE_POINT, FILE_ATRE_COMPRESSED and FILE_ATTR_ENCRYPTED - and preserves the rest. This mask is used to to obtain all flags that - are valid for setting. */ + FILE_ATTR_VALID_FLAGS = const_cpu_to_le32(0x00007fb7), + /* FILE_ATTR_VALID_FLAGS masks out the old DOS VolId and the + FILE_ATTR_DEVICE and preserves everything else. This mask + is used to obtain all flags that are valid for reading. */ + FILE_ATTR_VALID_SET_FLAGS = const_cpu_to_le32(0x000031a7), + /* FILE_ATTR_VALID_SET_FLAGS masks out the old DOS VolId, the + FILE_ATTR_DEVICE, FILE_ATTR_DIRECTORY, FILE_ATTR_SPARSE_FILE, + FILE_ATTR_REPARSE_POINT, FILE_ATRE_COMPRESSED and FILE_ATTR_ENCRYPTED + and preserves the rest. This mask is used to to obtain all flags that + are valid for setting. */ - /** - * FILE_ATTR_I30_INDEX_PRESENT - Is it a directory? - * - * This is a copy of the MFT_RECORD_IS_DIRECTORY bit from the mft - * record, telling us whether this is a directory or not, i.e. whether - * it has an index root attribute named "$I30" or not. - * - * This flag is only present in the FILE_NAME attribute (in the - * file_attributes field). - */ - FILE_ATTR_I30_INDEX_PRESENT = const_cpu_to_le32(0x10000000), - - /** - * FILE_ATTR_VIEW_INDEX_PRESENT - Does have a non-directory index? - * - * This is a copy of the MFT_RECORD_IS_VIEW_INDEX bit from the mft - * record, telling us whether this file has a view index present (eg. - * object id index, quota index, one of the security indexes and the - * reparse points index). - * - * This flag is only present in the $STANDARD_INFORMATION and - * $FILE_NAME attributes. - */ - FILE_ATTR_VIEW_INDEX_PRESENT = const_cpu_to_le32(0x20000000), + /** + * FILE_ATTR_I30_INDEX_PRESENT - Is it a directory? + * + * This is a copy of the MFT_RECORD_IS_DIRECTORY bit from the mft + * record, telling us whether this is a directory or not, i.e. whether + * it has an index root attribute named "$I30" or not. + * + * This flag is only present in the FILE_NAME attribute (in the + * file_attributes field). + */ + FILE_ATTR_I30_INDEX_PRESENT = const_cpu_to_le32(0x10000000), + + /** + * FILE_ATTR_VIEW_INDEX_PRESENT - Does have a non-directory index? + * + * This is a copy of the MFT_RECORD_IS_VIEW_INDEX bit from the mft + * record, telling us whether this file has a view index present (eg. + * object id index, quota index, one of the security indexes and the + * reparse points index). + * + * This flag is only present in the $STANDARD_INFORMATION and + * $FILE_NAME attributes. + */ + FILE_ATTR_VIEW_INDEX_PRESENT = const_cpu_to_le32(0x20000000), } __attribute__((__packed__)) FILE_ATTR_FLAGS; /* @@ -964,18 +906,14 @@ typedef enum { * assumed to be the one and only correct interpretation. */ typedef struct { - /*Ofs*/ - /* 0*/ - s64 creation_time; /* Time file was created. Updated when +/*Ofs*/ +/* 0*/ s64 creation_time; /* Time file was created. Updated when a filename is changed(?). */ - /* 8*/ - s64 last_data_change_time; /* Time the data attribute was last +/* 8*/ s64 last_data_change_time; /* Time the data attribute was last modified. */ - /* 16*/ - s64 last_mft_change_time; /* Time this mft record was last +/* 16*/ s64 last_mft_change_time; /* Time this mft record was last modified. */ - /* 24*/ - s64 last_access_time; /* Approximate time when the file was +/* 24*/ s64 last_access_time; /* Approximate time when the file was last accessed (obviously this is not updated on read-only volumes). In Windows this is only updated when @@ -983,64 +921,53 @@ typedef struct { passed since the last update. Also, last access times updates can be disabled altogether for speed. */ - /* 32*/ - FILE_ATTR_FLAGS file_attributes; /* Flags describing the file. */ - /* 36*/ - union { - /* NTFS 1.2 (and previous, presumably) */ - struct { - /* 36 */ - u8 reserved12[12]; /* Reserved/alignment to 8-byte +/* 32*/ FILE_ATTR_FLAGS file_attributes; /* Flags describing the file. */ +/* 36*/ union { + /* NTFS 1.2 (and previous, presumably) */ + struct { + /* 36 */ u8 reserved12[12]; /* Reserved/alignment to 8-byte boundary. */ - /* 48 */ - void *v1_end[0]; /* Marker for offsetof(). */ - } __attribute__((__packed__)); - /* sizeof() = 48 bytes */ - /* NTFS 3.0 */ - struct { - /* - * If a volume has been upgraded from a previous NTFS version, then these - * fields are present only if the file has been accessed since the upgrade. - * Recognize the difference by comparing the length of the resident attribute - * value. If it is 48, then the following fields are missing. If it is 72 then - * the fields are present. Maybe just check like this: - * if (resident.ValueLength < sizeof(STANDARD_INFORMATION)) { - * Assume NTFS 1.2- format. - * If (volume version is 3.0+) - * Upgrade attribute to NTFS 3.0 format. - * else - * Use NTFS 1.2- format for access. - * } else - * Use NTFS 3.0 format for access. - * Only problem is that it might be legal to set the length of the value to - * arbitrarily large values thus spoiling this check. - But chkdsk probably - * views that as a corruption, assuming that it behaves like this for all - * attributes. - */ - /* 36*/ - u32 maximum_versions; /* Maximum allowed versions for + /* 48 */ void *v1_end[0]; /* Marker for offsetof(). */ + } __attribute__((__packed__)); +/* sizeof() = 48 bytes */ + /* NTFS 3.0 */ + struct { +/* + * If a volume has been upgraded from a previous NTFS version, then these + * fields are present only if the file has been accessed since the upgrade. + * Recognize the difference by comparing the length of the resident attribute + * value. If it is 48, then the following fields are missing. If it is 72 then + * the fields are present. Maybe just check like this: + * if (resident.ValueLength < sizeof(STANDARD_INFORMATION)) { + * Assume NTFS 1.2- format. + * If (volume version is 3.0+) + * Upgrade attribute to NTFS 3.0 format. + * else + * Use NTFS 1.2- format for access. + * } else + * Use NTFS 3.0 format for access. + * Only problem is that it might be legal to set the length of the value to + * arbitrarily large values thus spoiling this check. - But chkdsk probably + * views that as a corruption, assuming that it behaves like this for all + * attributes. + */ + /* 36*/ u32 maximum_versions; /* Maximum allowed versions for file. Zero if version numbering is disabled. */ - /* 40*/ - u32 version_number; /* This file's version (if any). + /* 40*/ u32 version_number; /* This file's version (if any). Set to zero if maximum_versions is zero. */ - /* 44*/ - u32 class_id; /* Class id from bidirectional + /* 44*/ u32 class_id; /* Class id from bidirectional class id index (?). */ - /* 48*/ - u32 owner_id; /* Owner_id of the user owning + /* 48*/ u32 owner_id; /* Owner_id of the user owning the file. Translate via $Q index in FILE_Extend /$Quota to the quota control entry for the user owning the file. Zero if quotas are disabled. */ - /* 52*/ - u32 security_id; /* Security_id for the file. + /* 52*/ u32 security_id; /* Security_id for the file. Translate via $SII index and $SDS data stream in FILE_Secure to the security descriptor. */ - /* 56*/ - u64 quota_charged; /* Byte size of the charge to + /* 56*/ u64 quota_charged; /* Byte size of the charge to the quota for all streams of the file. Note: Is zero if quotas are disabled. */ - /* 64*/ - u64 usn; /* Last update sequence number + /* 64*/ u64 usn; /* Last update sequence number of the file. This is a direct index into the change (aka usn) journal file. It is zero if the usn journal is disabled. @@ -1054,11 +981,10 @@ typedef struct { partition. This, in contrast to disabling the journal is a very fast process, so the user won't even notice it. */ - /* 72*/ - void *v3_end[0]; /* Marker for offsetof(). */ - } __attribute__((__packed__)); - } __attribute__((__packed__)); - /* sizeof() = 72 bytes (NTFS 3.0) */ + /* 72*/ void *v3_end[0]; /* Marker for offsetof(). */ + } __attribute__((__packed__)); + } __attribute__((__packed__)); +/* sizeof() = 72 bytes (NTFS 3.0) */ } __attribute__((__packed__)) STANDARD_INFORMATION; /** @@ -1091,20 +1017,15 @@ typedef struct { * - There are many named streams. */ typedef struct { - /*Ofs*/ - /* 0*/ - ATTR_TYPES type; /* Type of referenced attribute. */ - /* 4*/ - u16 length; /* Byte size of this entry. */ - /* 6*/ - u8 name_length; /* Size in Unicode chars of the name of the +/*Ofs*/ +/* 0*/ ATTR_TYPES type; /* Type of referenced attribute. */ +/* 4*/ u16 length; /* Byte size of this entry. */ +/* 6*/ u8 name_length; /* Size in Unicode chars of the name of the attribute or 0 if unnamed. */ - /* 7*/ - u8 name_offset; /* Byte offset to beginning of attribute name +/* 7*/ u8 name_offset; /* Byte offset to beginning of attribute name (always set this to where the name would start even if unnamed). */ - /* 8*/ - VCN lowest_vcn; /* Lowest virtual cluster number of this portion +/* 8*/ VCN lowest_vcn; /* Lowest virtual cluster number of this portion of the attribute value. This is usually 0. It is non-zero for the case where one attribute does not fit into one mft record and thus @@ -1116,18 +1037,15 @@ typedef struct { value! The windows driver uses cmp, followed by jg when comparing this, thus it treats it as signed. */ - /* 16*/ - MFT_REF mft_reference; /* The reference of the mft record holding +/* 16*/ MFT_REF mft_reference; /* The reference of the mft record holding the ATTR_RECORD for this portion of the attribute value. */ - /* 24*/ - u16 instance; /* If lowest_vcn = 0, the instance of the +/* 24*/ u16 instance; /* If lowest_vcn = 0, the instance of the attribute being referenced; otherwise 0. */ - /* 26*/ - ntfschar name[0]; /* Use when creating only. When reading use +/* 26*/ ntfschar name[0]; /* Use when creating only. When reading use name_offset to determine the location of the name. */ - /* sizeof() = 26 + (attribute_name_length * 2) bytes */ +/* sizeof() = 26 + (attribute_name_length * 2) bytes */ } __attribute__((__packed__)) ATTR_LIST_ENTRY; /* @@ -1140,26 +1058,26 @@ typedef struct { * (8-bit). */ typedef enum { - FILE_NAME_POSIX = 0x00, - /* This is the largest namespace. It is case sensitive and - allows all Unicode characters except for: '\0' and '/'. - Beware that in WinNT/2k files which eg have the same name - except for their case will not be distinguished by the - standard utilities and thus a "del filename" will delete - both "filename" and "fileName" without warning. */ - FILE_NAME_WIN32 = 0x01, - /* The standard WinNT/2k NTFS long filenames. Case insensitive. - All Unicode chars except: '\0', '"', '*', '/', ':', '<', - '>', '?', '\' and '|'. Further, names cannot end with a '.' - or a space. */ - FILE_NAME_DOS = 0x02, - /* The standard DOS filenames (8.3 format). Uppercase only. - All 8-bit characters greater space, except: '"', '*', '+', - ',', '/', ':', ';', '<', '=', '>', '?' and '\'. */ - FILE_NAME_WIN32_AND_DOS = 0x03, - /* 3 means that both the Win32 and the DOS filenames are - identical and hence have been saved in this single filename - record. */ + FILE_NAME_POSIX = 0x00, + /* This is the largest namespace. It is case sensitive and + allows all Unicode characters except for: '\0' and '/'. + Beware that in WinNT/2k files which eg have the same name + except for their case will not be distinguished by the + standard utilities and thus a "del filename" will delete + both "filename" and "fileName" without warning. */ + FILE_NAME_WIN32 = 0x01, + /* The standard WinNT/2k NTFS long filenames. Case insensitive. + All Unicode chars except: '\0', '"', '*', '/', ':', '<', + '>', '?', '\' and '|'. Further, names cannot end with a '.' + or a space. */ + FILE_NAME_DOS = 0x02, + /* The standard DOS filenames (8.3 format). Uppercase only. + All 8-bit characters greater space, except: '"', '*', '+', + ',', '/', ':', ';', '<', '=', '>', '?' and '\'. */ + FILE_NAME_WIN32_AND_DOS = 0x03, + /* 3 means that both the Win32 and the DOS filenames are + identical and hence have been saved in this single filename + record. */ } __attribute__((__packed__)) FILE_NAME_TYPE_FLAGS; /** @@ -1176,23 +1094,17 @@ typedef enum { * assumed to be the one and only correct interpretation. */ typedef struct { - /*hex ofs*/ - /* 0*/ - MFT_REF parent_directory; /* Directory this filename is +/*hex ofs*/ +/* 0*/ MFT_REF parent_directory; /* Directory this filename is referenced from. */ - /* 8*/ - s64 creation_time; /* Time file was created. */ - /* 10*/ - s64 last_data_change_time; /* Time the data attribute was last +/* 8*/ s64 creation_time; /* Time file was created. */ +/* 10*/ s64 last_data_change_time; /* Time the data attribute was last modified. */ - /* 18*/ - s64 last_mft_change_time; /* Time this mft record was last +/* 18*/ s64 last_mft_change_time; /* Time this mft record was last modified. */ - /* 20*/ - s64 last_access_time; /* Last time this mft record was +/* 20*/ s64 last_access_time; /* Last time this mft record was accessed. */ - /* 28*/ - s64 allocated_size; /* Byte size of on-disk allocated space +/* 28*/ s64 allocated_size; /* Byte size of on-disk allocated space for the data attribute. So for normal $DATA, this is the allocated_size from the unnamed @@ -1201,34 +1113,25 @@ typedef struct { compressed_size from the unnamed $DATA attribute. NOTE: This is a multiple of the cluster size. */ - /* 30*/ - s64 data_size; /* Byte size of actual data in data +/* 30*/ s64 data_size; /* Byte size of actual data in data attribute. */ - /* 38*/ - FILE_ATTR_FLAGS file_attributes; /* Flags describing the file. */ - /* 3c*/ - union { - /* 3c*/ struct { - /* 3c*/ - u16 packed_ea_size; /* Size of the buffer needed to +/* 38*/ FILE_ATTR_FLAGS file_attributes; /* Flags describing the file. */ +/* 3c*/ union { + /* 3c*/ struct { + /* 3c*/ u16 packed_ea_size; /* Size of the buffer needed to pack the extended attributes (EAs), if such are present.*/ - /* 3e*/ - u16 reserved; /* Reserved for alignment. */ - } __attribute__((__packed__)); - /* 3c*/ - u32 reparse_point_tag; /* Type of reparse point, + /* 3e*/ u16 reserved; /* Reserved for alignment. */ + } __attribute__((__packed__)); + /* 3c*/ u32 reparse_point_tag; /* Type of reparse point, present only in reparse points and only if there are no EAs. */ - } __attribute__((__packed__)); - /* 40*/ - u8 file_name_length; /* Length of file name in + } __attribute__((__packed__)); +/* 40*/ u8 file_name_length; /* Length of file name in (Unicode) characters. */ - /* 41*/ - FILE_NAME_TYPE_FLAGS file_name_type; /* Namespace of the file name.*/ - /* 42*/ - ntfschar file_name[0]; /* File name in Unicode. */ +/* 41*/ FILE_NAME_TYPE_FLAGS file_name_type; /* Namespace of the file name.*/ +/* 42*/ ntfschar file_name[0]; /* File name in Unicode. */ } __attribute__((__packed__)) FILE_NAME_ATTR; /** @@ -1244,10 +1147,10 @@ typedef struct { * 1F010768-5A73-BC91-0010-A52216A7227B */ typedef struct { - u32 data1; /* The first eight hexadecimal digits of the GUID. */ - u16 data2; /* The first group of four hexadecimal digits. */ - u16 data3; /* The second group of four hexadecimal digits. */ - u8 data4[8]; /* The first two bytes are the third group of four + u32 data1; /* The first eight hexadecimal digits of the GUID. */ + u16 data2; /* The first group of four hexadecimal digits. */ + u16 data3; /* The second group of four hexadecimal digits. */ + u8 data4[8]; /* The first two bytes are the third group of four hexadecimal digits. The remaining six bytes are the final 12 hexadecimal digits. */ } __attribute__((__packed__)) GUID; @@ -1266,16 +1169,16 @@ typedef struct { * domain_id - Reserved (always zero). */ typedef struct { - MFT_REF mft_reference; /* Mft record containing the object_id in + MFT_REF mft_reference; /* Mft record containing the object_id in the index entry key. */ - union { - struct { - GUID birth_volume_id; - GUID birth_object_id; - GUID domain_id; - } __attribute__((__packed__)); - u8 extended_info[48]; - } __attribute__((__packed__)); + union { + struct { + GUID birth_volume_id; + GUID birth_object_id; + GUID domain_id; + } __attribute__((__packed__)); + u8 extended_info[48]; + } __attribute__((__packed__)); } __attribute__((__packed__)) OBJ_ID_INDEX_DATA; /** @@ -1284,25 +1187,25 @@ typedef struct { * NOTE: Always resident. */ typedef struct { - GUID object_id; /* Unique id assigned to the + GUID object_id; /* Unique id assigned to the file.*/ - /* The following fields are optional. The attribute value size is 16 - bytes, i.e. sizeof(GUID), if these are not present at all. Note, - the entries can be present but one or more (or all) can be zero - meaning that that particular value(s) is(are) not defined. Note, - when the fields are missing here, it is well possible that they are - to be found within the $Extend/$ObjId system file indexed under the - above object_id. */ - union { - struct { - GUID birth_volume_id; /* Unique id of volume on which + /* The following fields are optional. The attribute value size is 16 + bytes, i.e. sizeof(GUID), if these are not present at all. Note, + the entries can be present but one or more (or all) can be zero + meaning that that particular value(s) is(are) not defined. Note, + when the fields are missing here, it is well possible that they are + to be found within the $Extend/$ObjId system file indexed under the + above object_id. */ + union { + struct { + GUID birth_volume_id; /* Unique id of volume on which the file was first created.*/ - GUID birth_object_id; /* Unique id of file when it was + GUID birth_object_id; /* Unique id of file when it was first created. */ - GUID domain_id; /* Reserved, zero. */ - } __attribute__((__packed__)); - u8 extended_info[48]; - } __attribute__((__packed__)); + GUID domain_id; /* Reserved, zero. */ + } __attribute__((__packed__)); + u8 extended_info[48]; + } __attribute__((__packed__)); } __attribute__((__packed__)) OBJECT_ID_ATTR; #if 0 @@ -1313,13 +1216,13 @@ typedef struct { * the SID structure (see below). */ typedef enum { /* SID string prefix. */ - SECURITY_NULL_SID_AUTHORITY = {0, 0, 0, 0, 0, 0}, /* S-1-0 */ - SECURITY_WORLD_SID_AUTHORITY = {0, 0, 0, 0, 0, 1}, /* S-1-1 */ - SECURITY_LOCAL_SID_AUTHORITY = {0, 0, 0, 0, 0, 2}, /* S-1-2 */ - SECURITY_CREATOR_SID_AUTHORITY = {0, 0, 0, 0, 0, 3}, /* S-1-3 */ - SECURITY_NON_UNIQUE_AUTHORITY = {0, 0, 0, 0, 0, 4}, /* S-1-4 */ - SECURITY_NT_SID_AUTHORITY = {0, 0, 0, 0, 0, 5}, /* S-1-5 */ - } IDENTIFIER_AUTHORITIES; + SECURITY_NULL_SID_AUTHORITY = {0, 0, 0, 0, 0, 0}, /* S-1-0 */ + SECURITY_WORLD_SID_AUTHORITY = {0, 0, 0, 0, 0, 1}, /* S-1-1 */ + SECURITY_LOCAL_SID_AUTHORITY = {0, 0, 0, 0, 0, 2}, /* S-1-2 */ + SECURITY_CREATOR_SID_AUTHORITY = {0, 0, 0, 0, 0, 3}, /* S-1-3 */ + SECURITY_NON_UNIQUE_AUTHORITY = {0, 0, 0, 0, 0, 4}, /* S-1-4 */ + SECURITY_NT_SID_AUTHORITY = {0, 0, 0, 0, 0, 5}, /* S-1-5 */ +} IDENTIFIER_AUTHORITIES; #endif /** @@ -1335,73 +1238,73 @@ typedef enum { /* SID string prefix. */ * the relative identifier SECURITY_CREATOR_OWNER_RID (0). */ typedef enum { /* Identifier authority. */ - SECURITY_NULL_RID = 0, /* S-1-0 */ - SECURITY_WORLD_RID = 0, /* S-1-1 */ - SECURITY_LOCAL_RID = 0, /* S-1-2 */ + SECURITY_NULL_RID = 0, /* S-1-0 */ + SECURITY_WORLD_RID = 0, /* S-1-1 */ + SECURITY_LOCAL_RID = 0, /* S-1-2 */ - SECURITY_CREATOR_OWNER_RID = 0, /* S-1-3 */ - SECURITY_CREATOR_GROUP_RID = 1, /* S-1-3 */ + SECURITY_CREATOR_OWNER_RID = 0, /* S-1-3 */ + SECURITY_CREATOR_GROUP_RID = 1, /* S-1-3 */ - SECURITY_CREATOR_OWNER_SERVER_RID = 2, /* S-1-3 */ - SECURITY_CREATOR_GROUP_SERVER_RID = 3, /* S-1-3 */ + SECURITY_CREATOR_OWNER_SERVER_RID = 2, /* S-1-3 */ + SECURITY_CREATOR_GROUP_SERVER_RID = 3, /* S-1-3 */ - SECURITY_DIALUP_RID = 1, - SECURITY_NETWORK_RID = 2, - SECURITY_BATCH_RID = 3, - SECURITY_INTERACTIVE_RID = 4, - SECURITY_SERVICE_RID = 6, - SECURITY_ANONYMOUS_LOGON_RID = 7, - SECURITY_PROXY_RID = 8, - SECURITY_ENTERPRISE_CONTROLLERS_RID=9, - SECURITY_SERVER_LOGON_RID = 9, - SECURITY_PRINCIPAL_SELF_RID = 0xa, - SECURITY_AUTHENTICATED_USER_RID = 0xb, - SECURITY_RESTRICTED_CODE_RID = 0xc, - SECURITY_TERMINAL_SERVER_RID = 0xd, + SECURITY_DIALUP_RID = 1, + SECURITY_NETWORK_RID = 2, + SECURITY_BATCH_RID = 3, + SECURITY_INTERACTIVE_RID = 4, + SECURITY_SERVICE_RID = 6, + SECURITY_ANONYMOUS_LOGON_RID = 7, + SECURITY_PROXY_RID = 8, + SECURITY_ENTERPRISE_CONTROLLERS_RID=9, + SECURITY_SERVER_LOGON_RID = 9, + SECURITY_PRINCIPAL_SELF_RID = 0xa, + SECURITY_AUTHENTICATED_USER_RID = 0xb, + SECURITY_RESTRICTED_CODE_RID = 0xc, + SECURITY_TERMINAL_SERVER_RID = 0xd, - SECURITY_LOGON_IDS_RID = 5, - SECURITY_LOGON_IDS_RID_COUNT = 3, + SECURITY_LOGON_IDS_RID = 5, + SECURITY_LOGON_IDS_RID_COUNT = 3, - SECURITY_LOCAL_SYSTEM_RID = 0x12, + SECURITY_LOCAL_SYSTEM_RID = 0x12, - SECURITY_NT_NON_UNIQUE = 0x15, + SECURITY_NT_NON_UNIQUE = 0x15, - SECURITY_BUILTIN_DOMAIN_RID = 0x20, + SECURITY_BUILTIN_DOMAIN_RID = 0x20, - /* - * Well-known domain relative sub-authority values (RIDs). - */ + /* + * Well-known domain relative sub-authority values (RIDs). + */ - /* Users. */ - DOMAIN_USER_RID_ADMIN = 0x1f4, - DOMAIN_USER_RID_GUEST = 0x1f5, - DOMAIN_USER_RID_KRBTGT = 0x1f6, + /* Users. */ + DOMAIN_USER_RID_ADMIN = 0x1f4, + DOMAIN_USER_RID_GUEST = 0x1f5, + DOMAIN_USER_RID_KRBTGT = 0x1f6, - /* Groups. */ - DOMAIN_GROUP_RID_ADMINS = 0x200, - DOMAIN_GROUP_RID_USERS = 0x201, - DOMAIN_GROUP_RID_GUESTS = 0x202, - DOMAIN_GROUP_RID_COMPUTERS = 0x203, - DOMAIN_GROUP_RID_CONTROLLERS = 0x204, - DOMAIN_GROUP_RID_CERT_ADMINS = 0x205, - DOMAIN_GROUP_RID_SCHEMA_ADMINS = 0x206, - DOMAIN_GROUP_RID_ENTERPRISE_ADMINS= 0x207, - DOMAIN_GROUP_RID_POLICY_ADMINS = 0x208, + /* Groups. */ + DOMAIN_GROUP_RID_ADMINS = 0x200, + DOMAIN_GROUP_RID_USERS = 0x201, + DOMAIN_GROUP_RID_GUESTS = 0x202, + DOMAIN_GROUP_RID_COMPUTERS = 0x203, + DOMAIN_GROUP_RID_CONTROLLERS = 0x204, + DOMAIN_GROUP_RID_CERT_ADMINS = 0x205, + DOMAIN_GROUP_RID_SCHEMA_ADMINS = 0x206, + DOMAIN_GROUP_RID_ENTERPRISE_ADMINS= 0x207, + DOMAIN_GROUP_RID_POLICY_ADMINS = 0x208, - /* Aliases. */ - DOMAIN_ALIAS_RID_ADMINS = 0x220, - DOMAIN_ALIAS_RID_USERS = 0x221, - DOMAIN_ALIAS_RID_GUESTS = 0x222, - DOMAIN_ALIAS_RID_POWER_USERS = 0x223, + /* Aliases. */ + DOMAIN_ALIAS_RID_ADMINS = 0x220, + DOMAIN_ALIAS_RID_USERS = 0x221, + DOMAIN_ALIAS_RID_GUESTS = 0x222, + DOMAIN_ALIAS_RID_POWER_USERS = 0x223, - DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224, - DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225, - DOMAIN_ALIAS_RID_PRINT_OPS = 0x226, - DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227, + DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224, + DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225, + DOMAIN_ALIAS_RID_PRINT_OPS = 0x226, + DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227, - DOMAIN_ALIAS_RID_REPLICATOR = 0x228, - DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229, - DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a, + DOMAIN_ALIAS_RID_REPLICATOR = 0x228, + DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229, + DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a, } RELATIVE_IDENTIFIERS; /* @@ -1447,11 +1350,11 @@ typedef enum { /* Identifier authority. */ * NOTE: This is stored as a big endian number. */ typedef union { - struct { - u16 high_part; /* High 16-bits. */ - u32 low_part; /* Low 32-bits. */ - } __attribute__((__packed__)); - u8 value[6]; /* Value as individual bytes. */ + struct { + u16 high_part; /* High 16-bits. */ + u32 low_part; /* Low 32-bits. */ + } __attribute__((__packed__)); + u8 value[6]; /* Value as individual bytes. */ } __attribute__((__packed__)) SID_IDENTIFIER_AUTHORITY; /** @@ -1483,19 +1386,19 @@ typedef union { * sub_authority[1] = 544 // DOMAIN_ALIAS_RID_ADMINS */ typedef struct { - u8 revision; - u8 sub_authority_count; - SID_IDENTIFIER_AUTHORITY identifier_authority; - u32 sub_authority[1]; /* At least one sub_authority. */ + u8 revision; + u8 sub_authority_count; + SID_IDENTIFIER_AUTHORITY identifier_authority; + u32 sub_authority[1]; /* At least one sub_authority. */ } __attribute__((__packed__)) SID; /** * enum SID_CONSTANTS - Current constants for SIDs. */ typedef enum { - SID_REVISION = 1, /* Current revision level. */ - SID_MAX_SUB_AUTHORITIES = 15, /* Maximum number of those. */ - SID_RECOMMENDED_SUB_AUTHORITIES = 1, /* Will change to around 6 in + SID_REVISION = 1, /* Current revision level. */ + SID_MAX_SUB_AUTHORITIES = 15, /* Maximum number of those. */ + SID_RECOMMENDED_SUB_AUTHORITIES = 1, /* Will change to around 6 in a future revision. */ } SID_CONSTANTS; @@ -1503,28 +1406,28 @@ typedef enum { * enum ACE_TYPES - The predefined ACE types (8-bit, see below). */ typedef enum { - ACCESS_MIN_MS_ACE_TYPE = 0, - ACCESS_ALLOWED_ACE_TYPE = 0, - ACCESS_DENIED_ACE_TYPE = 1, - SYSTEM_AUDIT_ACE_TYPE = 2, - SYSTEM_ALARM_ACE_TYPE = 3, /* Not implemented as of Win2k. */ - ACCESS_MAX_MS_V2_ACE_TYPE = 3, + ACCESS_MIN_MS_ACE_TYPE = 0, + ACCESS_ALLOWED_ACE_TYPE = 0, + ACCESS_DENIED_ACE_TYPE = 1, + SYSTEM_AUDIT_ACE_TYPE = 2, + SYSTEM_ALARM_ACE_TYPE = 3, /* Not implemented as of Win2k. */ + ACCESS_MAX_MS_V2_ACE_TYPE = 3, - ACCESS_ALLOWED_COMPOUND_ACE_TYPE= 4, - ACCESS_MAX_MS_V3_ACE_TYPE = 4, + ACCESS_ALLOWED_COMPOUND_ACE_TYPE= 4, + ACCESS_MAX_MS_V3_ACE_TYPE = 4, - /* The following are Win2k only. */ - ACCESS_MIN_MS_OBJECT_ACE_TYPE = 5, - ACCESS_ALLOWED_OBJECT_ACE_TYPE = 5, - ACCESS_DENIED_OBJECT_ACE_TYPE = 6, - SYSTEM_AUDIT_OBJECT_ACE_TYPE = 7, - SYSTEM_ALARM_OBJECT_ACE_TYPE = 8, - ACCESS_MAX_MS_OBJECT_ACE_TYPE = 8, + /* The following are Win2k only. */ + ACCESS_MIN_MS_OBJECT_ACE_TYPE = 5, + ACCESS_ALLOWED_OBJECT_ACE_TYPE = 5, + ACCESS_DENIED_OBJECT_ACE_TYPE = 6, + SYSTEM_AUDIT_OBJECT_ACE_TYPE = 7, + SYSTEM_ALARM_OBJECT_ACE_TYPE = 8, + ACCESS_MAX_MS_OBJECT_ACE_TYPE = 8, - ACCESS_MAX_MS_V4_ACE_TYPE = 8, + ACCESS_MAX_MS_V4_ACE_TYPE = 8, - /* This one is for WinNT&2k. */ - ACCESS_MAX_MS_ACE_TYPE = 8, + /* This one is for WinNT&2k. */ + ACCESS_MAX_MS_ACE_TYPE = 8, } __attribute__((__packed__)) ACE_TYPES; /** @@ -1538,17 +1441,17 @@ typedef enum { * to indicate that a message is generated (in Windows!) for failed accesses. */ typedef enum { - /* The inheritance flags. */ - OBJECT_INHERIT_ACE = 0x01, - CONTAINER_INHERIT_ACE = 0x02, - NO_PROPAGATE_INHERIT_ACE = 0x04, - INHERIT_ONLY_ACE = 0x08, - INHERITED_ACE = 0x10, /* Win2k only. */ - VALID_INHERIT_FLAGS = 0x1f, + /* The inheritance flags. */ + OBJECT_INHERIT_ACE = 0x01, + CONTAINER_INHERIT_ACE = 0x02, + NO_PROPAGATE_INHERIT_ACE = 0x04, + INHERIT_ONLY_ACE = 0x08, + INHERITED_ACE = 0x10, /* Win2k only. */ + VALID_INHERIT_FLAGS = 0x1f, - /* The audit flags. */ - SUCCESSFUL_ACCESS_ACE_FLAG = 0x40, - FAILED_ACCESS_ACE_FLAG = 0x80, + /* The audit flags. */ + SUCCESSFUL_ACCESS_ACE_FLAG = 0x40, + FAILED_ACCESS_ACE_FLAG = 0x80, } __attribute__((__packed__)) ACE_FLAGS; /** @@ -1565,9 +1468,9 @@ typedef enum { * data depends on the ACE type. */ typedef struct { - ACE_TYPES type; /* Type of the ACE. */ - ACE_FLAGS flags; /* Flags describing the ACE. */ - u16 size; /* Size in bytes of the ACE. */ + ACE_TYPES type; /* Type of the ACE. */ + ACE_FLAGS flags; /* Flags describing the ACE. */ + u16 size; /* Size in bytes of the ACE. */ } __attribute__((__packed__)) ACE_HEADER; /** @@ -1576,133 +1479,133 @@ typedef struct { * Defines the access rights. */ typedef enum { - /* - * The specific rights (bits 0 to 15). Depend on the type of the - * object being secured by the ACE. - */ + /* + * The specific rights (bits 0 to 15). Depend on the type of the + * object being secured by the ACE. + */ - /* Specific rights for files and directories are as follows: */ + /* Specific rights for files and directories are as follows: */ - /* Right to read data from the file. (FILE) */ - FILE_READ_DATA = const_cpu_to_le32(0x00000001), - /* Right to list contents of a directory. (DIRECTORY) */ - FILE_LIST_DIRECTORY = const_cpu_to_le32(0x00000001), + /* Right to read data from the file. (FILE) */ + FILE_READ_DATA = const_cpu_to_le32(0x00000001), + /* Right to list contents of a directory. (DIRECTORY) */ + FILE_LIST_DIRECTORY = const_cpu_to_le32(0x00000001), - /* Right to write data to the file. (FILE) */ - FILE_WRITE_DATA = const_cpu_to_le32(0x00000002), - /* Right to create a file in the directory. (DIRECTORY) */ - FILE_ADD_FILE = const_cpu_to_le32(0x00000002), + /* Right to write data to the file. (FILE) */ + FILE_WRITE_DATA = const_cpu_to_le32(0x00000002), + /* Right to create a file in the directory. (DIRECTORY) */ + FILE_ADD_FILE = const_cpu_to_le32(0x00000002), - /* Right to append data to the file. (FILE) */ - FILE_APPEND_DATA = const_cpu_to_le32(0x00000004), - /* Right to create a subdirectory. (DIRECTORY) */ - FILE_ADD_SUBDIRECTORY = const_cpu_to_le32(0x00000004), + /* Right to append data to the file. (FILE) */ + FILE_APPEND_DATA = const_cpu_to_le32(0x00000004), + /* Right to create a subdirectory. (DIRECTORY) */ + FILE_ADD_SUBDIRECTORY = const_cpu_to_le32(0x00000004), - /* Right to read extended attributes. (FILE/DIRECTORY) */ - FILE_READ_EA = const_cpu_to_le32(0x00000008), + /* Right to read extended attributes. (FILE/DIRECTORY) */ + FILE_READ_EA = const_cpu_to_le32(0x00000008), - /* Right to write extended attributes. (FILE/DIRECTORY) */ - FILE_WRITE_EA = const_cpu_to_le32(0x00000010), + /* Right to write extended attributes. (FILE/DIRECTORY) */ + FILE_WRITE_EA = const_cpu_to_le32(0x00000010), - /* Right to execute a file. (FILE) */ - FILE_EXECUTE = const_cpu_to_le32(0x00000020), - /* Right to traverse the directory. (DIRECTORY) */ - FILE_TRAVERSE = const_cpu_to_le32(0x00000020), + /* Right to execute a file. (FILE) */ + FILE_EXECUTE = const_cpu_to_le32(0x00000020), + /* Right to traverse the directory. (DIRECTORY) */ + FILE_TRAVERSE = const_cpu_to_le32(0x00000020), - /* - * Right to delete a directory and all the files it contains (its - * children), even if the files are read-only. (DIRECTORY) - */ - FILE_DELETE_CHILD = const_cpu_to_le32(0x00000040), + /* + * Right to delete a directory and all the files it contains (its + * children), even if the files are read-only. (DIRECTORY) + */ + FILE_DELETE_CHILD = const_cpu_to_le32(0x00000040), - /* Right to read file attributes. (FILE/DIRECTORY) */ - FILE_READ_ATTRIBUTES = const_cpu_to_le32(0x00000080), + /* Right to read file attributes. (FILE/DIRECTORY) */ + FILE_READ_ATTRIBUTES = const_cpu_to_le32(0x00000080), - /* Right to change file attributes. (FILE/DIRECTORY) */ - FILE_WRITE_ATTRIBUTES = const_cpu_to_le32(0x00000100), + /* Right to change file attributes. (FILE/DIRECTORY) */ + FILE_WRITE_ATTRIBUTES = const_cpu_to_le32(0x00000100), - /* - * The standard rights (bits 16 to 23). Are independent of the type of - * object being secured. - */ + /* + * The standard rights (bits 16 to 23). Are independent of the type of + * object being secured. + */ - /* Right to delete the object. */ - DELETE = const_cpu_to_le32(0x00010000), + /* Right to delete the object. */ + DELETE = const_cpu_to_le32(0x00010000), - /* - * Right to read the information in the object's security descriptor, - * not including the information in the SACL. I.e. right to read the - * security descriptor and owner. - */ - READ_CONTROL = const_cpu_to_le32(0x00020000), + /* + * Right to read the information in the object's security descriptor, + * not including the information in the SACL. I.e. right to read the + * security descriptor and owner. + */ + READ_CONTROL = const_cpu_to_le32(0x00020000), - /* Right to modify the DACL in the object's security descriptor. */ - WRITE_DAC = const_cpu_to_le32(0x00040000), + /* Right to modify the DACL in the object's security descriptor. */ + WRITE_DAC = const_cpu_to_le32(0x00040000), - /* Right to change the owner in the object's security descriptor. */ - WRITE_OWNER = const_cpu_to_le32(0x00080000), + /* Right to change the owner in the object's security descriptor. */ + WRITE_OWNER = const_cpu_to_le32(0x00080000), - /* - * Right to use the object for synchronization. Enables a process to - * wait until the object is in the signalled state. Some object types - * do not support this access right. - */ - SYNCHRONIZE = const_cpu_to_le32(0x00100000), + /* + * Right to use the object for synchronization. Enables a process to + * wait until the object is in the signalled state. Some object types + * do not support this access right. + */ + SYNCHRONIZE = const_cpu_to_le32(0x00100000), - /* - * The following STANDARD_RIGHTS_* are combinations of the above for - * convenience and are defined by the Win32 API. - */ + /* + * The following STANDARD_RIGHTS_* are combinations of the above for + * convenience and are defined by the Win32 API. + */ - /* These are currently defined to READ_CONTROL. */ - STANDARD_RIGHTS_READ = const_cpu_to_le32(0x00020000), - STANDARD_RIGHTS_WRITE = const_cpu_to_le32(0x00020000), - STANDARD_RIGHTS_EXECUTE = const_cpu_to_le32(0x00020000), + /* These are currently defined to READ_CONTROL. */ + STANDARD_RIGHTS_READ = const_cpu_to_le32(0x00020000), + STANDARD_RIGHTS_WRITE = const_cpu_to_le32(0x00020000), + STANDARD_RIGHTS_EXECUTE = const_cpu_to_le32(0x00020000), - /* Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access. */ - STANDARD_RIGHTS_REQUIRED = const_cpu_to_le32(0x000f0000), + /* Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access. */ + STANDARD_RIGHTS_REQUIRED = const_cpu_to_le32(0x000f0000), - /* - * Combines DELETE, READ_CONTROL, WRITE_DAC, WRITE_OWNER, and - * SYNCHRONIZE access. - */ - STANDARD_RIGHTS_ALL = const_cpu_to_le32(0x001f0000), + /* + * Combines DELETE, READ_CONTROL, WRITE_DAC, WRITE_OWNER, and + * SYNCHRONIZE access. + */ + STANDARD_RIGHTS_ALL = const_cpu_to_le32(0x001f0000), - /* - * The access system ACL and maximum allowed access types (bits 24 to - * 25, bits 26 to 27 are reserved). - */ - ACCESS_SYSTEM_SECURITY = const_cpu_to_le32(0x01000000), - MAXIMUM_ALLOWED = const_cpu_to_le32(0x02000000), + /* + * The access system ACL and maximum allowed access types (bits 24 to + * 25, bits 26 to 27 are reserved). + */ + ACCESS_SYSTEM_SECURITY = const_cpu_to_le32(0x01000000), + MAXIMUM_ALLOWED = const_cpu_to_le32(0x02000000), - /* - * The generic rights (bits 28 to 31). These map onto the standard and - * specific rights. - */ + /* + * The generic rights (bits 28 to 31). These map onto the standard and + * specific rights. + */ - /* Read, write, and execute access. */ - GENERIC_ALL = const_cpu_to_le32(0x10000000), + /* Read, write, and execute access. */ + GENERIC_ALL = const_cpu_to_le32(0x10000000), - /* Execute access. */ - GENERIC_EXECUTE = const_cpu_to_le32(0x20000000), + /* Execute access. */ + GENERIC_EXECUTE = const_cpu_to_le32(0x20000000), - /* - * Write access. For files, this maps onto: - * FILE_APPEND_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | - * FILE_WRITE_EA | STANDARD_RIGHTS_WRITE | SYNCHRONIZE - * For directories, the mapping has the same numerical value. See - * above for the descriptions of the rights granted. - */ - GENERIC_WRITE = const_cpu_to_le32(0x40000000), + /* + * Write access. For files, this maps onto: + * FILE_APPEND_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | + * FILE_WRITE_EA | STANDARD_RIGHTS_WRITE | SYNCHRONIZE + * For directories, the mapping has the same numerical value. See + * above for the descriptions of the rights granted. + */ + GENERIC_WRITE = const_cpu_to_le32(0x40000000), - /* - * Read access. For files, this maps onto: - * FILE_READ_ATTRIBUTES | FILE_READ_DATA | FILE_READ_EA | - * STANDARD_RIGHTS_READ | SYNCHRONIZE - * For directories, the mapping has the same numerical value. See - * above for the descriptions of the rights granted. - */ - GENERIC_READ = const_cpu_to_le32(0x80000000), + /* + * Read access. For files, this maps onto: + * FILE_READ_ATTRIBUTES | FILE_READ_DATA | FILE_READ_EA | + * STANDARD_RIGHTS_READ | SYNCHRONIZE + * For directories, the mapping has the same numerical value. See + * above for the descriptions of the rights granted. + */ + GENERIC_READ = const_cpu_to_le32(0x80000000), } ACCESS_MASK; /** @@ -1714,10 +1617,10 @@ typedef enum { * FIXME: What exactly is this and what is it for? (AIA) */ typedef struct { - ACCESS_MASK generic_read; - ACCESS_MASK generic_write; - ACCESS_MASK generic_execute; - ACCESS_MASK generic_all; + ACCESS_MASK generic_read; + ACCESS_MASK generic_write; + ACCESS_MASK generic_execute; + ACCESS_MASK generic_all; } __attribute__((__packed__)) GENERIC_MAPPING; /* @@ -1730,49 +1633,42 @@ typedef struct { * ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, SYSTEM_AUDIT_ACE, SYSTEM_ALARM_ACE */ typedef struct { - /* 0 ACE_HEADER; -- Unfolded here as gcc doesn't like unnamed structs. */ - ACE_TYPES type; /* Type of the ACE. */ - ACE_FLAGS flags; /* Flags describing the ACE. */ - u16 size; /* Size in bytes of the ACE. */ +/* 0 ACE_HEADER; -- Unfolded here as gcc doesn't like unnamed structs. */ + ACE_TYPES type; /* Type of the ACE. */ + ACE_FLAGS flags; /* Flags describing the ACE. */ + u16 size; /* Size in bytes of the ACE. */ - /* 4*/ - ACCESS_MASK mask; /* Access mask associated with the ACE. */ - /* 8*/ - SID sid; /* The SID associated with the ACE. */ +/* 4*/ ACCESS_MASK mask; /* Access mask associated with the ACE. */ +/* 8*/ SID sid; /* The SID associated with the ACE. */ } __attribute__((__packed__)) ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, -SYSTEM_AUDIT_ACE, SYSTEM_ALARM_ACE; + SYSTEM_AUDIT_ACE, SYSTEM_ALARM_ACE; /** * enum OBJECT_ACE_FLAGS - The object ACE flags (32-bit). */ typedef enum { - ACE_OBJECT_TYPE_PRESENT = const_cpu_to_le32(1), - ACE_INHERITED_OBJECT_TYPE_PRESENT = const_cpu_to_le32(2), + ACE_OBJECT_TYPE_PRESENT = const_cpu_to_le32(1), + ACE_INHERITED_OBJECT_TYPE_PRESENT = const_cpu_to_le32(2), } OBJECT_ACE_FLAGS; /** * struct ACCESS_ALLOWED_OBJECT_ACE - */ typedef struct { - /* 0 ACE_HEADER; -- Unfolded here as gcc doesn't like unnamed structs. */ - ACE_TYPES type; /* Type of the ACE. */ - ACE_FLAGS flags; /* Flags describing the ACE. */ - u16 size; /* Size in bytes of the ACE. */ +/* 0 ACE_HEADER; -- Unfolded here as gcc doesn't like unnamed structs. */ + ACE_TYPES type; /* Type of the ACE. */ + ACE_FLAGS flags; /* Flags describing the ACE. */ + u16 size; /* Size in bytes of the ACE. */ - /* 4*/ - ACCESS_MASK mask; /* Access mask associated with the ACE. */ - /* 8*/ - OBJECT_ACE_FLAGS object_flags; /* Flags describing the object ACE. */ - /* 12*/ - GUID object_type; - /* 28*/ - GUID inherited_object_type; - /* 44*/ - SID sid; /* The SID associated with the ACE. */ +/* 4*/ ACCESS_MASK mask; /* Access mask associated with the ACE. */ +/* 8*/ OBJECT_ACE_FLAGS object_flags; /* Flags describing the object ACE. */ +/* 12*/ GUID object_type; +/* 28*/ GUID inherited_object_type; +/* 44*/ SID sid; /* The SID associated with the ACE. */ } __attribute__((__packed__)) ACCESS_ALLOWED_OBJECT_ACE, -ACCESS_DENIED_OBJECT_ACE, -SYSTEM_AUDIT_OBJECT_ACE, -SYSTEM_ALARM_OBJECT_ACE; + ACCESS_DENIED_OBJECT_ACE, + SYSTEM_AUDIT_OBJECT_ACE, + SYSTEM_ALARM_OBJECT_ACE; /** * struct ACL - An ACL is an access-control list (ACL). @@ -1783,30 +1679,30 @@ SYSTEM_ALARM_OBJECT_ACE; * are aligned on 4-byte boundaries. */ typedef struct { - u8 revision; /* Revision of this ACL. */ - u8 alignment1; - u16 size; /* Allocated space in bytes for ACL. Includes this + u8 revision; /* Revision of this ACL. */ + u8 alignment1; + u16 size; /* Allocated space in bytes for ACL. Includes this header, the ACEs and the remaining free space. */ - u16 ace_count; /* Number of ACEs in the ACL. */ - u16 alignment2; - /* sizeof() = 8 bytes */ + u16 ace_count; /* Number of ACEs in the ACL. */ + u16 alignment2; +/* sizeof() = 8 bytes */ } __attribute__((__packed__)) ACL; /** * enum ACL_CONSTANTS - Current constants for ACLs. */ typedef enum { - /* Current revision. */ - ACL_REVISION = 2, - ACL_REVISION_DS = 4, + /* Current revision. */ + ACL_REVISION = 2, + ACL_REVISION_DS = 4, - /* History of revisions. */ - ACL_REVISION1 = 1, - MIN_ACL_REVISION = 2, - ACL_REVISION2 = 2, - ACL_REVISION3 = 3, - ACL_REVISION4 = 4, - MAX_ACL_REVISION = 4, + /* History of revisions. */ + ACL_REVISION1 = 1, + MIN_ACL_REVISION = 2, + ACL_REVISION2 = 2, + ACL_REVISION3 = 3, + ACL_REVISION4 = 4, + MAX_ACL_REVISION = 4, } ACL_CONSTANTS; /** @@ -1859,20 +1755,20 @@ typedef enum { * beginning of the security descriptor. */ typedef enum { - SE_OWNER_DEFAULTED = const_cpu_to_le16(0x0001), - SE_GROUP_DEFAULTED = const_cpu_to_le16(0x0002), - SE_DACL_PRESENT = const_cpu_to_le16(0x0004), - SE_DACL_DEFAULTED = const_cpu_to_le16(0x0008), - SE_SACL_PRESENT = const_cpu_to_le16(0x0010), - SE_SACL_DEFAULTED = const_cpu_to_le16(0x0020), - SE_DACL_AUTO_INHERIT_REQ = const_cpu_to_le16(0x0100), - SE_SACL_AUTO_INHERIT_REQ = const_cpu_to_le16(0x0200), - SE_DACL_AUTO_INHERITED = const_cpu_to_le16(0x0400), - SE_SACL_AUTO_INHERITED = const_cpu_to_le16(0x0800), - SE_DACL_PROTECTED = const_cpu_to_le16(0x1000), - SE_SACL_PROTECTED = const_cpu_to_le16(0x2000), - SE_RM_CONTROL_VALID = const_cpu_to_le16(0x4000), - SE_SELF_RELATIVE = const_cpu_to_le16(0x8000), + SE_OWNER_DEFAULTED = const_cpu_to_le16(0x0001), + SE_GROUP_DEFAULTED = const_cpu_to_le16(0x0002), + SE_DACL_PRESENT = const_cpu_to_le16(0x0004), + SE_DACL_DEFAULTED = const_cpu_to_le16(0x0008), + SE_SACL_PRESENT = const_cpu_to_le16(0x0010), + SE_SACL_DEFAULTED = const_cpu_to_le16(0x0020), + SE_DACL_AUTO_INHERIT_REQ = const_cpu_to_le16(0x0100), + SE_SACL_AUTO_INHERIT_REQ = const_cpu_to_le16(0x0200), + SE_DACL_AUTO_INHERITED = const_cpu_to_le16(0x0400), + SE_SACL_AUTO_INHERITED = const_cpu_to_le16(0x0800), + SE_DACL_PROTECTED = const_cpu_to_le16(0x1000), + SE_SACL_PROTECTED = const_cpu_to_le16(0x2000), + SE_RM_CONTROL_VALID = const_cpu_to_le16(0x4000), + SE_SELF_RELATIVE = const_cpu_to_le16(0x8000), } __attribute__((__packed__)) SECURITY_DESCRIPTOR_CONTROL; /** @@ -1882,25 +1778,25 @@ typedef enum { * as the sacl and dacl ACLs inside the security descriptor itself. */ typedef struct { - u8 revision; /* Revision level of the security descriptor. */ - u8 alignment; - SECURITY_DESCRIPTOR_CONTROL control; /* Flags qualifying the type of + u8 revision; /* Revision level of the security descriptor. */ + u8 alignment; + SECURITY_DESCRIPTOR_CONTROL control; /* Flags qualifying the type of the descriptor as well as the following fields. */ - u32 owner; /* Byte offset to a SID representing an object's + u32 owner; /* Byte offset to a SID representing an object's owner. If this is NULL, no owner SID is present in the descriptor. */ - u32 group; /* Byte offset to a SID representing an object's + u32 group; /* Byte offset to a SID representing an object's primary group. If this is NULL, no primary group SID is present in the descriptor. */ - u32 sacl; /* Byte offset to a system ACL. Only valid, if + u32 sacl; /* Byte offset to a system ACL. Only valid, if SE_SACL_PRESENT is set in the control field. If SE_SACL_PRESENT is set but sacl is NULL, a NULL ACL is specified. */ - u32 dacl; /* Byte offset to a discretionary ACL. Only valid, if + u32 dacl; /* Byte offset to a discretionary ACL. Only valid, if SE_DACL_PRESENT is set in the control field. If SE_DACL_PRESENT is set but dacl is NULL, a NULL ACL (unconditionally granting access) is specified. */ - /* sizeof() = 0x14 bytes */ +/* sizeof() = 0x14 bytes */ } __attribute__((__packed__)) SECURITY_DESCRIPTOR_RELATIVE; /** @@ -1914,21 +1810,21 @@ typedef struct { * On disk, a self-relative security descriptor is used. */ typedef struct { - u8 revision; /* Revision level of the security descriptor. */ - u8 alignment; - SECURITY_DESCRIPTOR_CONTROL control; /* Flags qualifying the type of + u8 revision; /* Revision level of the security descriptor. */ + u8 alignment; + SECURITY_DESCRIPTOR_CONTROL control; /* Flags qualifying the type of the descriptor as well as the following fields. */ - SID *owner; /* Points to a SID representing an object's owner. If + SID *owner; /* Points to a SID representing an object's owner. If this is NULL, no owner SID is present in the descriptor. */ - SID *group; /* Points to a SID representing an object's primary + SID *group; /* Points to a SID representing an object's primary group. If this is NULL, no primary group SID is present in the descriptor. */ - ACL *sacl; /* Points to a system ACL. Only valid, if + ACL *sacl; /* Points to a system ACL. Only valid, if SE_SACL_PRESENT is set in the control field. If SE_SACL_PRESENT is set but sacl is NULL, a NULL ACL is specified. */ - ACL *dacl; /* Points to a discretionary ACL. Only valid, if + ACL *dacl; /* Points to a discretionary ACL. Only valid, if SE_DACL_PRESENT is set in the control field. If SE_DACL_PRESENT is set but dacl is NULL, a NULL ACL (unconditionally granting access) is specified. */ @@ -1940,13 +1836,13 @@ typedef struct { * Current constants for security descriptors. */ typedef enum { - /* Current revision. */ - SECURITY_DESCRIPTOR_REVISION = 1, - SECURITY_DESCRIPTOR_REVISION1 = 1, + /* Current revision. */ + SECURITY_DESCRIPTOR_REVISION = 1, + SECURITY_DESCRIPTOR_REVISION1 = 1, - /* The sizes of both the absolute and relative security descriptors is - the same as pointers, at least on ia32 architecture are 32-bit. */ - SECURITY_DESCRIPTOR_MIN_LENGTH = sizeof(SECURITY_DESCRIPTOR), + /* The sizes of both the absolute and relative security descriptors is + the same as pointers, at least on ia32 architecture are 32-bit. */ + SECURITY_DESCRIPTOR_MIN_LENGTH = sizeof(SECURITY_DESCRIPTOR), } SECURITY_DESCRIPTOR_CONSTANTS; /* @@ -2007,21 +1903,21 @@ typedef SECURITY_DESCRIPTOR_RELATIVE SECURITY_DESCRIPTOR_ATTR; * This is also the index entry data part of both the $SII and $SDH indexes. */ typedef struct { - u32 hash; /* Hash of the security descriptor. */ - u32 security_id; /* The security_id assigned to the descriptor. */ - u64 offset; /* Byte offset of this entry in the $SDS stream. */ - u32 length; /* Size in bytes of this entry in $SDS stream. */ + u32 hash; /* Hash of the security descriptor. */ + u32 security_id; /* The security_id assigned to the descriptor. */ + u64 offset; /* Byte offset of this entry in the $SDS stream. */ + u32 length; /* Size in bytes of this entry in $SDS stream. */ } __attribute__((__packed__)) SECURITY_DESCRIPTOR_HEADER; /** * struct SDH_INDEX_DATA - */ typedef struct { - u32 hash; /* Hash of the security descriptor. */ - u32 security_id; /* The security_id assigned to the descriptor. */ - u64 offset; /* Byte offset of this entry in the $SDS stream. */ - u32 length; /* Size in bytes of this entry in $SDS stream. */ - u32 reserved_II; /* Padding - always unicode "II" or zero. This field + u32 hash; /* Hash of the security descriptor. */ + u32 security_id; /* The security_id assigned to the descriptor. */ + u64 offset; /* Byte offset of this entry in the $SDS stream. */ + u32 length; /* Size in bytes of this entry in $SDS stream. */ + u32 reserved_II; /* Padding - always unicode "II" or zero. This field isn't counted in INDEX_ENTRY's data_length. */ } __attribute__((__packed__)) SDH_INDEX_DATA; @@ -2044,14 +1940,13 @@ typedef SECURITY_DESCRIPTOR_HEADER SII_INDEX_DATA; * $SDS data stream and the second copy will be at offset 0x451d0. */ typedef struct { - /* 0 SECURITY_DESCRIPTOR_HEADER; -- Unfolded here as gcc doesn't like - unnamed structs. */ - u32 hash; /* Hash of the security descriptor. */ - u32 security_id; /* The security_id assigned to the descriptor. */ - u64 offset; /* Byte offset of this entry in the $SDS stream. */ - u32 length; /* Size in bytes of this entry in $SDS stream. */ - /* 20*/ - SECURITY_DESCRIPTOR_RELATIVE sid; /* The self-relative security +/* 0 SECURITY_DESCRIPTOR_HEADER; -- Unfolded here as gcc doesn't like + unnamed structs. */ + u32 hash; /* Hash of the security descriptor. */ + u32 security_id; /* The security_id assigned to the descriptor. */ + u64 offset; /* Byte offset of this entry in the $SDS stream. */ + u32 length; /* Size in bytes of this entry in $SDS stream. */ +/* 20*/ SECURITY_DESCRIPTOR_RELATIVE sid; /* The self-relative security descriptor. */ } __attribute__((__packed__)) SDS_ENTRY; @@ -2061,7 +1956,7 @@ typedef struct { * The collation type is COLLATION_NTOFS_ULONG. */ typedef struct { - u32 security_id; /* The security_id assigned to the descriptor. */ + u32 security_id; /* The security_id assigned to the descriptor. */ } __attribute__((__packed__)) SII_INDEX_KEY; /** @@ -2071,8 +1966,8 @@ typedef struct { * The collation rule is COLLATION_NTOFS_SECURITY_HASH. */ typedef struct { - u32 hash; /* Hash of the security descriptor. */ - u32 security_id; /* The security_id assigned to the descriptor. */ + u32 hash; /* Hash of the security descriptor. */ + u32 security_id; /* The security_id assigned to the descriptor. */ } __attribute__((__packed__)) SDH_INDEX_KEY; /** @@ -2082,22 +1977,22 @@ typedef struct { * NOTE: Present only in FILE_Volume. */ typedef struct { - ntfschar name[0]; /* The name of the volume in Unicode. */ + ntfschar name[0]; /* The name of the volume in Unicode. */ } __attribute__((__packed__)) VOLUME_NAME; /** * enum VOLUME_FLAGS - Possible flags for the volume (16-bit). */ typedef enum { - VOLUME_IS_DIRTY = const_cpu_to_le16(0x0001), - VOLUME_RESIZE_LOG_FILE = const_cpu_to_le16(0x0002), - VOLUME_UPGRADE_ON_MOUNT = const_cpu_to_le16(0x0004), - VOLUME_MOUNTED_ON_NT4 = const_cpu_to_le16(0x0008), - VOLUME_DELETE_USN_UNDERWAY = const_cpu_to_le16(0x0010), - VOLUME_REPAIR_OBJECT_ID = const_cpu_to_le16(0x0020), - VOLUME_CHKDSK_UNDERWAY = const_cpu_to_le16(0x4000), - VOLUME_MODIFIED_BY_CHKDSK = const_cpu_to_le16(0x8000), - VOLUME_FLAGS_MASK = const_cpu_to_le16(0xc03f), + VOLUME_IS_DIRTY = const_cpu_to_le16(0x0001), + VOLUME_RESIZE_LOG_FILE = const_cpu_to_le16(0x0002), + VOLUME_UPGRADE_ON_MOUNT = const_cpu_to_le16(0x0004), + VOLUME_MOUNTED_ON_NT4 = const_cpu_to_le16(0x0008), + VOLUME_DELETE_USN_UNDERWAY = const_cpu_to_le16(0x0010), + VOLUME_REPAIR_OBJECT_ID = const_cpu_to_le16(0x0020), + VOLUME_CHKDSK_UNDERWAY = const_cpu_to_le16(0x4000), + VOLUME_MODIFIED_BY_CHKDSK = const_cpu_to_le16(0x8000), + VOLUME_FLAGS_MASK = const_cpu_to_le16(0xc03f), } __attribute__((__packed__)) VOLUME_FLAGS; /** @@ -2109,10 +2004,10 @@ typedef enum { * NTFS 1.2. I haven't personally seen other values yet. */ typedef struct { - u64 reserved; /* Not used (yet?). */ - u8 major_ver; /* Major version of the ntfs format. */ - u8 minor_ver; /* Minor version of the ntfs format. */ - VOLUME_FLAGS flags; /* Bit array of VOLUME_* flags. */ + u64 reserved; /* Not used (yet?). */ + u8 major_ver; /* Major version of the ntfs format. */ + u8 minor_ver; /* Minor version of the ntfs format. */ + VOLUME_FLAGS flags; /* Bit array of VOLUME_* flags. */ } __attribute__((__packed__)) VOLUME_INFORMATION; /** @@ -2123,29 +2018,29 @@ typedef struct { * Data contents of a file (i.e. the unnamed stream) or of a named stream. */ typedef struct { - u8 data[0]; /* The file's data contents. */ + u8 data[0]; /* The file's data contents. */ } __attribute__((__packed__)) DATA_ATTR; /** * enum INDEX_HEADER_FLAGS - Index header flags (8-bit). */ typedef enum { - /* When index header is in an index root attribute: */ - SMALL_INDEX = 0, /* The index is small enough to fit inside the + /* When index header is in an index root attribute: */ + SMALL_INDEX = 0, /* The index is small enough to fit inside the index root attribute and there is no index allocation attribute present. */ - LARGE_INDEX = 1, /* The index is too large to fit in the index + LARGE_INDEX = 1, /* The index is too large to fit in the index root attribute and/or an index allocation attribute is present. */ - /* - * When index header is in an index block, i.e. is part of index - * allocation attribute: - */ - LEAF_NODE = 0, /* This is a leaf node, i.e. there are no more + /* + * When index header is in an index block, i.e. is part of index + * allocation attribute: + */ + LEAF_NODE = 0, /* This is a leaf node, i.e. there are no more nodes branching off it. */ - INDEX_NODE = 1, /* This node indexes other nodes, i.e. is not a + INDEX_NODE = 1, /* This node indexes other nodes, i.e. is not a leaf node. */ - NODE_MASK = 1, /* Mask for accessing the *_NODE bits. */ + NODE_MASK = 1, /* Mask for accessing the *_NODE bits. */ } __attribute__((__packed__)) INDEX_HEADER_FLAGS; /** @@ -2160,29 +2055,24 @@ typedef enum { * start of the index root or index allocation structures themselves. */ typedef struct { - /* 0*/ - u32 entries_offset; /* Byte offset from the INDEX_HEADER to first +/* 0*/ u32 entries_offset; /* Byte offset from the INDEX_HEADER to first INDEX_ENTRY, aligned to 8-byte boundary. */ - /* 4*/ - u32 index_length; /* Data size in byte of the INDEX_ENTRY's, +/* 4*/ u32 index_length; /* Data size in byte of the INDEX_ENTRY's, including the INDEX_HEADER, aligned to 8. */ - /* 8*/ - u32 allocated_size; /* Allocated byte size of this index (block), +/* 8*/ u32 allocated_size; /* Allocated byte size of this index (block), multiple of 8 bytes. See more below. */ - /* - For the index root attribute, the above two numbers are always - equal, as the attribute is resident and it is resized as needed. - - For the index allocation attribute, the attribute is not resident - and the allocated_size is equal to the index_block_size specified - by the corresponding INDEX_ROOT attribute minus the INDEX_BLOCK - size not counting the INDEX_HEADER part (i.e. minus -24). - */ - /* 12*/ - INDEX_HEADER_FLAGS ih_flags; /* Bit field of INDEX_HEADER_FLAGS. */ - /* 13*/ - u8 reserved[3]; /* Reserved/align to 8-byte boundary.*/ - /* sizeof() == 16 */ + /* + For the index root attribute, the above two numbers are always + equal, as the attribute is resident and it is resized as needed. + + For the index allocation attribute, the attribute is not resident + and the allocated_size is equal to the index_block_size specified + by the corresponding INDEX_ROOT attribute minus the INDEX_BLOCK + size not counting the INDEX_HEADER part (i.e. minus -24). + */ +/* 12*/ INDEX_HEADER_FLAGS ih_flags; /* Bit field of INDEX_HEADER_FLAGS. */ +/* 13*/ u8 reserved[3]; /* Reserved/align to 8-byte boundary.*/ +/* sizeof() == 16 */ } __attribute__((__packed__)) INDEX_HEADER; /** @@ -2205,29 +2095,23 @@ typedef struct { * directories do not contain entries for themselves, though. */ typedef struct { - /* 0*/ - ATTR_TYPES type; /* Type of the indexed attribute. Is +/* 0*/ ATTR_TYPES type; /* Type of the indexed attribute. Is $FILE_NAME for directories, zero for view indexes. No other values allowed. */ - /* 4*/ - COLLATION_RULES collation_rule; /* Collation rule used to sort the +/* 4*/ COLLATION_RULES collation_rule; /* Collation rule used to sort the index entries. If type is $FILE_NAME, this must be COLLATION_FILE_NAME. */ - /* 8*/ - u32 index_block_size; /* Size of index block in bytes (in +/* 8*/ u32 index_block_size; /* Size of index block in bytes (in the index allocation attribute). */ - /* 12*/ - s8 clusters_per_index_block; /* Size of index block in clusters (in +/* 12*/ s8 clusters_per_index_block; /* Size of index block in clusters (in the index allocation attribute), when an index block is >= than a cluster, otherwise sectors per index block. */ - /* 13*/ - u8 reserved[3]; /* Reserved/align to 8-byte boundary. */ - /* 16*/ - INDEX_HEADER index; /* Index header describing the +/* 13*/ u8 reserved[3]; /* Reserved/align to 8-byte boundary. */ +/* 16*/ INDEX_HEADER index; /* Index header describing the following index entries. */ - /* sizeof()= 32 bytes */ +/* sizeof()= 32 bytes */ } __attribute__((__packed__)) INDEX_ROOT; /** @@ -2240,28 +2124,25 @@ typedef struct { * index entries (INDEX_ENTRY structures), as described by the INDEX_HEADER. */ typedef struct { - /* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ - NTFS_RECORD_TYPES magic;/* Magic is "INDX". */ - u16 usa_ofs; /* See NTFS_RECORD definition. */ - u16 usa_count; /* See NTFS_RECORD definition. */ +/* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ + NTFS_RECORD_TYPES magic;/* Magic is "INDX". */ + u16 usa_ofs; /* See NTFS_RECORD definition. */ + u16 usa_count; /* See NTFS_RECORD definition. */ - /* 8*/ - LSN lsn; /* $LogFile sequence number of the last +/* 8*/ LSN lsn; /* $LogFile sequence number of the last modification of this index block. */ - /* 16*/ - VCN index_block_vcn; /* Virtual cluster number of the index block. */ - /* 24*/ - INDEX_HEADER index; /* Describes the following index entries. */ - /* sizeof()= 40 (0x28) bytes */ - /* - * When creating the index block, we place the update sequence array at this - * offset, i.e. before we start with the index entries. This also makes sense, - * otherwise we could run into problems with the update sequence array - * containing in itself the last two bytes of a sector which would mean that - * multi sector transfer protection wouldn't work. As you can't protect data - * by overwriting it since you then can't get it back... - * When reading use the data from the ntfs record header. - */ +/* 16*/ VCN index_block_vcn; /* Virtual cluster number of the index block. */ +/* 24*/ INDEX_HEADER index; /* Describes the following index entries. */ +/* sizeof()= 40 (0x28) bytes */ +/* + * When creating the index block, we place the update sequence array at this + * offset, i.e. before we start with the index entries. This also makes sense, + * otherwise we could run into problems with the update sequence array + * containing in itself the last two bytes of a sector which would mean that + * multi sector transfer protection wouldn't work. As you can't protect data + * by overwriting it since you then can't get it back... + * When reading use the data from the ntfs record header. + */ } __attribute__((__packed__)) INDEX_BLOCK; typedef INDEX_BLOCK INDEX_ALLOCATION; @@ -2278,8 +2159,8 @@ typedef INDEX_BLOCK INDEX_ALLOCATION; * primary key / is not a key at all. (AIA) */ typedef struct { - u32 reparse_tag; /* Reparse point type (inc. flags). */ - MFT_REF file_id; /* Mft record of the file containing the + u32 reparse_tag; /* Reparse point type (inc. flags). */ + MFT_REF file_id; /* Mft record of the file containing the reparse point attribute. */ } __attribute__((__packed__)) REPARSE_INDEX_KEY; @@ -2287,24 +2168,24 @@ typedef struct { * enum QUOTA_FLAGS - Quota flags (32-bit). */ typedef enum { - /* The user quota flags. Names explain meaning. */ - QUOTA_FLAG_DEFAULT_LIMITS = const_cpu_to_le32(0x00000001), - QUOTA_FLAG_LIMIT_REACHED = const_cpu_to_le32(0x00000002), - QUOTA_FLAG_ID_DELETED = const_cpu_to_le32(0x00000004), + /* The user quota flags. Names explain meaning. */ + QUOTA_FLAG_DEFAULT_LIMITS = const_cpu_to_le32(0x00000001), + QUOTA_FLAG_LIMIT_REACHED = const_cpu_to_le32(0x00000002), + QUOTA_FLAG_ID_DELETED = const_cpu_to_le32(0x00000004), - QUOTA_FLAG_USER_MASK = const_cpu_to_le32(0x00000007), - /* Bit mask for user quota flags. */ + QUOTA_FLAG_USER_MASK = const_cpu_to_le32(0x00000007), + /* Bit mask for user quota flags. */ - /* These flags are only present in the quota defaults index entry, - i.e. in the entry where owner_id = QUOTA_DEFAULTS_ID. */ - QUOTA_FLAG_TRACKING_ENABLED = const_cpu_to_le32(0x00000010), - QUOTA_FLAG_ENFORCEMENT_ENABLED = const_cpu_to_le32(0x00000020), - QUOTA_FLAG_TRACKING_REQUESTED = const_cpu_to_le32(0x00000040), - QUOTA_FLAG_LOG_THRESHOLD = const_cpu_to_le32(0x00000080), - QUOTA_FLAG_LOG_LIMIT = const_cpu_to_le32(0x00000100), - QUOTA_FLAG_OUT_OF_DATE = const_cpu_to_le32(0x00000200), - QUOTA_FLAG_CORRUPT = const_cpu_to_le32(0x00000400), - QUOTA_FLAG_PENDING_DELETES = const_cpu_to_le32(0x00000800), + /* These flags are only present in the quota defaults index entry, + i.e. in the entry where owner_id = QUOTA_DEFAULTS_ID. */ + QUOTA_FLAG_TRACKING_ENABLED = const_cpu_to_le32(0x00000010), + QUOTA_FLAG_ENFORCEMENT_ENABLED = const_cpu_to_le32(0x00000020), + QUOTA_FLAG_TRACKING_REQUESTED = const_cpu_to_le32(0x00000040), + QUOTA_FLAG_LOG_THRESHOLD = const_cpu_to_le32(0x00000080), + QUOTA_FLAG_LOG_LIMIT = const_cpu_to_le32(0x00000100), + QUOTA_FLAG_OUT_OF_DATE = const_cpu_to_le32(0x00000200), + QUOTA_FLAG_CORRUPT = const_cpu_to_le32(0x00000400), + QUOTA_FLAG_PENDING_DELETES = const_cpu_to_le32(0x00000800), } QUOTA_FLAGS; /** @@ -2331,15 +2212,15 @@ typedef enum { * The $Q index entry data is the quota control entry and is defined below. */ typedef struct { - u32 version; /* Currently equals 2. */ - QUOTA_FLAGS flags; /* Flags describing this quota entry. */ - u64 bytes_used; /* How many bytes of the quota are in use. */ - s64 change_time; /* Last time this quota entry was changed. */ - s64 threshold; /* Soft quota (-1 if not limited). */ - s64 limit; /* Hard quota (-1 if not limited). */ - s64 exceeded_time; /* How long the soft quota has been exceeded. */ - /* The below field is NOT present for the quota defaults entry. */ - SID sid; /* The SID of the user/object associated with + u32 version; /* Currently equals 2. */ + QUOTA_FLAGS flags; /* Flags describing this quota entry. */ + u64 bytes_used; /* How many bytes of the quota are in use. */ + s64 change_time; /* Last time this quota entry was changed. */ + s64 threshold; /* Soft quota (-1 if not limited). */ + s64 limit; /* Hard quota (-1 if not limited). */ + s64 exceeded_time; /* How long the soft quota has been exceeded. */ +/* The below field is NOT present for the quota defaults entry. */ + SID sid; /* The SID of the user/object associated with this quota entry. If this field is missing then the INDEX_ENTRY is padded with zeros to multiply of 8 which are not counted in @@ -2353,8 +2234,8 @@ typedef struct { * struct QUOTA_O_INDEX_DATA - */ typedef struct { - u32 owner_id; - u32 unknown; /* Always 32. Seems to be padding and it's not + u32 owner_id; + u32 unknown; /* Always 32. Seems to be padding and it's not counted in the INDEX_ENTRY's data_length. This field shouldn't be really here. */ } __attribute__((__packed__)) QUOTA_O_INDEX_DATA; @@ -2363,52 +2244,47 @@ typedef struct { * enum PREDEFINED_OWNER_IDS - Predefined owner_id values (32-bit). */ typedef enum { - QUOTA_INVALID_ID = const_cpu_to_le32(0x00000000), - QUOTA_DEFAULTS_ID = const_cpu_to_le32(0x00000001), - QUOTA_FIRST_USER_ID = const_cpu_to_le32(0x00000100), + QUOTA_INVALID_ID = const_cpu_to_le32(0x00000000), + QUOTA_DEFAULTS_ID = const_cpu_to_le32(0x00000001), + QUOTA_FIRST_USER_ID = const_cpu_to_le32(0x00000100), } PREDEFINED_OWNER_IDS; /** * enum INDEX_ENTRY_FLAGS - Index entry flags (16-bit). */ typedef enum { - INDEX_ENTRY_NODE = const_cpu_to_le16(1), /* This entry contains a + INDEX_ENTRY_NODE = const_cpu_to_le16(1), /* This entry contains a sub-node, i.e. a reference to an index block in form of a virtual cluster number (see below). */ - INDEX_ENTRY_END = const_cpu_to_le16(2), /* This signifies the last + INDEX_ENTRY_END = const_cpu_to_le16(2), /* This signifies the last entry in an index block. The index entry does not represent a file but it can point to a sub-node. */ - INDEX_ENTRY_SPACE_FILLER = 0xffff, /* Just to force 16-bit width. */ + INDEX_ENTRY_SPACE_FILLER = 0xffff, /* Just to force 16-bit width. */ } __attribute__((__packed__)) INDEX_ENTRY_FLAGS; /** * struct INDEX_ENTRY_HEADER - This the index entry header (see below). - * + * * ========================================================== * !!!!! SEE DESCRIPTION OF THE FIELDS AT INDEX_ENTRY !!!!! * ========================================================== */ typedef struct { - /* 0*/ - union { - MFT_REF indexed_file; - struct { - u16 data_offset; - u16 data_length; - u32 reservedV; - } __attribute__((__packed__)); - } __attribute__((__packed__)); - /* 8*/ - u16 length; - /* 10*/ - u16 key_length; - /* 12*/ - INDEX_ENTRY_FLAGS flags; - /* 14*/ - u16 reserved; - /* sizeof() = 16 bytes */ +/* 0*/ union { + MFT_REF indexed_file; + struct { + u16 data_offset; + u16 data_length; + u32 reservedV; + } __attribute__((__packed__)); + } __attribute__((__packed__)); +/* 8*/ u16 length; +/* 10*/ u16 key_length; +/* 12*/ INDEX_ENTRY_FLAGS flags; +/* 14*/ u16 reserved; +/* sizeof() = 16 bytes */ } __attribute__((__packed__)) INDEX_ENTRY_HEADER; /** @@ -2421,66 +2297,61 @@ typedef struct { * NOTE: Before NTFS 3.0 only filename attributes were indexed. */ typedef struct { - /* 0 INDEX_ENTRY_HEADER; -- Unfolded here as gcc dislikes unnamed structs. */ - union { /* Only valid when INDEX_ENTRY_END is not set. */ - MFT_REF indexed_file; /* The mft reference of the file +/* 0 INDEX_ENTRY_HEADER; -- Unfolded here as gcc dislikes unnamed structs. */ + union { /* Only valid when INDEX_ENTRY_END is not set. */ + MFT_REF indexed_file; /* The mft reference of the file described by this index entry. Used for directory indexes. */ - struct { /* Used for views/indexes to find the entry's data. */ - u16 data_offset; /* Data byte offset from this + struct { /* Used for views/indexes to find the entry's data. */ + u16 data_offset; /* Data byte offset from this INDEX_ENTRY. Follows the index key. */ - u16 data_length; /* Data length in bytes. */ - u32 reservedV; /* Reserved (zero). */ - } __attribute__((__packed__)); - } __attribute__((__packed__)); - /* 8*/ - u16 length; /* Byte size of this index entry, multiple of + u16 data_length; /* Data length in bytes. */ + u32 reservedV; /* Reserved (zero). */ + } __attribute__((__packed__)); + } __attribute__((__packed__)); +/* 8*/ u16 length; /* Byte size of this index entry, multiple of 8-bytes. Size includes INDEX_ENTRY_HEADER and the optional subnode VCN. See below. */ - /* 10*/ - u16 key_length; /* Byte size of the key value, which is in the +/* 10*/ u16 key_length; /* Byte size of the key value, which is in the index entry. It follows field reserved. Not multiple of 8-bytes. */ - /* 12*/ - INDEX_ENTRY_FLAGS ie_flags; /* Bit field of INDEX_ENTRY_* flags. */ - /* 14*/ - u16 reserved; /* Reserved/align to 8-byte boundary. */ - /* End of INDEX_ENTRY_HEADER */ - /* 16*/ - union { /* The key of the indexed attribute. NOTE: Only present +/* 12*/ INDEX_ENTRY_FLAGS ie_flags; /* Bit field of INDEX_ENTRY_* flags. */ +/* 14*/ u16 reserved; /* Reserved/align to 8-byte boundary. */ +/* End of INDEX_ENTRY_HEADER */ +/* 16*/ union { /* The key of the indexed attribute. NOTE: Only present if INDEX_ENTRY_END bit in flags is not set. NOTE: On NTFS versions before 3.0 the only valid key is the FILE_NAME_ATTR. On NTFS 3.0+ the following additional index keys are defined: */ - FILE_NAME_ATTR file_name;/* $I30 index in directories. */ - SII_INDEX_KEY sii; /* $SII index in $Secure. */ - SDH_INDEX_KEY sdh; /* $SDH index in $Secure. */ - GUID object_id; /* $O index in FILE_Extend/$ObjId: The + FILE_NAME_ATTR file_name;/* $I30 index in directories. */ + SII_INDEX_KEY sii; /* $SII index in $Secure. */ + SDH_INDEX_KEY sdh; /* $SDH index in $Secure. */ + GUID object_id; /* $O index in FILE_Extend/$ObjId: The object_id of the mft record found in the data part of the index. */ - REPARSE_INDEX_KEY reparse; /* $R index in + REPARSE_INDEX_KEY reparse; /* $R index in FILE_Extend/$Reparse. */ - SID sid; /* $O index in FILE_Extend/$Quota: + SID sid; /* $O index in FILE_Extend/$Quota: SID of the owner of the user_id. */ - u32 owner_id; /* $Q index in FILE_Extend/$Quota: + u32 owner_id; /* $Q index in FILE_Extend/$Quota: user_id of the owner of the quota control entry in the data part of the index. */ - } __attribute__((__packed__)) key; - /* The (optional) index data is inserted here when creating. - VCN vcn; If INDEX_ENTRY_NODE bit in ie_flags is set, the last - eight bytes of this index entry contain the virtual - cluster number of the index block that holds the - entries immediately preceding the current entry. - - If the key_length is zero, then the vcn immediately - follows the INDEX_ENTRY_HEADER. - - The address of the vcn of "ie" INDEX_ENTRY is given by - (char*)ie + le16_to_cpu(ie->length) - sizeof(VCN) - */ + } __attribute__((__packed__)) key; + /* The (optional) index data is inserted here when creating. + VCN vcn; If INDEX_ENTRY_NODE bit in ie_flags is set, the last + eight bytes of this index entry contain the virtual + cluster number of the index block that holds the + entries immediately preceding the current entry. + + If the key_length is zero, then the vcn immediately + follows the INDEX_ENTRY_HEADER. + + The address of the vcn of "ie" INDEX_ENTRY is given by + (char*)ie + le16_to_cpu(ie->length) - sizeof(VCN) + */ } __attribute__((__packed__)) INDEX_ENTRY; /** @@ -2494,7 +2365,7 @@ typedef struct { * number of clusters in the index allocation attribute. */ typedef struct { - u8 bitmap[0]; /* Array of bits. */ + u8 bitmap[0]; /* Array of bits. */ } __attribute__((__packed__)) BITMAP_ATTR; /** @@ -2518,26 +2389,26 @@ typedef struct { * defined tags have to use zero here. */ typedef enum { - IO_REPARSE_TAG_IS_ALIAS = const_cpu_to_le32(0x20000000), - IO_REPARSE_TAG_IS_HIGH_LATENCY = const_cpu_to_le32(0x40000000), - IO_REPARSE_TAG_IS_MICROSOFT = const_cpu_to_le32(0x80000000), + IO_REPARSE_TAG_IS_ALIAS = const_cpu_to_le32(0x20000000), + IO_REPARSE_TAG_IS_HIGH_LATENCY = const_cpu_to_le32(0x40000000), + IO_REPARSE_TAG_IS_MICROSOFT = const_cpu_to_le32(0x80000000), - IO_REPARSE_TAG_RESERVED_ZERO = const_cpu_to_le32(0x00000000), - IO_REPARSE_TAG_RESERVED_ONE = const_cpu_to_le32(0x00000001), - IO_REPARSE_TAG_RESERVED_RANGE = const_cpu_to_le32(0x00000001), + IO_REPARSE_TAG_RESERVED_ZERO = const_cpu_to_le32(0x00000000), + IO_REPARSE_TAG_RESERVED_ONE = const_cpu_to_le32(0x00000001), + IO_REPARSE_TAG_RESERVED_RANGE = const_cpu_to_le32(0x00000001), - IO_REPARSE_TAG_NSS = const_cpu_to_le32(0x68000005), - IO_REPARSE_TAG_NSS_RECOVER = const_cpu_to_le32(0x68000006), - IO_REPARSE_TAG_SIS = const_cpu_to_le32(0x68000007), - IO_REPARSE_TAG_DFS = const_cpu_to_le32(0x68000008), + IO_REPARSE_TAG_NSS = const_cpu_to_le32(0x68000005), + IO_REPARSE_TAG_NSS_RECOVER = const_cpu_to_le32(0x68000006), + IO_REPARSE_TAG_SIS = const_cpu_to_le32(0x68000007), + IO_REPARSE_TAG_DFS = const_cpu_to_le32(0x68000008), - IO_REPARSE_TAG_MOUNT_POINT = const_cpu_to_le32(0x88000003), + IO_REPARSE_TAG_MOUNT_POINT = const_cpu_to_le32(0x88000003), - IO_REPARSE_TAG_HSM = const_cpu_to_le32(0xa8000004), + IO_REPARSE_TAG_HSM = const_cpu_to_le32(0xa8000004), - IO_REPARSE_TAG_SYMBOLIC_LINK = const_cpu_to_le32(0xe8000000), + IO_REPARSE_TAG_SYMBOLIC_LINK = const_cpu_to_le32(0xe8000000), - IO_REPARSE_TAG_VALID_VALUES = const_cpu_to_le32(0xe000ffff), + IO_REPARSE_TAG_VALID_VALUES = const_cpu_to_le32(0xe000ffff), } PREDEFINED_REPARSE_TAGS; /** @@ -2546,10 +2417,10 @@ typedef enum { * NOTE: Can be resident or non-resident. */ typedef struct { - u32 reparse_tag; /* Reparse point type (inc. flags). */ - u16 reparse_data_length; /* Byte size of reparse data. */ - u16 reserved; /* Align to 8-byte boundary. */ - u8 reparse_data[0]; /* Meaning depends on reparse_tag. */ + u32 reparse_tag; /* Reparse point type (inc. flags). */ + u16 reparse_data_length; /* Byte size of reparse data. */ + u16 reserved; /* Align to 8-byte boundary. */ + u8 reparse_data[0]; /* Meaning depends on reparse_tag. */ } __attribute__((__packed__)) REPARSE_POINT; /** @@ -2558,11 +2429,11 @@ typedef struct { * NOTE: Always resident. */ typedef struct { - u16 ea_length; /* Byte size of the packed extended + u16 ea_length; /* Byte size of the packed extended attributes. */ - u16 need_ea_count; /* The number of extended attributes which have + u16 need_ea_count; /* The number of extended attributes which have the NEED_EA bit set. */ - u32 ea_query_length; /* Byte size of the buffer required to query + u32 ea_query_length; /* Byte size of the buffer required to query the extended attributes when calling ZwQueryEaFile() in Windows NT/2k. I.e. the byte size of the unpacked extended @@ -2573,7 +2444,7 @@ typedef struct { * enum EA_FLAGS - Extended attribute flags (8-bit). */ typedef enum { - NEED_EA = 0x80, /* Indicate that the file to which the EA + NEED_EA = 0x80, /* Indicate that the file to which the EA belongs cannot be interpreted without understanding the associated extended attributes. */ @@ -2589,13 +2460,13 @@ typedef enum { * FIXME: It seems that name is always uppercased. Is it true? */ typedef struct { - u32 next_entry_offset; /* Offset to the next EA_ATTR. */ - EA_FLAGS flags; /* Flags describing the EA. */ - u8 name_length; /* Length of the name of the extended + u32 next_entry_offset; /* Offset to the next EA_ATTR. */ + EA_FLAGS flags; /* Flags describing the EA. */ + u8 name_length; /* Length of the name of the extended attribute in bytes. */ - u16 value_length; /* Byte size of the EA's value. */ - u8 name[0]; /* Name of the EA. */ - u8 value[0]; /* The value of the EA. Immediately + u16 value_length; /* Byte size of the EA's value. */ + u8 name[0]; /* Name of the EA. */ + u8 value[0]; /* The value of the EA. Immediately follows the name. */ } __attribute__((__packed__)) EA_ATTR; @@ -2606,7 +2477,7 @@ typedef struct { * NTFS 3.0 during beta testing. */ typedef struct { - /* Irrelevant as feature unused. */ + /* Irrelevant as feature unused. */ } __attribute__((__packed__)) PROPERTY_SET; /** @@ -2621,7 +2492,7 @@ typedef struct { * attribute with the name $EFS. See below for the relevant structures. */ typedef struct { - /* Can be anything the creator chooses. */ + /* Can be anything the creator chooses. */ } __attribute__((__packed__)) LOGGED_UTILITY_STREAM; /* @@ -2657,36 +2528,31 @@ typedef struct { * The header of the Logged utility stream (0x100) attribute named "$EFS". */ typedef struct { - /* 0*/ - u32 length; /* Length of EFS attribute in bytes. */ - u32 state; /* Always 0? */ - u32 version; /* Efs version. Always 2? */ - u32 crypto_api_version; /* Always 0? */ - /* 16*/ - u8 unknown4[16]; /* MD5 hash of decrypted FEK? This field is +/* 0*/ u32 length; /* Length of EFS attribute in bytes. */ + u32 state; /* Always 0? */ + u32 version; /* Efs version. Always 2? */ + u32 crypto_api_version; /* Always 0? */ +/* 16*/ u8 unknown4[16]; /* MD5 hash of decrypted FEK? This field is created with a call to UuidCreate() so is unlikely to be an MD5 hash and is more likely to be GUID of this encrytped file or something like that. */ - /* 32*/ - u8 unknown5[16]; /* MD5 hash of DDFs? */ - /* 48*/ - u8 unknown6[16]; /* MD5 hash of DRFs? */ - /* 64*/ - u32 offset_to_ddf_array;/* Offset in bytes to the array of data +/* 32*/ u8 unknown5[16]; /* MD5 hash of DDFs? */ +/* 48*/ u8 unknown6[16]; /* MD5 hash of DRFs? */ +/* 64*/ u32 offset_to_ddf_array;/* Offset in bytes to the array of data decryption fields (DDF), see below. Zero if no DDFs are present. */ - u32 offset_to_drf_array;/* Offset in bytes to the array of data + u32 offset_to_drf_array;/* Offset in bytes to the array of data recovery fields (DRF), see below. Zero if no DRFs are present. */ - u32 reserved; /* Reserved. */ + u32 reserved; /* Reserved. */ } __attribute__((__packed__)) EFS_ATTR_HEADER; /** * struct EFS_DF_ARRAY_HEADER - */ typedef struct { - u32 df_count; /* Number of data decryption/recovery fields in + u32 df_count; /* Number of data decryption/recovery fields in the array. */ } __attribute__((__packed__)) EFS_DF_ARRAY_HEADER; @@ -2694,65 +2560,56 @@ typedef struct { * struct EFS_DF_HEADER - */ typedef struct { - /* 0*/ - u32 df_length; /* Length of this data decryption/recovery +/* 0*/ u32 df_length; /* Length of this data decryption/recovery field in bytes. */ - u32 cred_header_offset; /* Offset in bytes to the credential header. */ - u32 fek_size; /* Size in bytes of the encrypted file + u32 cred_header_offset; /* Offset in bytes to the credential header. */ + u32 fek_size; /* Size in bytes of the encrypted file encryption key (FEK). */ - u32 fek_offset; /* Offset in bytes to the FEK from the start of + u32 fek_offset; /* Offset in bytes to the FEK from the start of the data decryption/recovery field. */ - /* 16*/ - u32 unknown1; /* always 0? Might be just padding. */ +/* 16*/ u32 unknown1; /* always 0? Might be just padding. */ } __attribute__((__packed__)) EFS_DF_HEADER; /** * struct EFS_DF_CREDENTIAL_HEADER - */ typedef struct { - /* 0*/ - u32 cred_length; /* Length of this credential in bytes. */ - u32 sid_offset; /* Offset in bytes to the user's sid from start +/* 0*/ u32 cred_length; /* Length of this credential in bytes. */ + u32 sid_offset; /* Offset in bytes to the user's sid from start of this structure. Zero if no sid is present. */ - /* 8*/ - u32 type; /* Type of this credential: +/* 8*/ u32 type; /* Type of this credential: 1 = CryptoAPI container. 2 = Unexpected type. 3 = Certificate thumbprint. other = Unknown type. */ - union { - /* CryptoAPI container. */ - struct { - /* 12*/ - u32 container_name_offset; /* Offset in bytes to + union { + /* CryptoAPI container. */ + struct { +/* 12*/ u32 container_name_offset; /* Offset in bytes to the name of the container from start of this structure (may not be zero). */ - /* 16*/ - u32 provider_name_offset; /* Offset in bytes to +/* 16*/ u32 provider_name_offset; /* Offset in bytes to the name of the provider from start of this structure (may not be zero). */ - u32 public_key_blob_offset; /* Offset in bytes to + u32 public_key_blob_offset; /* Offset in bytes to the public key blob from start of this structure. */ - /* 24*/ - u32 public_key_blob_size; /* Size in bytes of +/* 24*/ u32 public_key_blob_size; /* Size in bytes of public key blob. */ - } __attribute__((__packed__)); - /* Certificate thumbprint. */ - struct { - /* 12*/ - u32 cert_thumbprint_header_size; /* Size in + } __attribute__((__packed__)); + /* Certificate thumbprint. */ + struct { +/* 12*/ u32 cert_thumbprint_header_size; /* Size in bytes of the header of the certificate thumbprint. */ - /* 16*/ - u32 cert_thumbprint_header_offset; /* Offset in +/* 16*/ u32 cert_thumbprint_header_offset; /* Offset in bytes to the header of the certificate thumbprint from start of this structure. */ - u32 unknown1; /* Always 0? Might be padding... */ - u32 unknown2; /* Always 0? Might be padding... */ - } __attribute__((__packed__)); - } __attribute__((__packed__)); + u32 unknown1; /* Always 0? Might be padding... */ + u32 unknown2; /* Always 0? Might be padding... */ + } __attribute__((__packed__)); + } __attribute__((__packed__)); } __attribute__((__packed__)) EFS_DF_CREDENTIAL_HEADER; typedef EFS_DF_CREDENTIAL_HEADER EFS_DF_CRED_HEADER; @@ -2761,19 +2618,16 @@ typedef EFS_DF_CREDENTIAL_HEADER EFS_DF_CRED_HEADER; * struct EFS_DF_CERTIFICATE_THUMBPRINT_HEADER - */ typedef struct { - /* 0*/ - u32 thumbprint_offset; /* Offset in bytes to the thumbprint. */ - u32 thumbprint_size; /* Size of thumbprint in bytes. */ - /* 8*/ - u32 container_name_offset; /* Offset in bytes to the name of the +/* 0*/ u32 thumbprint_offset; /* Offset in bytes to the thumbprint. */ + u32 thumbprint_size; /* Size of thumbprint in bytes. */ +/* 8*/ u32 container_name_offset; /* Offset in bytes to the name of the container from start of this structure or 0 if no name present. */ - u32 provider_name_offset; /* Offset in bytes to the name of the + u32 provider_name_offset; /* Offset in bytes to the name of the cryptographic provider from start of this structure or 0 if no name present. */ - /* 16*/ - u32 user_name_offset; /* Offset in bytes to the user name +/* 16*/ u32 user_name_offset; /* Offset in bytes to the user name from start of this structure or 0 if no user name present. (This is also known as lpDisplayInformation.) */ @@ -2782,26 +2636,26 @@ typedef struct { typedef EFS_DF_CERTIFICATE_THUMBPRINT_HEADER EFS_DF_CERT_THUMBPRINT_HEADER; typedef enum { - INTX_SYMBOLIC_LINK = - const_cpu_to_le64(0x014B4E4C78746E49ULL), /* "IntxLNK\1" */ - INTX_CHARACTER_DEVICE = - const_cpu_to_le64(0x0052484378746E49ULL), /* "IntxCHR\0" */ - INTX_BLOCK_DEVICE = - const_cpu_to_le64(0x004B4C4278746E49ULL), /* "IntxBLK\0" */ + INTX_SYMBOLIC_LINK = + const_cpu_to_le64(0x014B4E4C78746E49ULL), /* "IntxLNK\1" */ + INTX_CHARACTER_DEVICE = + const_cpu_to_le64(0x0052484378746E49ULL), /* "IntxCHR\0" */ + INTX_BLOCK_DEVICE = + const_cpu_to_le64(0x004B4C4278746E49ULL), /* "IntxBLK\0" */ } INTX_FILE_TYPES; typedef struct { - INTX_FILE_TYPES magic; /* Intx file magic. */ - union { - /* For character and block devices. */ - struct { - u64 major; /* Major device number. */ - u64 minor; /* Minor device number. */ - void *device_end[0]; /* Marker for offsetof(). */ - } __attribute__((__packed__)); - /* For symbolic links. */ - ntfschar target[0]; - } __attribute__((__packed__)); + INTX_FILE_TYPES magic; /* Intx file magic. */ + union { + /* For character and block devices. */ + struct { + u64 major; /* Major device number. */ + u64 minor; /* Minor device number. */ + void *device_end[0]; /* Marker for offsetof(). */ + } __attribute__((__packed__)); + /* For symbolic links. */ + ntfschar target[0]; + } __attribute__((__packed__)); } __attribute__((__packed__)) INTX_FILE; #endif /* defined _NTFS_LAYOUT_H */ diff --git a/source/libntfs/lcnalloc.c b/source/libntfs/lcnalloc.c index 1a20e692..ae678430 100644 --- a/source/libntfs/lcnalloc.c +++ b/source/libntfs/lcnalloc.c @@ -48,7 +48,7 @@ /* * Plenty possibilities for big optimizations all over in the cluster - * allocation, however at the moment the dominant bottleneck (~ 90%) is + * allocation, however at the moment the dominant bottleneck (~ 90%) is * the update of the mapping pairs which converges to the cubic Faulhaber's * formula as the function of the number of extents (fragments, runs). */ @@ -56,32 +56,34 @@ #define NTFS_LCNALLOC_SKIP NTFS_LCNALLOC_BSIZE enum { - ZONE_MFT = 1, - ZONE_DATA1 = 2, - ZONE_DATA2 = 4 + ZONE_MFT = 1, + ZONE_DATA1 = 2, + ZONE_DATA2 = 4 } ; -static void ntfs_cluster_set_zone_pos(LCN start, LCN end, LCN *pos, LCN tc) { - ntfs_log_trace("pos: %lld tc: %lld\n", (long long)*pos, (long long)tc); +static void ntfs_cluster_set_zone_pos(LCN start, LCN end, LCN *pos, LCN tc) +{ + ntfs_log_trace("pos: %lld tc: %lld\n", (long long)*pos, (long long)tc); - if (tc >= end) - *pos = start; - else if (tc >= start) - *pos = tc; + if (tc >= end) + *pos = start; + else if (tc >= start) + *pos = tc; } -static void ntfs_cluster_update_zone_pos(ntfs_volume *vol, u8 zone, LCN tc) { - ntfs_log_trace("tc = %lld, zone = %d\n", (long long)tc, zone); - - if (zone == ZONE_MFT) - ntfs_cluster_set_zone_pos(vol->mft_lcn, vol->mft_zone_end, - &vol->mft_zone_pos, tc); - else if (zone == ZONE_DATA1) - ntfs_cluster_set_zone_pos(vol->mft_zone_end, vol->nr_clusters, - &vol->data1_zone_pos, tc); - else /* zone == ZONE_DATA2 */ - ntfs_cluster_set_zone_pos(0, vol->mft_zone_start, - &vol->data2_zone_pos, tc); +static void ntfs_cluster_update_zone_pos(ntfs_volume *vol, u8 zone, LCN tc) +{ + ntfs_log_trace("tc = %lld, zone = %d\n", (long long)tc, zone); + + if (zone == ZONE_MFT) + ntfs_cluster_set_zone_pos(vol->mft_lcn, vol->mft_zone_end, + &vol->mft_zone_pos, tc); + else if (zone == ZONE_DATA1) + ntfs_cluster_set_zone_pos(vol->mft_zone_end, vol->nr_clusters, + &vol->data1_zone_pos, tc); + else /* zone == ZONE_DATA2 */ + ntfs_cluster_set_zone_pos(0, vol->mft_zone_start, + &vol->data2_zone_pos, tc); } /* @@ -90,101 +92,104 @@ static void ntfs_cluster_update_zone_pos(ntfs_volume *vol, u8 zone, LCN tc) { * Next allocation will reuse the freed cluster */ -static void update_full_status(ntfs_volume *vol, LCN lcn) { - if (lcn >= vol->mft_zone_end) { - if (vol->full_zones & ZONE_DATA1) { - ntfs_cluster_update_zone_pos(vol, ZONE_DATA1, lcn); - vol->full_zones &= ~ZONE_DATA1; - } - } else - if (lcn < vol->mft_zone_start) { - if (vol->full_zones & ZONE_DATA2) { - ntfs_cluster_update_zone_pos(vol, ZONE_DATA2, lcn); - vol->full_zones &= ~ZONE_DATA2; - } - } else { - if (vol->full_zones & ZONE_MFT) { - ntfs_cluster_update_zone_pos(vol, ZONE_MFT, lcn); - vol->full_zones &= ~ZONE_MFT; - } - } +static void update_full_status(ntfs_volume *vol, LCN lcn) +{ + if (lcn >= vol->mft_zone_end) { + if (vol->full_zones & ZONE_DATA1) { + ntfs_cluster_update_zone_pos(vol, ZONE_DATA1, lcn); + vol->full_zones &= ~ZONE_DATA1; + } + } else + if (lcn < vol->mft_zone_start) { + if (vol->full_zones & ZONE_DATA2) { + ntfs_cluster_update_zone_pos(vol, ZONE_DATA2, lcn); + vol->full_zones &= ~ZONE_DATA2; + } + } else { + if (vol->full_zones & ZONE_MFT) { + ntfs_cluster_update_zone_pos(vol, ZONE_MFT, lcn); + vol->full_zones &= ~ZONE_MFT; + } + } +} + +static s64 max_empty_bit_range(unsigned char *buf, int size) +{ + int i, j, run = 0; + int max_range = 0; + s64 start_pos = -1; + + ntfs_log_trace("Entering\n"); + + i = 0; + while (i < size) { + switch (*buf) { + case 0 : + do { + buf++; + run += 8; + i++; + } while ((i < size) && !*buf); + break; + case 255 : + if (run > max_range) { + max_range = run; + start_pos = (s64)i * 8 - run; + } + run = 0; + do { + buf++; + i++; + } while ((i < size) && (*buf == 255)); + break; + default : + for (j = 0; j < 8; j++) { + + int bit = *buf & (1 << j); + + if (bit) { + if (run > max_range) { + max_range = run; + start_pos = (s64)i * 8 + (j - run); + } + run = 0; + } else + run++; + } + i++; + buf++; + + } + } + + if (run > max_range) + start_pos = (s64)i * 8 - run; + + return start_pos; } -static s64 max_empty_bit_range(unsigned char *buf, int size) { - int i, j, run = 0; - int max_range = 0; - s64 start_pos = -1; +static int bitmap_writeback(ntfs_volume *vol, s64 pos, s64 size, void *b, + u8 *writeback) +{ + s64 written; + + ntfs_log_trace("Entering\n"); + + if (!*writeback) + return 0; + + *writeback = 0; + + written = ntfs_attr_pwrite(vol->lcnbmp_na, pos, size, b); + if (written != size) { + if (!written) + errno = EIO; + ntfs_log_perror("Bitmap write error (%lld, %lld)", + (long long)pos, (long long)size); + return -1; + } - ntfs_log_trace("Entering\n"); - - i = 0; - while (i < size) { - switch (*buf) { - case 0 : - do { - buf++; - run += 8; - i++; - } while ((i < size) && !*buf); - break; - case 255 : - if (run > max_range) { - max_range = run; - start_pos = (s64)i * 8 - run; - } - run = 0; - do { - buf++; - i++; - } while ((i < size) && (*buf == 255)); - break; - default : - for (j = 0; j < 8; j++) { - - int bit = *buf & (1 << j); - - if (bit) { - if (run > max_range) { - max_range = run; - start_pos = (s64)i * 8 + (j - run); - } - run = 0; - } else - run++; - } - i++; - buf++; - - } - } - - if (run > max_range) - start_pos = (s64)i * 8 - run; - - return start_pos; -} - -static int bitmap_writeback(ntfs_volume *vol, s64 pos, s64 size, void *b, - u8 *writeback) { - s64 written; - - ntfs_log_trace("Entering\n"); - - if (!*writeback) - return 0; - - *writeback = 0; - - written = ntfs_attr_pwrite(vol->lcnbmp_na, pos, size, b); - if (written != size) { - if (!written) - errno = EIO; - ntfs_log_perror("Bitmap write error (%lld, %lld)", - (long long)pos, (long long)size); - return -1; - } - - return 0; + return 0; } /** @@ -215,350 +220,350 @@ static int bitmap_writeback(ntfs_volume *vol, s64 pos, s64 size, void *b, * expanded to cover the start of the volume in order to reserve space for the * mft bitmap attribute. * - * The complexity stems from the need of implementing the mft vs data zoned - * approach and from the fact that we have access to the lcn bitmap via up to - * NTFS_LCNALLOC_BSIZE bytes at a time, so we need to cope with crossing over - * boundaries of two buffers. Further, the fact that the allocator allows for - * caller supplied hints as to the location of where allocation should begin - * and the fact that the allocator keeps track of where in the data zones the - * next natural allocation should occur, contribute to the complexity of the - * function. But it should all be worthwhile, because this allocator: + * The complexity stems from the need of implementing the mft vs data zoned + * approach and from the fact that we have access to the lcn bitmap via up to + * NTFS_LCNALLOC_BSIZE bytes at a time, so we need to cope with crossing over + * boundaries of two buffers. Further, the fact that the allocator allows for + * caller supplied hints as to the location of where allocation should begin + * and the fact that the allocator keeps track of where in the data zones the + * next natural allocation should occur, contribute to the complexity of the + * function. But it should all be worthwhile, because this allocator: * 1) implements MFT zone reservation - * 2) causes reduction in fragmentation. + * 2) causes reduction in fragmentation. * The code is not optimized for speed. */ runlist *ntfs_cluster_alloc(ntfs_volume *vol, VCN start_vcn, s64 count, - LCN start_lcn, const NTFS_CLUSTER_ALLOCATION_ZONES zone) { - LCN zone_start, zone_end; /* current search range */ - LCN last_read_pos, lcn; - LCN bmp_pos; /* current bit position inside the bitmap */ - LCN prev_lcn = 0, prev_run_len = 0; - s64 clusters, br; - runlist *rl = NULL, *trl; - u8 *buf, *byte, bit, writeback; - u8 pass = 1; /* 1: inside zone; 2: start of zone */ - u8 search_zone; /* 4: data2 (start) 1: mft (middle) 2: data1 (end) */ - u8 done_zones = 0; - u8 has_guess, used_zone_pos; - int err = 0, rlpos, rlsize, buf_size; + LCN start_lcn, const NTFS_CLUSTER_ALLOCATION_ZONES zone) +{ + LCN zone_start, zone_end; /* current search range */ + LCN last_read_pos, lcn; + LCN bmp_pos; /* current bit position inside the bitmap */ + LCN prev_lcn = 0, prev_run_len = 0; + s64 clusters, br; + runlist *rl = NULL, *trl; + u8 *buf, *byte, bit, writeback; + u8 pass = 1; /* 1: inside zone; 2: start of zone */ + u8 search_zone; /* 4: data2 (start) 1: mft (middle) 2: data1 (end) */ + u8 done_zones = 0; + u8 has_guess, used_zone_pos; + int err = 0, rlpos, rlsize, buf_size; - ntfs_log_enter("Entering with count = 0x%llx, start_lcn = 0x%llx, " - "zone = %s_ZONE.\n", (long long)count, (long long) - start_lcn, zone == MFT_ZONE ? "MFT" : "DATA"); + ntfs_log_enter("Entering with count = 0x%llx, start_lcn = 0x%llx, " + "zone = %s_ZONE.\n", (long long)count, (long long) + start_lcn, zone == MFT_ZONE ? "MFT" : "DATA"); + + if (!vol || count < 0 || start_lcn < -1 || !vol->lcnbmp_na || + (s8)zone < FIRST_ZONE || zone > LAST_ZONE) { + errno = EINVAL; + ntfs_log_perror("%s: vcn: %lld, count: %lld, lcn: %lld", + __FUNCTION__, (long long)start_vcn, + (long long)count, (long long)start_lcn); + goto out; + } - if (!vol || count < 0 || start_lcn < -1 || !vol->lcnbmp_na || - (s8)zone < FIRST_ZONE || zone > LAST_ZONE) { - errno = EINVAL; - ntfs_log_perror("%s: vcn: %lld, count: %lld, lcn: %lld", - __FUNCTION__, (long long)start_vcn, - (long long)count, (long long)start_lcn); - goto out; - } + /* Return empty runlist if @count == 0 */ + if (!count) { + rl = ntfs_malloc(0x1000); + if (rl) { + rl[0].vcn = start_vcn; + rl[0].lcn = LCN_RL_NOT_MAPPED; + rl[0].length = 0; + } + goto out; + } - /* Return empty runlist if @count == 0 */ - if (!count) { - rl = ntfs_malloc(0x1000); - if (rl) { - rl[0].vcn = start_vcn; - rl[0].lcn = LCN_RL_NOT_MAPPED; - rl[0].length = 0; - } - goto out; - } + buf = ntfs_malloc(NTFS_LCNALLOC_BSIZE); + if (!buf) + goto out; + /* + * If no @start_lcn was requested, use the current zone + * position otherwise use the requested @start_lcn. + */ + has_guess = 1; + zone_start = start_lcn; + + if (zone_start < 0) { + if (zone == DATA_ZONE) + zone_start = vol->data1_zone_pos; + else + zone_start = vol->mft_zone_pos; + has_guess = 0; + } + + used_zone_pos = has_guess ? 0 : 1; + + if (!zone_start || zone_start == vol->mft_zone_start || + zone_start == vol->mft_zone_end) + pass = 2; + + if (zone_start < vol->mft_zone_start) { + zone_end = vol->mft_zone_start; + search_zone = ZONE_DATA2; + } else if (zone_start < vol->mft_zone_end) { + zone_end = vol->mft_zone_end; + search_zone = ZONE_MFT; + } else { + zone_end = vol->nr_clusters; + search_zone = ZONE_DATA1; + } + + bmp_pos = zone_start; - buf = ntfs_malloc(NTFS_LCNALLOC_BSIZE); - if (!buf) - goto out; - /* - * If no @start_lcn was requested, use the current zone - * position otherwise use the requested @start_lcn. - */ - has_guess = 1; - zone_start = start_lcn; + /* Loop until all clusters are allocated. */ + clusters = count; + rlpos = rlsize = 0; + while (1) { + /* check whether we have exhausted the current zone */ + if (search_zone & vol->full_zones) + goto zone_pass_done; + last_read_pos = bmp_pos >> 3; + br = ntfs_attr_pread(vol->lcnbmp_na, last_read_pos, + NTFS_LCNALLOC_BSIZE, buf); + if (br <= 0) { + if (!br) + goto zone_pass_done; + err = errno; + ntfs_log_perror("Reading $BITMAP failed"); + goto err_ret; + } + /* + * We might have read less than NTFS_LCNALLOC_BSIZE bytes + * if we are close to the end of the attribute. + */ + buf_size = (int)br << 3; + lcn = bmp_pos & 7; + bmp_pos &= ~7; + writeback = 0; + + while (lcn < buf_size) { + byte = buf + (lcn >> 3); + bit = 1 << (lcn & 7); + if (has_guess) { + if (*byte & bit) { + has_guess = 0; + break; + } + } else { + lcn = max_empty_bit_range(buf, br); + if (lcn < 0) + break; + has_guess = 1; + continue; + } - if (zone_start < 0) { - if (zone == DATA_ZONE) - zone_start = vol->data1_zone_pos; - else - zone_start = vol->mft_zone_pos; - has_guess = 0; - } - - used_zone_pos = has_guess ? 0 : 1; - - if (!zone_start || zone_start == vol->mft_zone_start || - zone_start == vol->mft_zone_end) - pass = 2; - - if (zone_start < vol->mft_zone_start) { - zone_end = vol->mft_zone_start; - search_zone = ZONE_DATA2; - } else if (zone_start < vol->mft_zone_end) { - zone_end = vol->mft_zone_end; - search_zone = ZONE_MFT; - } else { - zone_end = vol->nr_clusters; - search_zone = ZONE_DATA1; - } - - bmp_pos = zone_start; - - /* Loop until all clusters are allocated. */ - clusters = count; - rlpos = rlsize = 0; - while (1) { - /* check whether we have exhausted the current zone */ - if (search_zone & vol->full_zones) - goto zone_pass_done; - last_read_pos = bmp_pos >> 3; - br = ntfs_attr_pread(vol->lcnbmp_na, last_read_pos, - NTFS_LCNALLOC_BSIZE, buf); - if (br <= 0) { - if (!br) - goto zone_pass_done; - err = errno; - ntfs_log_perror("Reading $BITMAP failed"); - goto err_ret; - } - /* - * We might have read less than NTFS_LCNALLOC_BSIZE bytes - * if we are close to the end of the attribute. - */ - buf_size = (int)br << 3; - lcn = bmp_pos & 7; - bmp_pos &= ~7; - writeback = 0; - - while (lcn < buf_size) { - byte = buf + (lcn >> 3); - bit = 1 << (lcn & 7); - if (has_guess) { - if (*byte & bit) { - has_guess = 0; - break; - } - } else { - lcn = max_empty_bit_range(buf, br); - if (lcn < 0) - break; - has_guess = 1; - continue; - } - - /* First free bit is at lcn + bmp_pos. */ - - /* Reallocate memory if necessary. */ - if ((rlpos + 2) * (int)sizeof(runlist) >= rlsize) { - rlsize += 4096; - trl = realloc(rl, rlsize); - if (!trl) { - err = ENOMEM; - ntfs_log_perror("realloc() failed"); - goto wb_err_ret; - } - rl = trl; - } - - /* Allocate the bitmap bit. */ - *byte |= bit; - writeback = 1; - if (vol->free_clusters <= 0) - ntfs_log_error("Non-positive free clusters " - "(%lld)!\n", - (long long)vol->free_clusters); - else - vol->free_clusters--; - - /* - * Coalesce with previous run if adjacent LCNs. - * Otherwise, append a new run. - */ - if (prev_lcn == lcn + bmp_pos - prev_run_len && rlpos) { - ntfs_log_debug("Cluster coalesce: prev_lcn: " - "%lld lcn: %lld bmp_pos: %lld " - "prev_run_len: %lld\n", - (long long)prev_lcn, - (long long)lcn, (long long)bmp_pos, - (long long)prev_run_len); - rl[rlpos - 1].length = ++prev_run_len; - } else { - if (rlpos) - rl[rlpos].vcn = rl[rlpos - 1].vcn + - prev_run_len; - else { - rl[rlpos].vcn = start_vcn; - ntfs_log_debug("Start_vcn: %lld\n", - (long long)start_vcn); - } - - rl[rlpos].lcn = prev_lcn = lcn + bmp_pos; - rl[rlpos].length = prev_run_len = 1; - rlpos++; - } - - ntfs_log_debug("RUN: %-16lld %-16lld %-16lld\n", - (long long)rl[rlpos - 1].vcn, - (long long)rl[rlpos - 1].lcn, - (long long)rl[rlpos - 1].length); - /* Done? */ - if (!--clusters) { - if (used_zone_pos) - ntfs_cluster_update_zone_pos(vol, - search_zone, lcn + bmp_pos + 1 + - NTFS_LCNALLOC_SKIP); - goto done_ret; - } - - lcn++; - } - - if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) { - err = errno; - goto err_ret; - } - - if (!used_zone_pos) { - - used_zone_pos = 1; - - if (search_zone == ZONE_MFT) - zone_start = vol->mft_zone_pos; - else if (search_zone == ZONE_DATA1) - zone_start = vol->data1_zone_pos; - else - zone_start = vol->data2_zone_pos; - - if (!zone_start || zone_start == vol->mft_zone_start || - zone_start == vol->mft_zone_end) - pass = 2; - bmp_pos = zone_start; - } else - bmp_pos += buf_size; - - if (bmp_pos < zone_end) - continue; + /* First free bit is at lcn + bmp_pos. */ + + /* Reallocate memory if necessary. */ + if ((rlpos + 2) * (int)sizeof(runlist) >= rlsize) { + rlsize += 4096; + trl = realloc(rl, rlsize); + if (!trl) { + err = ENOMEM; + ntfs_log_perror("realloc() failed"); + goto wb_err_ret; + } + rl = trl; + } + + /* Allocate the bitmap bit. */ + *byte |= bit; + writeback = 1; + if (vol->free_clusters <= 0) + ntfs_log_error("Non-positive free clusters " + "(%lld)!\n", + (long long)vol->free_clusters); + else + vol->free_clusters--; + + /* + * Coalesce with previous run if adjacent LCNs. + * Otherwise, append a new run. + */ + if (prev_lcn == lcn + bmp_pos - prev_run_len && rlpos) { + ntfs_log_debug("Cluster coalesce: prev_lcn: " + "%lld lcn: %lld bmp_pos: %lld " + "prev_run_len: %lld\n", + (long long)prev_lcn, + (long long)lcn, (long long)bmp_pos, + (long long)prev_run_len); + rl[rlpos - 1].length = ++prev_run_len; + } else { + if (rlpos) + rl[rlpos].vcn = rl[rlpos - 1].vcn + + prev_run_len; + else { + rl[rlpos].vcn = start_vcn; + ntfs_log_debug("Start_vcn: %lld\n", + (long long)start_vcn); + } + + rl[rlpos].lcn = prev_lcn = lcn + bmp_pos; + rl[rlpos].length = prev_run_len = 1; + rlpos++; + } + + ntfs_log_debug("RUN: %-16lld %-16lld %-16lld\n", + (long long)rl[rlpos - 1].vcn, + (long long)rl[rlpos - 1].lcn, + (long long)rl[rlpos - 1].length); + /* Done? */ + if (!--clusters) { + if (used_zone_pos) + ntfs_cluster_update_zone_pos(vol, + search_zone, lcn + bmp_pos + 1 + + NTFS_LCNALLOC_SKIP); + goto done_ret; + } + + lcn++; + } + + if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) { + err = errno; + goto err_ret; + } + + if (!used_zone_pos) { + + used_zone_pos = 1; + + if (search_zone == ZONE_MFT) + zone_start = vol->mft_zone_pos; + else if (search_zone == ZONE_DATA1) + zone_start = vol->data1_zone_pos; + else + zone_start = vol->data2_zone_pos; + + if (!zone_start || zone_start == vol->mft_zone_start || + zone_start == vol->mft_zone_end) + pass = 2; + bmp_pos = zone_start; + } else + bmp_pos += buf_size; + + if (bmp_pos < zone_end) + continue; zone_pass_done: - ntfs_log_trace("Finished current zone pass(%i).\n", pass); - if (pass == 1) { - pass = 2; - zone_end = zone_start; - - if (search_zone == ZONE_MFT) - zone_start = vol->mft_zone_start; - else if (search_zone == ZONE_DATA1) - zone_start = vol->mft_zone_end; - else - zone_start = 0; - - /* Sanity check. */ - if (zone_end < zone_start) - zone_end = zone_start; - - bmp_pos = zone_start; - - continue; - } - /* pass == 2 */ + ntfs_log_trace("Finished current zone pass(%i).\n", pass); + if (pass == 1) { + pass = 2; + zone_end = zone_start; + + if (search_zone == ZONE_MFT) + zone_start = vol->mft_zone_start; + else if (search_zone == ZONE_DATA1) + zone_start = vol->mft_zone_end; + else + zone_start = 0; + + /* Sanity check. */ + if (zone_end < zone_start) + zone_end = zone_start; + + bmp_pos = zone_start; + + continue; + } + /* pass == 2 */ done_zones_check: - done_zones |= search_zone; - vol->full_zones |= search_zone; - if (done_zones < (ZONE_MFT + ZONE_DATA1 + ZONE_DATA2)) { - ntfs_log_trace("Switching zone.\n"); - pass = 1; - if (rlpos) { - LCN tc = tc = rl[rlpos - 1].lcn + - rl[rlpos - 1].length + NTFS_LCNALLOC_SKIP; - - if (used_zone_pos) - ntfs_cluster_update_zone_pos(vol, - search_zone, tc); - } - - switch (search_zone) { - case ZONE_MFT: - ntfs_log_trace("Zone switch: mft -> data1\n"); -switch_to_data1_zone: - search_zone = ZONE_DATA1; - zone_start = vol->data1_zone_pos; - zone_end = vol->nr_clusters; - if (zone_start == vol->mft_zone_end) - pass = 2; - break; - case ZONE_DATA1: - ntfs_log_trace("Zone switch: data1 -> data2\n"); - search_zone = ZONE_DATA2; - zone_start = vol->data2_zone_pos; - zone_end = vol->mft_zone_start; - if (!zone_start) - pass = 2; - break; - case ZONE_DATA2: - if (!(done_zones & ZONE_DATA1)) { - ntfs_log_trace("data2 -> data1\n"); - goto switch_to_data1_zone; - } - ntfs_log_trace("Zone switch: data2 -> mft\n"); - search_zone = ZONE_MFT; - zone_start = vol->mft_zone_pos; - zone_end = vol->mft_zone_end; - if (zone_start == vol->mft_zone_start) - pass = 2; - break; - } - - bmp_pos = zone_start; - - if (zone_start == zone_end) { - ntfs_log_trace("Empty zone, skipped.\n"); - goto done_zones_check; - } - - continue; - } - - ntfs_log_trace("All zones are finished, no space on device.\n"); - err = ENOSPC; - goto err_ret; - } + done_zones |= search_zone; + vol->full_zones |= search_zone; + if (done_zones < (ZONE_MFT + ZONE_DATA1 + ZONE_DATA2)) { + ntfs_log_trace("Switching zone.\n"); + pass = 1; + if (rlpos) { + LCN tc = tc = rl[rlpos - 1].lcn + + rl[rlpos - 1].length + NTFS_LCNALLOC_SKIP; + + if (used_zone_pos) + ntfs_cluster_update_zone_pos(vol, + search_zone, tc); + } + + switch (search_zone) { + case ZONE_MFT: + ntfs_log_trace("Zone switch: mft -> data1\n"); +switch_to_data1_zone: search_zone = ZONE_DATA1; + zone_start = vol->data1_zone_pos; + zone_end = vol->nr_clusters; + if (zone_start == vol->mft_zone_end) + pass = 2; + break; + case ZONE_DATA1: + ntfs_log_trace("Zone switch: data1 -> data2\n"); + search_zone = ZONE_DATA2; + zone_start = vol->data2_zone_pos; + zone_end = vol->mft_zone_start; + if (!zone_start) + pass = 2; + break; + case ZONE_DATA2: + if (!(done_zones & ZONE_DATA1)) { + ntfs_log_trace("data2 -> data1\n"); + goto switch_to_data1_zone; + } + ntfs_log_trace("Zone switch: data2 -> mft\n"); + search_zone = ZONE_MFT; + zone_start = vol->mft_zone_pos; + zone_end = vol->mft_zone_end; + if (zone_start == vol->mft_zone_start) + pass = 2; + break; + } + + bmp_pos = zone_start; + + if (zone_start == zone_end) { + ntfs_log_trace("Empty zone, skipped.\n"); + goto done_zones_check; + } + + continue; + } + + ntfs_log_trace("All zones are finished, no space on device.\n"); + err = ENOSPC; + goto err_ret; + } done_ret: - ntfs_log_debug("At done_ret.\n"); - /* Add runlist terminator element. */ - rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; - rl[rlpos].lcn = LCN_RL_NOT_MAPPED; - rl[rlpos].length = 0; - if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) { - err = errno; - goto err_ret; - } + ntfs_log_debug("At done_ret.\n"); + /* Add runlist terminator element. */ + rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; + rl[rlpos].lcn = LCN_RL_NOT_MAPPED; + rl[rlpos].length = 0; + if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) { + err = errno; + goto err_ret; + } done_err_ret: - free(buf); - if (err) { - errno = err; - ntfs_log_perror("Failed to allocate clusters"); - rl = NULL; - } -out: - ntfs_log_leave("\n"); - return rl; + free(buf); + if (err) { + errno = err; + ntfs_log_perror("Failed to allocate clusters"); + rl = NULL; + } +out: + ntfs_log_leave("\n"); + return rl; wb_err_ret: - ntfs_log_trace("At wb_err_ret.\n"); - if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) - err = errno; + ntfs_log_trace("At wb_err_ret.\n"); + if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) + err = errno; err_ret: - ntfs_log_trace("At err_ret.\n"); - if (rl) { - /* Add runlist terminator element. */ - rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; - rl[rlpos].lcn = LCN_RL_NOT_MAPPED; - rl[rlpos].length = 0; - ntfs_debug_runlist_dump(rl); - ntfs_cluster_free_from_rl(vol, rl); - free(rl); - rl = NULL; - } - goto done_err_ret; + ntfs_log_trace("At err_ret.\n"); + if (rl) { + /* Add runlist terminator element. */ + rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; + rl[rlpos].lcn = LCN_RL_NOT_MAPPED; + rl[rlpos].length = 0; + ntfs_debug_runlist_dump(rl); + ntfs_cluster_free_from_rl(vol, rl); + free(rl); + rl = NULL; + } + goto done_err_ret; } /** @@ -568,39 +573,40 @@ err_ret: * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_cluster_free_from_rl(ntfs_volume *vol, runlist *rl) { - s64 nr_freed = 0; - int ret = -1; +int ntfs_cluster_free_from_rl(ntfs_volume *vol, runlist *rl) +{ + s64 nr_freed = 0; + int ret = -1; - ntfs_log_trace("Entering.\n"); + ntfs_log_trace("Entering.\n"); - for (; rl->length; rl++) { + for (; rl->length; rl++) { - ntfs_log_trace("Dealloc lcn 0x%llx, len 0x%llx.\n", - (long long)rl->lcn, (long long)rl->length); + ntfs_log_trace("Dealloc lcn 0x%llx, len 0x%llx.\n", + (long long)rl->lcn, (long long)rl->length); - if (rl->lcn >= 0) { - update_full_status(vol,rl->lcn); - if (ntfs_bitmap_clear_run(vol->lcnbmp_na, rl->lcn, - rl->length)) { - ntfs_log_perror("Cluster deallocation failed " - "(%lld, %lld)", - (long long)rl->lcn, - (long long)rl->length); - goto out; - } - nr_freed += rl->length ; - } - } + if (rl->lcn >= 0) { + update_full_status(vol,rl->lcn); + if (ntfs_bitmap_clear_run(vol->lcnbmp_na, rl->lcn, + rl->length)) { + ntfs_log_perror("Cluster deallocation failed " + "(%lld, %lld)", + (long long)rl->lcn, + (long long)rl->length); + goto out; + } + nr_freed += rl->length ; + } + } - ret = 0; + ret = 0; out: - vol->free_clusters += nr_freed; - if (vol->free_clusters > vol->nr_clusters) - ntfs_log_error("Too many free clusters (%lld > %lld)!", - (long long)vol->free_clusters, - (long long)vol->nr_clusters); - return ret; + vol->free_clusters += nr_freed; + if (vol->free_clusters > vol->nr_clusters) + ntfs_log_error("Too many free clusters (%lld > %lld)!", + (long long)vol->free_clusters, + (long long)vol->nr_clusters); + return ret; } /** @@ -619,110 +625,111 @@ out: * On success return the number of deallocated clusters (not counting sparse * clusters) and on error return -1 with errno set to the error code. */ -int ntfs_cluster_free(ntfs_volume *vol, ntfs_attr *na, VCN start_vcn, s64 count) { - runlist *rl; - s64 delta, to_free, nr_freed = 0; - int ret = -1; +int ntfs_cluster_free(ntfs_volume *vol, ntfs_attr *na, VCN start_vcn, s64 count) +{ + runlist *rl; + s64 delta, to_free, nr_freed = 0; + int ret = -1; - if (!vol || !vol->lcnbmp_na || !na || start_vcn < 0 || - (count < 0 && count != -1)) { - ntfs_log_trace("Invalid arguments!\n"); - errno = EINVAL; - return -1; - } + if (!vol || !vol->lcnbmp_na || !na || start_vcn < 0 || + (count < 0 && count != -1)) { + ntfs_log_trace("Invalid arguments!\n"); + errno = EINVAL; + return -1; + } + + ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x, count 0x%llx, " + "vcn 0x%llx.\n", (unsigned long long)na->ni->mft_no, + na->type, (long long)count, (long long)start_vcn); - ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x, count 0x%llx, " - "vcn 0x%llx.\n", (unsigned long long)na->ni->mft_no, - na->type, (long long)count, (long long)start_vcn); + rl = ntfs_attr_find_vcn(na, start_vcn); + if (!rl) { + if (errno == ENOENT) + ret = 0; + goto leave; + } - rl = ntfs_attr_find_vcn(na, start_vcn); - if (!rl) { - if (errno == ENOENT) - ret = 0; - goto leave; - } + if (rl->lcn < 0 && rl->lcn != LCN_HOLE) { + errno = EIO; + ntfs_log_perror("%s: Unexpected lcn (%lld)", __FUNCTION__, + (long long)rl->lcn); + goto leave; + } - if (rl->lcn < 0 && rl->lcn != LCN_HOLE) { - errno = EIO; - ntfs_log_perror("%s: Unexpected lcn (%lld)", __FUNCTION__, - (long long)rl->lcn); - goto leave; - } + /* Find the starting cluster inside the run that needs freeing. */ + delta = start_vcn - rl->vcn; - /* Find the starting cluster inside the run that needs freeing. */ - delta = start_vcn - rl->vcn; + /* The number of clusters in this run that need freeing. */ + to_free = rl->length - delta; + if (count >= 0 && to_free > count) + to_free = count; - /* The number of clusters in this run that need freeing. */ - to_free = rl->length - delta; - if (count >= 0 && to_free > count) - to_free = count; + if (rl->lcn != LCN_HOLE) { + /* Do the actual freeing of the clusters in this run. */ + update_full_status(vol,rl->lcn + delta); + if (ntfs_bitmap_clear_run(vol->lcnbmp_na, rl->lcn + delta, + to_free)) + goto leave; + nr_freed = to_free; + } - if (rl->lcn != LCN_HOLE) { - /* Do the actual freeing of the clusters in this run. */ - update_full_status(vol,rl->lcn + delta); - if (ntfs_bitmap_clear_run(vol->lcnbmp_na, rl->lcn + delta, - to_free)) - goto leave; - nr_freed = to_free; - } + /* Go to the next run and adjust the number of clusters left to free. */ + ++rl; + if (count >= 0) + count -= to_free; - /* Go to the next run and adjust the number of clusters left to free. */ - ++rl; - if (count >= 0) - count -= to_free; + /* + * Loop over the remaining runs, using @count as a capping value, and + * free them. + */ + for (; rl->length && count != 0; ++rl) { + // FIXME: Need to try ntfs_attr_map_runlist() for attribute + // list support! (AIA) + if (rl->lcn < 0 && rl->lcn != LCN_HOLE) { + // FIXME: Eeek! We need rollback! (AIA) + errno = EIO; + ntfs_log_perror("%s: Invalid lcn (%lli)", + __FUNCTION__, (long long)rl->lcn); + goto out; + } - /* - * Loop over the remaining runs, using @count as a capping value, and - * free them. - */ - for (; rl->length && count != 0; ++rl) { - // FIXME: Need to try ntfs_attr_map_runlist() for attribute - // list support! (AIA) - if (rl->lcn < 0 && rl->lcn != LCN_HOLE) { - // FIXME: Eeek! We need rollback! (AIA) - errno = EIO; - ntfs_log_perror("%s: Invalid lcn (%lli)", - __FUNCTION__, (long long)rl->lcn); - goto out; - } + /* The number of clusters in this run that need freeing. */ + to_free = rl->length; + if (count >= 0 && to_free > count) + to_free = count; - /* The number of clusters in this run that need freeing. */ - to_free = rl->length; - if (count >= 0 && to_free > count) - to_free = count; + if (rl->lcn != LCN_HOLE) { + update_full_status(vol,rl->lcn); + if (ntfs_bitmap_clear_run(vol->lcnbmp_na, rl->lcn, + to_free)) { + // FIXME: Eeek! We need rollback! (AIA) + ntfs_log_perror("%s: Clearing bitmap run failed", + __FUNCTION__); + goto out; + } + nr_freed += to_free; + } - if (rl->lcn != LCN_HOLE) { - update_full_status(vol,rl->lcn); - if (ntfs_bitmap_clear_run(vol->lcnbmp_na, rl->lcn, - to_free)) { - // FIXME: Eeek! We need rollback! (AIA) - ntfs_log_perror("%s: Clearing bitmap run failed", - __FUNCTION__); - goto out; - } - nr_freed += to_free; - } + if (count >= 0) + count -= to_free; + } - if (count >= 0) - count -= to_free; - } + if (count != -1 && count != 0) { + // FIXME: Eeek! BUG() + errno = EIO; + ntfs_log_perror("%s: count still not zero (%lld)", __FUNCTION__, + (long long)count); + goto out; + } - if (count != -1 && count != 0) { - // FIXME: Eeek! BUG() - errno = EIO; - ntfs_log_perror("%s: count still not zero (%lld)", __FUNCTION__, - (long long)count); - goto out; - } - - ret = nr_freed; + ret = nr_freed; out: - vol->free_clusters += nr_freed ; - if (vol->free_clusters > vol->nr_clusters) - ntfs_log_error("Too many free clusters (%lld > %lld)!", - (long long)vol->free_clusters, - (long long)vol->nr_clusters); -leave: - ntfs_log_leave("\n"); - return ret; + vol->free_clusters += nr_freed ; + if (vol->free_clusters > vol->nr_clusters) + ntfs_log_error("Too many free clusters (%lld > %lld)!", + (long long)vol->free_clusters, + (long long)vol->nr_clusters); +leave: + ntfs_log_leave("\n"); + return ret; } diff --git a/source/libntfs/lcnalloc.h b/source/libntfs/lcnalloc.h index 1207f594..e87ca43a 100644 --- a/source/libntfs/lcnalloc.h +++ b/source/libntfs/lcnalloc.h @@ -32,19 +32,19 @@ * enum NTFS_CLUSTER_ALLOCATION_ZONES - */ typedef enum { - FIRST_ZONE = 0, /* For sanity checking. */ - MFT_ZONE = 0, /* Allocate from $MFT zone. */ - DATA_ZONE = 1, /* Allocate from $DATA zone. */ - LAST_ZONE = 1, /* For sanity checking. */ + FIRST_ZONE = 0, /* For sanity checking. */ + MFT_ZONE = 0, /* Allocate from $MFT zone. */ + DATA_ZONE = 1, /* Allocate from $DATA zone. */ + LAST_ZONE = 1, /* For sanity checking. */ } NTFS_CLUSTER_ALLOCATION_ZONES; extern runlist *ntfs_cluster_alloc(ntfs_volume *vol, VCN start_vcn, s64 count, - LCN start_lcn, const NTFS_CLUSTER_ALLOCATION_ZONES zone); + LCN start_lcn, const NTFS_CLUSTER_ALLOCATION_ZONES zone); extern int ntfs_cluster_free_from_rl(ntfs_volume *vol, runlist *rl); extern int ntfs_cluster_free(ntfs_volume *vol, ntfs_attr *na, VCN start_vcn, - s64 count); + s64 count); #endif /* defined _NTFS_LCNALLOC_H */ diff --git a/source/libntfs/logfile.c b/source/libntfs/logfile.c index 4a340763..4a129cb4 100644 --- a/source/libntfs/logfile.c +++ b/source/libntfs/logfile.c @@ -54,94 +54,95 @@ * This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not * require the full restart page. */ -static BOOL ntfs_check_restart_page_header(RESTART_PAGE_HEADER *rp, s64 pos) { - u32 logfile_system_page_size, logfile_log_page_size; - u16 ra_ofs, usa_count, usa_ofs, usa_end = 0; - BOOL have_usa = TRUE; +static BOOL ntfs_check_restart_page_header(RESTART_PAGE_HEADER *rp, s64 pos) +{ + u32 logfile_system_page_size, logfile_log_page_size; + u16 ra_ofs, usa_count, usa_ofs, usa_end = 0; + BOOL have_usa = TRUE; - ntfs_log_trace("Entering.\n"); - /* - * If the system or log page sizes are smaller than the ntfs block size - * or either is not a power of 2 we cannot handle this log file. - */ - logfile_system_page_size = le32_to_cpu(rp->system_page_size); - logfile_log_page_size = le32_to_cpu(rp->log_page_size); - if (logfile_system_page_size < NTFS_BLOCK_SIZE || - logfile_log_page_size < NTFS_BLOCK_SIZE || - logfile_system_page_size & - (logfile_system_page_size - 1) || - logfile_log_page_size & (logfile_log_page_size - 1)) { - ntfs_log_error("$LogFile uses unsupported page size.\n"); - return FALSE; - } - /* - * We must be either at !pos (1st restart page) or at pos = system page - * size (2nd restart page). - */ - if (pos && pos != logfile_system_page_size) { - ntfs_log_error("Found restart area in incorrect " - "position in $LogFile.\n"); - return FALSE; - } - /* We only know how to handle version 1.1. */ - if (sle16_to_cpu(rp->major_ver) != 1 || - sle16_to_cpu(rp->minor_ver) != 1) { - ntfs_log_error("$LogFile version %i.%i is not " - "supported. (This driver supports version " - "1.1 only.)\n", (int)sle16_to_cpu(rp->major_ver), - (int)sle16_to_cpu(rp->minor_ver)); - return FALSE; - } - /* - * If chkdsk has been run the restart page may not be protected by an - * update sequence array. - */ - if (ntfs_is_chkd_record(rp->magic) && !le16_to_cpu(rp->usa_count)) { - have_usa = FALSE; - goto skip_usa_checks; - } - /* Verify the size of the update sequence array. */ - usa_count = 1 + (logfile_system_page_size >> NTFS_BLOCK_SIZE_BITS); - if (usa_count != le16_to_cpu(rp->usa_count)) { - ntfs_log_error("$LogFile restart page specifies " - "inconsistent update sequence array count.\n"); - return FALSE; - } - /* Verify the position of the update sequence array. */ - usa_ofs = le16_to_cpu(rp->usa_ofs); - usa_end = usa_ofs + usa_count * sizeof(u16); - if (usa_ofs < sizeof(RESTART_PAGE_HEADER) || - usa_end > NTFS_BLOCK_SIZE - sizeof(u16)) { - ntfs_log_error("$LogFile restart page specifies " - "inconsistent update sequence array offset.\n"); - return FALSE; - } + ntfs_log_trace("Entering.\n"); + /* + * If the system or log page sizes are smaller than the ntfs block size + * or either is not a power of 2 we cannot handle this log file. + */ + logfile_system_page_size = le32_to_cpu(rp->system_page_size); + logfile_log_page_size = le32_to_cpu(rp->log_page_size); + if (logfile_system_page_size < NTFS_BLOCK_SIZE || + logfile_log_page_size < NTFS_BLOCK_SIZE || + logfile_system_page_size & + (logfile_system_page_size - 1) || + logfile_log_page_size & (logfile_log_page_size - 1)) { + ntfs_log_error("$LogFile uses unsupported page size.\n"); + return FALSE; + } + /* + * We must be either at !pos (1st restart page) or at pos = system page + * size (2nd restart page). + */ + if (pos && pos != logfile_system_page_size) { + ntfs_log_error("Found restart area in incorrect " + "position in $LogFile.\n"); + return FALSE; + } + /* We only know how to handle version 1.1. */ + if (sle16_to_cpu(rp->major_ver) != 1 || + sle16_to_cpu(rp->minor_ver) != 1) { + ntfs_log_error("$LogFile version %i.%i is not " + "supported. (This driver supports version " + "1.1 only.)\n", (int)sle16_to_cpu(rp->major_ver), + (int)sle16_to_cpu(rp->minor_ver)); + return FALSE; + } + /* + * If chkdsk has been run the restart page may not be protected by an + * update sequence array. + */ + if (ntfs_is_chkd_record(rp->magic) && !le16_to_cpu(rp->usa_count)) { + have_usa = FALSE; + goto skip_usa_checks; + } + /* Verify the size of the update sequence array. */ + usa_count = 1 + (logfile_system_page_size >> NTFS_BLOCK_SIZE_BITS); + if (usa_count != le16_to_cpu(rp->usa_count)) { + ntfs_log_error("$LogFile restart page specifies " + "inconsistent update sequence array count.\n"); + return FALSE; + } + /* Verify the position of the update sequence array. */ + usa_ofs = le16_to_cpu(rp->usa_ofs); + usa_end = usa_ofs + usa_count * sizeof(u16); + if (usa_ofs < sizeof(RESTART_PAGE_HEADER) || + usa_end > NTFS_BLOCK_SIZE - sizeof(u16)) { + ntfs_log_error("$LogFile restart page specifies " + "inconsistent update sequence array offset.\n"); + return FALSE; + } skip_usa_checks: - /* - * Verify the position of the restart area. It must be: - * - aligned to 8-byte boundary, - * - after the update sequence array, and - * - within the system page size. - */ - ra_ofs = le16_to_cpu(rp->restart_area_offset); - if (ra_ofs & 7 || (have_usa ? ra_ofs < usa_end : - ra_ofs < sizeof(RESTART_PAGE_HEADER)) || - ra_ofs > logfile_system_page_size) { - ntfs_log_error("$LogFile restart page specifies " - "inconsistent restart area offset.\n"); - return FALSE; - } - /* - * Only restart pages modified by chkdsk are allowed to have chkdsk_lsn - * set. - */ - if (!ntfs_is_chkd_record(rp->magic) && sle64_to_cpu(rp->chkdsk_lsn)) { - ntfs_log_error("$LogFile restart page is not modified " - "by chkdsk but a chkdsk LSN is specified.\n"); - return FALSE; - } - ntfs_log_trace("Done.\n"); - return TRUE; + /* + * Verify the position of the restart area. It must be: + * - aligned to 8-byte boundary, + * - after the update sequence array, and + * - within the system page size. + */ + ra_ofs = le16_to_cpu(rp->restart_area_offset); + if (ra_ofs & 7 || (have_usa ? ra_ofs < usa_end : + ra_ofs < sizeof(RESTART_PAGE_HEADER)) || + ra_ofs > logfile_system_page_size) { + ntfs_log_error("$LogFile restart page specifies " + "inconsistent restart area offset.\n"); + return FALSE; + } + /* + * Only restart pages modified by chkdsk are allowed to have chkdsk_lsn + * set. + */ + if (!ntfs_is_chkd_record(rp->magic) && sle64_to_cpu(rp->chkdsk_lsn)) { + ntfs_log_error("$LogFile restart page is not modified " + "by chkdsk but a chkdsk LSN is specified.\n"); + return FALSE; + } + ntfs_log_trace("Done.\n"); + return TRUE; } /** @@ -157,104 +158,105 @@ skip_usa_checks: * This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not * require the full restart page. */ -static BOOL ntfs_check_restart_area(RESTART_PAGE_HEADER *rp) { - u64 file_size; - RESTART_AREA *ra; - u16 ra_ofs, ra_len, ca_ofs; - u8 fs_bits; +static BOOL ntfs_check_restart_area(RESTART_PAGE_HEADER *rp) +{ + u64 file_size; + RESTART_AREA *ra; + u16 ra_ofs, ra_len, ca_ofs; + u8 fs_bits; - ntfs_log_trace("Entering.\n"); - ra_ofs = le16_to_cpu(rp->restart_area_offset); - ra = (RESTART_AREA*)((u8*)rp + ra_ofs); - /* - * Everything before ra->file_size must be before the first word - * protected by an update sequence number. This ensures that it is - * safe to access ra->client_array_offset. - */ - if (ra_ofs + offsetof(RESTART_AREA, file_size) > - NTFS_BLOCK_SIZE - sizeof(u16)) { - ntfs_log_error("$LogFile restart area specifies " - "inconsistent file offset.\n"); - return FALSE; - } - /* - * Now that we can access ra->client_array_offset, make sure everything - * up to the log client array is before the first word protected by an - * update sequence number. This ensures we can access all of the - * restart area elements safely. Also, the client array offset must be - * aligned to an 8-byte boundary. - */ - ca_ofs = le16_to_cpu(ra->client_array_offset); - if (((ca_ofs + 7) & ~7) != ca_ofs || - ra_ofs + ca_ofs > (u16)(NTFS_BLOCK_SIZE - - sizeof(u16))) { - ntfs_log_error("$LogFile restart area specifies " - "inconsistent client array offset.\n"); - return FALSE; - } - /* - * The restart area must end within the system page size both when - * calculated manually and as specified by ra->restart_area_length. - * Also, the calculated length must not exceed the specified length. - */ - ra_len = ca_ofs + le16_to_cpu(ra->log_clients) * - sizeof(LOG_CLIENT_RECORD); - if ((u32)(ra_ofs + ra_len) > le32_to_cpu(rp->system_page_size) || - (u32)(ra_ofs + le16_to_cpu(ra->restart_area_length)) > - le32_to_cpu(rp->system_page_size) || - ra_len > le16_to_cpu(ra->restart_area_length)) { - ntfs_log_error("$LogFile restart area is out of bounds " - "of the system page size specified by the " - "restart page header and/or the specified " - "restart area length is inconsistent.\n"); - return FALSE; - } - /* - * The ra->client_free_list and ra->client_in_use_list must be either - * LOGFILE_NO_CLIENT or less than ra->log_clients or they are - * overflowing the client array. - */ - if ((ra->client_free_list != LOGFILE_NO_CLIENT && - le16_to_cpu(ra->client_free_list) >= - le16_to_cpu(ra->log_clients)) || - (ra->client_in_use_list != LOGFILE_NO_CLIENT && - le16_to_cpu(ra->client_in_use_list) >= - le16_to_cpu(ra->log_clients))) { - ntfs_log_error("$LogFile restart area specifies " - "overflowing client free and/or in use lists.\n"); - return FALSE; - } - /* - * Check ra->seq_number_bits against ra->file_size for consistency. - * We cannot just use ffs() because the file size is not a power of 2. - */ - file_size = (u64)sle64_to_cpu(ra->file_size); - fs_bits = 0; - while (file_size) { - file_size >>= 1; - fs_bits++; - } - if (le32_to_cpu(ra->seq_number_bits) != (u32)(67 - fs_bits)) { - ntfs_log_error("$LogFile restart area specifies " - "inconsistent sequence number bits.\n"); - return FALSE; - } - /* The log record header length must be a multiple of 8. */ - if (((le16_to_cpu(ra->log_record_header_length) + 7) & ~7) != - le16_to_cpu(ra->log_record_header_length)) { - ntfs_log_error("$LogFile restart area specifies " - "inconsistent log record header length.\n"); - return FALSE; - } - /* Ditto for the log page data offset. */ - if (((le16_to_cpu(ra->log_page_data_offset) + 7) & ~7) != - le16_to_cpu(ra->log_page_data_offset)) { - ntfs_log_error("$LogFile restart area specifies " - "inconsistent log page data offset.\n"); - return FALSE; - } - ntfs_log_trace("Done.\n"); - return TRUE; + ntfs_log_trace("Entering.\n"); + ra_ofs = le16_to_cpu(rp->restart_area_offset); + ra = (RESTART_AREA*)((u8*)rp + ra_ofs); + /* + * Everything before ra->file_size must be before the first word + * protected by an update sequence number. This ensures that it is + * safe to access ra->client_array_offset. + */ + if (ra_ofs + offsetof(RESTART_AREA, file_size) > + NTFS_BLOCK_SIZE - sizeof(u16)) { + ntfs_log_error("$LogFile restart area specifies " + "inconsistent file offset.\n"); + return FALSE; + } + /* + * Now that we can access ra->client_array_offset, make sure everything + * up to the log client array is before the first word protected by an + * update sequence number. This ensures we can access all of the + * restart area elements safely. Also, the client array offset must be + * aligned to an 8-byte boundary. + */ + ca_ofs = le16_to_cpu(ra->client_array_offset); + if (((ca_ofs + 7) & ~7) != ca_ofs || + ra_ofs + ca_ofs > (u16)(NTFS_BLOCK_SIZE - + sizeof(u16))) { + ntfs_log_error("$LogFile restart area specifies " + "inconsistent client array offset.\n"); + return FALSE; + } + /* + * The restart area must end within the system page size both when + * calculated manually and as specified by ra->restart_area_length. + * Also, the calculated length must not exceed the specified length. + */ + ra_len = ca_ofs + le16_to_cpu(ra->log_clients) * + sizeof(LOG_CLIENT_RECORD); + if ((u32)(ra_ofs + ra_len) > le32_to_cpu(rp->system_page_size) || + (u32)(ra_ofs + le16_to_cpu(ra->restart_area_length)) > + le32_to_cpu(rp->system_page_size) || + ra_len > le16_to_cpu(ra->restart_area_length)) { + ntfs_log_error("$LogFile restart area is out of bounds " + "of the system page size specified by the " + "restart page header and/or the specified " + "restart area length is inconsistent.\n"); + return FALSE; + } + /* + * The ra->client_free_list and ra->client_in_use_list must be either + * LOGFILE_NO_CLIENT or less than ra->log_clients or they are + * overflowing the client array. + */ + if ((ra->client_free_list != LOGFILE_NO_CLIENT && + le16_to_cpu(ra->client_free_list) >= + le16_to_cpu(ra->log_clients)) || + (ra->client_in_use_list != LOGFILE_NO_CLIENT && + le16_to_cpu(ra->client_in_use_list) >= + le16_to_cpu(ra->log_clients))) { + ntfs_log_error("$LogFile restart area specifies " + "overflowing client free and/or in use lists.\n"); + return FALSE; + } + /* + * Check ra->seq_number_bits against ra->file_size for consistency. + * We cannot just use ffs() because the file size is not a power of 2. + */ + file_size = (u64)sle64_to_cpu(ra->file_size); + fs_bits = 0; + while (file_size) { + file_size >>= 1; + fs_bits++; + } + if (le32_to_cpu(ra->seq_number_bits) != (u32)(67 - fs_bits)) { + ntfs_log_error("$LogFile restart area specifies " + "inconsistent sequence number bits.\n"); + return FALSE; + } + /* The log record header length must be a multiple of 8. */ + if (((le16_to_cpu(ra->log_record_header_length) + 7) & ~7) != + le16_to_cpu(ra->log_record_header_length)) { + ntfs_log_error("$LogFile restart area specifies " + "inconsistent log record header length.\n"); + return FALSE; + } + /* Ditto for the log page data offset. */ + if (((le16_to_cpu(ra->log_page_data_offset) + 7) & ~7) != + le16_to_cpu(ra->log_page_data_offset)) { + ntfs_log_error("$LogFile restart area specifies " + "inconsistent log page data offset.\n"); + return FALSE; + } + ntfs_log_trace("Done.\n"); + return TRUE; } /** @@ -271,52 +273,53 @@ static BOOL ntfs_check_restart_area(RESTART_PAGE_HEADER *rp) { * function needs @rp->system_page_size bytes in @rp, i.e. it requires the full * restart page and the page must be multi sector transfer deprotected. */ -static BOOL ntfs_check_log_client_array(RESTART_PAGE_HEADER *rp) { - RESTART_AREA *ra; - LOG_CLIENT_RECORD *ca, *cr; - u16 nr_clients, idx; - BOOL in_free_list, idx_is_first; +static BOOL ntfs_check_log_client_array(RESTART_PAGE_HEADER *rp) +{ + RESTART_AREA *ra; + LOG_CLIENT_RECORD *ca, *cr; + u16 nr_clients, idx; + BOOL in_free_list, idx_is_first; - ntfs_log_trace("Entering.\n"); - ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset)); - ca = (LOG_CLIENT_RECORD*)((u8*)ra + - le16_to_cpu(ra->client_array_offset)); - /* - * Check the ra->client_free_list first and then check the - * ra->client_in_use_list. Check each of the log client records in - * each of the lists and check that the array does not overflow the - * ra->log_clients value. Also keep track of the number of records - * visited as there cannot be more than ra->log_clients records and - * that way we detect eventual loops in within a list. - */ - nr_clients = le16_to_cpu(ra->log_clients); - idx = le16_to_cpu(ra->client_free_list); - in_free_list = TRUE; + ntfs_log_trace("Entering.\n"); + ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset)); + ca = (LOG_CLIENT_RECORD*)((u8*)ra + + le16_to_cpu(ra->client_array_offset)); + /* + * Check the ra->client_free_list first and then check the + * ra->client_in_use_list. Check each of the log client records in + * each of the lists and check that the array does not overflow the + * ra->log_clients value. Also keep track of the number of records + * visited as there cannot be more than ra->log_clients records and + * that way we detect eventual loops in within a list. + */ + nr_clients = le16_to_cpu(ra->log_clients); + idx = le16_to_cpu(ra->client_free_list); + in_free_list = TRUE; check_list: - for (idx_is_first = TRUE; idx != LOGFILE_NO_CLIENT_CPU; nr_clients--, - idx = le16_to_cpu(cr->next_client)) { - if (!nr_clients || idx >= le16_to_cpu(ra->log_clients)) - goto err_out; - /* Set @cr to the current log client record. */ - cr = ca + idx; - /* The first log client record must not have a prev_client. */ - if (idx_is_first) { - if (cr->prev_client != LOGFILE_NO_CLIENT) - goto err_out; - idx_is_first = FALSE; - } - } - /* Switch to and check the in use list if we just did the free list. */ - if (in_free_list) { - in_free_list = FALSE; - idx = le16_to_cpu(ra->client_in_use_list); - goto check_list; - } - ntfs_log_trace("Done.\n"); - return TRUE; + for (idx_is_first = TRUE; idx != LOGFILE_NO_CLIENT_CPU; nr_clients--, + idx = le16_to_cpu(cr->next_client)) { + if (!nr_clients || idx >= le16_to_cpu(ra->log_clients)) + goto err_out; + /* Set @cr to the current log client record. */ + cr = ca + idx; + /* The first log client record must not have a prev_client. */ + if (idx_is_first) { + if (cr->prev_client != LOGFILE_NO_CLIENT) + goto err_out; + idx_is_first = FALSE; + } + } + /* Switch to and check the in use list if we just did the free list. */ + if (in_free_list) { + in_free_list = FALSE; + idx = le16_to_cpu(ra->client_in_use_list); + goto check_list; + } + ntfs_log_trace("Done.\n"); + return TRUE; err_out: - ntfs_log_error("$LogFile log client array is corrupt.\n"); - return FALSE; + ntfs_log_error("$LogFile log client array is corrupt.\n"); + return FALSE; } /** @@ -347,96 +350,97 @@ err_out: * EIO - Failed to reading from $LogFile. */ static int ntfs_check_and_load_restart_page(ntfs_attr *log_na, - RESTART_PAGE_HEADER *rp, s64 pos, RESTART_PAGE_HEADER **wrp, - LSN *lsn) { - RESTART_AREA *ra; - RESTART_PAGE_HEADER *trp; - int err; + RESTART_PAGE_HEADER *rp, s64 pos, RESTART_PAGE_HEADER **wrp, + LSN *lsn) +{ + RESTART_AREA *ra; + RESTART_PAGE_HEADER *trp; + int err; - ntfs_log_trace("Entering.\n"); - /* Check the restart page header for consistency. */ - if (!ntfs_check_restart_page_header(rp, pos)) { - /* Error output already done inside the function. */ - return EINVAL; - } - /* Check the restart area for consistency. */ - if (!ntfs_check_restart_area(rp)) { - /* Error output already done inside the function. */ - return EINVAL; - } - ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset)); - /* - * Allocate a buffer to store the whole restart page so we can multi - * sector transfer deprotect it. - */ - trp = ntfs_malloc(le32_to_cpu(rp->system_page_size)); - if (!trp) - return errno; - /* - * Read the whole of the restart page into the buffer. If it fits - * completely inside @rp, just copy it from there. Otherwise read it - * from disk. - */ - if (le32_to_cpu(rp->system_page_size) <= NTFS_BLOCK_SIZE) - memcpy(trp, rp, le32_to_cpu(rp->system_page_size)); - else if (ntfs_attr_pread(log_na, pos, - le32_to_cpu(rp->system_page_size), trp) != - le32_to_cpu(rp->system_page_size)) { - err = errno; - ntfs_log_error("Failed to read whole restart page into the " - "buffer.\n"); - if (err != ENOMEM) - err = EIO; - goto err_out; - } - /* - * Perform the multi sector transfer deprotection on the buffer if the - * restart page is protected. - */ - if ((!ntfs_is_chkd_record(trp->magic) || le16_to_cpu(trp->usa_count)) - && ntfs_mst_post_read_fixup((NTFS_RECORD*)trp, - le32_to_cpu(rp->system_page_size))) { - /* - * A multi sector tranfer error was detected. We only need to - * abort if the restart page contents exceed the multi sector - * transfer fixup of the first sector. - */ - if (le16_to_cpu(rp->restart_area_offset) + - le16_to_cpu(ra->restart_area_length) > - NTFS_BLOCK_SIZE - (int)sizeof(u16)) { - ntfs_log_error("Multi sector transfer error " - "detected in $LogFile restart page.\n"); - err = EINVAL; - goto err_out; - } - } - /* - * If the restart page is modified by chkdsk or there are no active - * logfile clients, the logfile is consistent. Otherwise, need to - * check the log client records for consistency, too. - */ - err = 0; - if (ntfs_is_rstr_record(rp->magic) && - ra->client_in_use_list != LOGFILE_NO_CLIENT) { - if (!ntfs_check_log_client_array(trp)) { - err = EINVAL; - goto err_out; - } - } - if (lsn) { - if (ntfs_is_rstr_record(rp->magic)) - *lsn = sle64_to_cpu(ra->current_lsn); - else /* if (ntfs_is_chkd_record(rp->magic)) */ - *lsn = sle64_to_cpu(rp->chkdsk_lsn); - } - ntfs_log_trace("Done.\n"); - if (wrp) - *wrp = trp; - else { + ntfs_log_trace("Entering.\n"); + /* Check the restart page header for consistency. */ + if (!ntfs_check_restart_page_header(rp, pos)) { + /* Error output already done inside the function. */ + return EINVAL; + } + /* Check the restart area for consistency. */ + if (!ntfs_check_restart_area(rp)) { + /* Error output already done inside the function. */ + return EINVAL; + } + ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset)); + /* + * Allocate a buffer to store the whole restart page so we can multi + * sector transfer deprotect it. + */ + trp = ntfs_malloc(le32_to_cpu(rp->system_page_size)); + if (!trp) + return errno; + /* + * Read the whole of the restart page into the buffer. If it fits + * completely inside @rp, just copy it from there. Otherwise read it + * from disk. + */ + if (le32_to_cpu(rp->system_page_size) <= NTFS_BLOCK_SIZE) + memcpy(trp, rp, le32_to_cpu(rp->system_page_size)); + else if (ntfs_attr_pread(log_na, pos, + le32_to_cpu(rp->system_page_size), trp) != + le32_to_cpu(rp->system_page_size)) { + err = errno; + ntfs_log_error("Failed to read whole restart page into the " + "buffer.\n"); + if (err != ENOMEM) + err = EIO; + goto err_out; + } + /* + * Perform the multi sector transfer deprotection on the buffer if the + * restart page is protected. + */ + if ((!ntfs_is_chkd_record(trp->magic) || le16_to_cpu(trp->usa_count)) + && ntfs_mst_post_read_fixup((NTFS_RECORD*)trp, + le32_to_cpu(rp->system_page_size))) { + /* + * A multi sector tranfer error was detected. We only need to + * abort if the restart page contents exceed the multi sector + * transfer fixup of the first sector. + */ + if (le16_to_cpu(rp->restart_area_offset) + + le16_to_cpu(ra->restart_area_length) > + NTFS_BLOCK_SIZE - (int)sizeof(u16)) { + ntfs_log_error("Multi sector transfer error " + "detected in $LogFile restart page.\n"); + err = EINVAL; + goto err_out; + } + } + /* + * If the restart page is modified by chkdsk or there are no active + * logfile clients, the logfile is consistent. Otherwise, need to + * check the log client records for consistency, too. + */ + err = 0; + if (ntfs_is_rstr_record(rp->magic) && + ra->client_in_use_list != LOGFILE_NO_CLIENT) { + if (!ntfs_check_log_client_array(trp)) { + err = EINVAL; + goto err_out; + } + } + if (lsn) { + if (ntfs_is_rstr_record(rp->magic)) + *lsn = sle64_to_cpu(ra->current_lsn); + else /* if (ntfs_is_chkd_record(rp->magic)) */ + *lsn = sle64_to_cpu(rp->chkdsk_lsn); + } + ntfs_log_trace("Done.\n"); + if (wrp) + *wrp = trp; + else { err_out: - free(trp); - } - return err; + free(trp); + } + return err; } /** @@ -456,171 +460,172 @@ err_out: * if the $LogFile was created on a system with a different page size to ours * yet and mst deprotection would fail if our page size is smaller. */ -BOOL ntfs_check_logfile(ntfs_attr *log_na, RESTART_PAGE_HEADER **rp) { - s64 size, pos; - LSN rstr1_lsn, rstr2_lsn; - ntfs_volume *vol = log_na->ni->vol; - u8 *kaddr = NULL; - RESTART_PAGE_HEADER *rstr1_ph = NULL; - RESTART_PAGE_HEADER *rstr2_ph = NULL; - int log_page_size, log_page_mask, err; - BOOL logfile_is_empty = TRUE; - u8 log_page_bits; +BOOL ntfs_check_logfile(ntfs_attr *log_na, RESTART_PAGE_HEADER **rp) +{ + s64 size, pos; + LSN rstr1_lsn, rstr2_lsn; + ntfs_volume *vol = log_na->ni->vol; + u8 *kaddr = NULL; + RESTART_PAGE_HEADER *rstr1_ph = NULL; + RESTART_PAGE_HEADER *rstr2_ph = NULL; + int log_page_size, log_page_mask, err; + BOOL logfile_is_empty = TRUE; + u8 log_page_bits; - ntfs_log_trace("Entering.\n"); - /* An empty $LogFile must have been clean before it got emptied. */ - if (NVolLogFileEmpty(vol)) - goto is_empty; - size = log_na->data_size; - /* Make sure the file doesn't exceed the maximum allowed size. */ - if (size > (s64)MaxLogFileSize) - size = MaxLogFileSize; - log_page_size = DefaultLogPageSize; - log_page_mask = log_page_size - 1; - /* - * Use generic_ffs() instead of ffs() to enable the compiler to - * optimize log_page_size and log_page_bits into constants. - */ - log_page_bits = ffs(log_page_size) - 1; - size &= ~(log_page_size - 1); + ntfs_log_trace("Entering.\n"); + /* An empty $LogFile must have been clean before it got emptied. */ + if (NVolLogFileEmpty(vol)) + goto is_empty; + size = log_na->data_size; + /* Make sure the file doesn't exceed the maximum allowed size. */ + if (size > (s64)MaxLogFileSize) + size = MaxLogFileSize; + log_page_size = DefaultLogPageSize; + log_page_mask = log_page_size - 1; + /* + * Use generic_ffs() instead of ffs() to enable the compiler to + * optimize log_page_size and log_page_bits into constants. + */ + log_page_bits = ffs(log_page_size) - 1; + size &= ~(log_page_size - 1); - /* - * Ensure the log file is big enough to store at least the two restart - * pages and the minimum number of log record pages. - */ - if (size < log_page_size * 2 || (size - log_page_size * 2) >> - log_page_bits < MinLogRecordPages) { - ntfs_log_error("$LogFile is too small.\n"); - return FALSE; - } - /* Allocate memory for restart page. */ - kaddr = ntfs_malloc(NTFS_BLOCK_SIZE); - if (!kaddr) - return FALSE; - /* - * Read through the file looking for a restart page. Since the restart - * page header is at the beginning of a page we only need to search at - * what could be the beginning of a page (for each page size) rather - * than scanning the whole file byte by byte. If all potential places - * contain empty and uninitialized records, the log file can be assumed - * to be empty. - */ - for (pos = 0; pos < size; pos <<= 1) { - /* - * Read first NTFS_BLOCK_SIZE bytes of potential restart page. - */ - if (ntfs_attr_pread(log_na, pos, NTFS_BLOCK_SIZE, kaddr) != - NTFS_BLOCK_SIZE) { - ntfs_log_error("Failed to read first NTFS_BLOCK_SIZE " - "bytes of potential restart page.\n"); - goto err_out; - } + /* + * Ensure the log file is big enough to store at least the two restart + * pages and the minimum number of log record pages. + */ + if (size < log_page_size * 2 || (size - log_page_size * 2) >> + log_page_bits < MinLogRecordPages) { + ntfs_log_error("$LogFile is too small.\n"); + return FALSE; + } + /* Allocate memory for restart page. */ + kaddr = ntfs_malloc(NTFS_BLOCK_SIZE); + if (!kaddr) + return FALSE; + /* + * Read through the file looking for a restart page. Since the restart + * page header is at the beginning of a page we only need to search at + * what could be the beginning of a page (for each page size) rather + * than scanning the whole file byte by byte. If all potential places + * contain empty and uninitialized records, the log file can be assumed + * to be empty. + */ + for (pos = 0; pos < size; pos <<= 1) { + /* + * Read first NTFS_BLOCK_SIZE bytes of potential restart page. + */ + if (ntfs_attr_pread(log_na, pos, NTFS_BLOCK_SIZE, kaddr) != + NTFS_BLOCK_SIZE) { + ntfs_log_error("Failed to read first NTFS_BLOCK_SIZE " + "bytes of potential restart page.\n"); + goto err_out; + } - /* - * A non-empty block means the logfile is not empty while an - * empty block after a non-empty block has been encountered - * means we are done. - */ - if (!ntfs_is_empty_recordp((le32*)kaddr)) - logfile_is_empty = FALSE; - else if (!logfile_is_empty) - break; - /* - * A log record page means there cannot be a restart page after - * this so no need to continue searching. - */ - if (ntfs_is_rcrd_recordp((le32*)kaddr)) - break; - /* If not a (modified by chkdsk) restart page, continue. */ - if (!ntfs_is_rstr_recordp((le32*)kaddr) && - !ntfs_is_chkd_recordp((le32*)kaddr)) { - if (!pos) - pos = NTFS_BLOCK_SIZE >> 1; - continue; - } - /* - * Check the (modified by chkdsk) restart page for consistency - * and get a copy of the complete multi sector transfer - * deprotected restart page. - */ - err = ntfs_check_and_load_restart_page(log_na, - (RESTART_PAGE_HEADER*)kaddr, pos, - !rstr1_ph ? &rstr1_ph : &rstr2_ph, - !rstr1_ph ? &rstr1_lsn : &rstr2_lsn); - if (!err) { - /* - * If we have now found the first (modified by chkdsk) - * restart page, continue looking for the second one. - */ - if (!pos) { - pos = NTFS_BLOCK_SIZE >> 1; - continue; - } - /* - * We have now found the second (modified by chkdsk) - * restart page, so we can stop looking. - */ - break; - } - /* - * Error output already done inside the function. Note, we do - * not abort if the restart page was invalid as we might still - * find a valid one further in the file. - */ - if (err != EINVAL) - goto err_out; - /* Continue looking. */ - if (!pos) - pos = NTFS_BLOCK_SIZE >> 1; - } - if (kaddr) { - free(kaddr); - kaddr = NULL; - } - if (logfile_is_empty) { - NVolSetLogFileEmpty(vol); + /* + * A non-empty block means the logfile is not empty while an + * empty block after a non-empty block has been encountered + * means we are done. + */ + if (!ntfs_is_empty_recordp((le32*)kaddr)) + logfile_is_empty = FALSE; + else if (!logfile_is_empty) + break; + /* + * A log record page means there cannot be a restart page after + * this so no need to continue searching. + */ + if (ntfs_is_rcrd_recordp((le32*)kaddr)) + break; + /* If not a (modified by chkdsk) restart page, continue. */ + if (!ntfs_is_rstr_recordp((le32*)kaddr) && + !ntfs_is_chkd_recordp((le32*)kaddr)) { + if (!pos) + pos = NTFS_BLOCK_SIZE >> 1; + continue; + } + /* + * Check the (modified by chkdsk) restart page for consistency + * and get a copy of the complete multi sector transfer + * deprotected restart page. + */ + err = ntfs_check_and_load_restart_page(log_na, + (RESTART_PAGE_HEADER*)kaddr, pos, + !rstr1_ph ? &rstr1_ph : &rstr2_ph, + !rstr1_ph ? &rstr1_lsn : &rstr2_lsn); + if (!err) { + /* + * If we have now found the first (modified by chkdsk) + * restart page, continue looking for the second one. + */ + if (!pos) { + pos = NTFS_BLOCK_SIZE >> 1; + continue; + } + /* + * We have now found the second (modified by chkdsk) + * restart page, so we can stop looking. + */ + break; + } + /* + * Error output already done inside the function. Note, we do + * not abort if the restart page was invalid as we might still + * find a valid one further in the file. + */ + if (err != EINVAL) + goto err_out; + /* Continue looking. */ + if (!pos) + pos = NTFS_BLOCK_SIZE >> 1; + } + if (kaddr) { + free(kaddr); + kaddr = NULL; + } + if (logfile_is_empty) { + NVolSetLogFileEmpty(vol); is_empty: - ntfs_log_trace("Done. ($LogFile is empty.)\n"); - return TRUE; - } - if (!rstr1_ph) { - if (rstr2_ph) - ntfs_log_error("BUG: rstr2_ph isn't NULL!\n"); - ntfs_log_error("Did not find any restart pages in " - "$LogFile and it was not empty.\n"); - return FALSE; - } - /* If both restart pages were found, use the more recent one. */ - if (rstr2_ph) { - /* - * If the second restart area is more recent, switch to it. - * Otherwise just throw it away. - */ - if (rstr2_lsn > rstr1_lsn) { - ntfs_log_debug("Using second restart page as it is more " - "recent.\n"); - free(rstr1_ph); - rstr1_ph = rstr2_ph; - /* rstr1_lsn = rstr2_lsn; */ - } else { - ntfs_log_debug("Using first restart page as it is more " - "recent.\n"); - free(rstr2_ph); - } - rstr2_ph = NULL; - } - /* All consistency checks passed. */ - if (rp) - *rp = rstr1_ph; - else - free(rstr1_ph); - ntfs_log_trace("Done.\n"); - return TRUE; + ntfs_log_trace("Done. ($LogFile is empty.)\n"); + return TRUE; + } + if (!rstr1_ph) { + if (rstr2_ph) + ntfs_log_error("BUG: rstr2_ph isn't NULL!\n"); + ntfs_log_error("Did not find any restart pages in " + "$LogFile and it was not empty.\n"); + return FALSE; + } + /* If both restart pages were found, use the more recent one. */ + if (rstr2_ph) { + /* + * If the second restart area is more recent, switch to it. + * Otherwise just throw it away. + */ + if (rstr2_lsn > rstr1_lsn) { + ntfs_log_debug("Using second restart page as it is more " + "recent.\n"); + free(rstr1_ph); + rstr1_ph = rstr2_ph; + /* rstr1_lsn = rstr2_lsn; */ + } else { + ntfs_log_debug("Using first restart page as it is more " + "recent.\n"); + free(rstr2_ph); + } + rstr2_ph = NULL; + } + /* All consistency checks passed. */ + if (rp) + *rp = rstr1_ph; + else + free(rstr1_ph); + ntfs_log_trace("Done.\n"); + return TRUE; err_out: - free(kaddr); - free(rstr1_ph); - free(rstr2_ph); - return FALSE; + free(kaddr); + free(rstr1_ph); + free(rstr2_ph); + return FALSE; } /** @@ -643,41 +648,42 @@ err_out: * is empty this function requires that NVolLogFileEmpty() is true otherwise an * empty volume will be reported as dirty. */ -BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp) { - RESTART_AREA *ra; +BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp) +{ + RESTART_AREA *ra; - ntfs_log_trace("Entering.\n"); - /* An empty $LogFile must have been clean before it got emptied. */ - if (NVolLogFileEmpty(log_na->ni->vol)) { - ntfs_log_trace("$LogFile is empty\n"); - return TRUE; - } - if (!rp) { - ntfs_log_error("Restart page header is NULL\n"); - return FALSE; - } - if (!ntfs_is_rstr_record(rp->magic) && - !ntfs_is_chkd_record(rp->magic)) { - ntfs_log_error("Restart page buffer is invalid\n"); - return FALSE; - } + ntfs_log_trace("Entering.\n"); + /* An empty $LogFile must have been clean before it got emptied. */ + if (NVolLogFileEmpty(log_na->ni->vol)) { + ntfs_log_trace("$LogFile is empty\n"); + return TRUE; + } + if (!rp) { + ntfs_log_error("Restart page header is NULL\n"); + return FALSE; + } + if (!ntfs_is_rstr_record(rp->magic) && + !ntfs_is_chkd_record(rp->magic)) { + ntfs_log_error("Restart page buffer is invalid\n"); + return FALSE; + } - ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset)); - /* - * If the $LogFile has active clients, i.e. it is open, and we do not - * have the RESTART_VOLUME_IS_CLEAN bit set in the restart area flags, - * we assume there was an unclean shutdown. - */ - if (ra->client_in_use_list != LOGFILE_NO_CLIENT && - !(ra->flags & RESTART_VOLUME_IS_CLEAN)) { - ntfs_log_error("The disk contains an unclean file system (%d, " - "%d).\n", le16_to_cpu(ra->client_in_use_list), - le16_to_cpu(ra->flags)); - return FALSE; - } - /* $LogFile indicates a clean shutdown. */ - ntfs_log_trace("$LogFile indicates a clean shutdown\n"); - return TRUE; + ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset)); + /* + * If the $LogFile has active clients, i.e. it is open, and we do not + * have the RESTART_VOLUME_IS_CLEAN bit set in the restart area flags, + * we assume there was an unclean shutdown. + */ + if (ra->client_in_use_list != LOGFILE_NO_CLIENT && + !(ra->flags & RESTART_VOLUME_IS_CLEAN)) { + ntfs_log_error("The disk contains an unclean file system (%d, " + "%d).\n", le16_to_cpu(ra->client_in_use_list), + le16_to_cpu(ra->flags)); + return FALSE; + } + /* $LogFile indicates a clean shutdown. */ + ntfs_log_trace("$LogFile indicates a clean shutdown\n"); + return TRUE; } /** @@ -691,40 +697,41 @@ BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp) { * checked by a call to ntfs_check_logfile() and that ntfs_is_logfile_clean() * has been used to ensure that the $LogFile is clean. */ -int ntfs_empty_logfile(ntfs_attr *na) { - /*s64 pos, count; - char buf[NTFS_BUF_SIZE];*/ +int ntfs_empty_logfile(ntfs_attr *na) +{ + /*s64 pos, count; + char buf[NTFS_BUF_SIZE];*/ - ntfs_log_trace("Entering.\n"); + ntfs_log_trace("Entering.\n"); + + if (NVolLogFileEmpty(na->ni->vol)) + return 0; - if (NVolLogFileEmpty(na->ni->vol)) - return 0; + if (!NAttrNonResident(na)) { + errno = EIO; + ntfs_log_perror("Resident $LogFile $DATA attribute"); + return -1; + } - if (!NAttrNonResident(na)) { - errno = EIO; - ntfs_log_perror("Resident $LogFile $DATA attribute"); - return -1; - } + /*memset(buf, -1, NTFS_BUF_SIZE); - /*memset(buf, -1, NTFS_BUF_SIZE); + pos = 0; + while ((count = na->data_size - pos) > 0) { + + if (count > NTFS_BUF_SIZE) + count = NTFS_BUF_SIZE; - pos = 0; - while ((count = na->data_size - pos) > 0) { + count = ntfs_attr_pwrite(na, pos, count, buf); + if (count <= 0) { + ntfs_log_perror("Failed to reset $LogFile"); + if (count != -1) + errno = EIO; + return -1; + } + pos += count; + }*/ - if (count > NTFS_BUF_SIZE) - count = NTFS_BUF_SIZE; - - count = ntfs_attr_pwrite(na, pos, count, buf); - if (count <= 0) { - ntfs_log_perror("Failed to reset $LogFile"); - if (count != -1) - errno = EIO; - return -1; - } - pos += count; - }*/ - - NVolSetLogFileEmpty(na->ni->vol); - - return 0; + NVolSetLogFileEmpty(na->ni->vol); + + return 0; } diff --git a/source/libntfs/logfile.h b/source/libntfs/logfile.h index 7477b35d..798d562d 100644 --- a/source/libntfs/logfile.h +++ b/source/libntfs/logfile.h @@ -62,47 +62,38 @@ * Begins the restart area. */ typedef struct { - /*Ofs*/ - /* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ - /* 0*/ - NTFS_RECORD_TYPES magic;/* The magic is "RSTR". */ - /* 4*/ - le16 usa_ofs; /* See NTFS_RECORD definition in layout.h. +/*Ofs*/ +/* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ +/* 0*/ NTFS_RECORD_TYPES magic;/* The magic is "RSTR". */ +/* 4*/ le16 usa_ofs; /* See NTFS_RECORD definition in layout.h. When creating, set this to be immediately after this header structure (without any alignment). */ - /* 6*/ - le16 usa_count; /* See NTFS_RECORD definition in layout.h. */ +/* 6*/ le16 usa_count; /* See NTFS_RECORD definition in layout.h. */ - /* 8*/ - leLSN chkdsk_lsn; /* The last log file sequence number found by +/* 8*/ leLSN chkdsk_lsn; /* The last log file sequence number found by chkdsk. Only used when the magic is changed to "CHKD". Otherwise this is zero. */ - /* 16*/ - le32 system_page_size; /* Byte size of system pages when the log file +/* 16*/ le32 system_page_size; /* Byte size of system pages when the log file was created, has to be >= 512 and a power of 2. Use this to calculate the required size of the usa (usa_count) and add it to usa_ofs. Then verify that the result is less than the value of the restart_area_offset. */ - /* 20*/ - le32 log_page_size; /* Byte size of log file pages, has to be >= +/* 20*/ le32 log_page_size; /* Byte size of log file pages, has to be >= 512 and a power of 2. The default is 4096 and is used when the system page size is between 4096 and 8192. Otherwise this is set to the system page size instead. */ - /* 24*/ - le16 restart_area_offset;/* Byte offset from the start of this header to +/* 24*/ le16 restart_area_offset;/* Byte offset from the start of this header to the RESTART_AREA. Value has to be aligned to 8-byte boundary. When creating, set this to be after the usa. */ - /* 26*/ - sle16 minor_ver; /* Log file minor version. Only check if major +/* 26*/ sle16 minor_ver; /* Log file minor version. Only check if major version is 1. */ - /* 28*/ - sle16 major_ver; /* Log file major version. We only support +/* 28*/ sle16 major_ver; /* Log file major version. We only support version 1.1. */ - /* sizeof() = 30 (0x1e) bytes */ +/* sizeof() = 30 (0x1e) bytes */ } __attribute__((__packed__)) RESTART_PAGE_HEADER; /* @@ -118,8 +109,8 @@ typedef struct { * information about the log file in which they are present. */ enum { - RESTART_VOLUME_IS_CLEAN = const_cpu_to_le16(0x0002), - RESTART_SPACE_FILLER = 0xffff, /* gcc: Force enum bit width to 16. */ + RESTART_VOLUME_IS_CLEAN = const_cpu_to_le16(0x0002), + RESTART_SPACE_FILLER = 0xffff, /* gcc: Force enum bit width to 16. */ } __attribute__((__packed__)); typedef le16 RESTART_AREA_FLAGS; @@ -132,20 +123,17 @@ typedef le16 RESTART_AREA_FLAGS; * See notes at restart_area_offset above. */ typedef struct { - /*Ofs*/ - /* 0*/ - leLSN current_lsn; /* The current, i.e. last LSN inside the log +/*Ofs*/ +/* 0*/ leLSN current_lsn; /* The current, i.e. last LSN inside the log when the restart area was last written. This happens often but what is the interval? Is it just fixed time or is it every time a check point is written or something else? On create set to 0. */ - /* 8*/ - le16 log_clients; /* Number of log client records in the array of +/* 8*/ le16 log_clients; /* Number of log client records in the array of log client records which follows this restart area. Must be 1. */ - /* 10*/ - le16 client_free_list; /* The index of the first free log client record +/* 10*/ le16 client_free_list; /* The index of the first free log client record in the array of log client records. LOGFILE_NO_CLIENT means that there are no free log client records in the array. @@ -161,8 +149,7 @@ typedef struct { and presumably later, the logfile is always open, even on clean shutdown so this should always be LOGFILE_NO_CLIENT. */ - /* 12*/ - le16 client_in_use_list;/* The index of the first in-use log client +/* 12*/ le16 client_in_use_list;/* The index of the first in-use log client record in the array of log client records. LOGFILE_NO_CLIENT means that there are no in-use log client records in the array. If @@ -179,8 +166,7 @@ typedef struct { presumably later, the logfile is always open, even on clean shutdown so this should always be 0. */ - /* 14*/ - RESTART_AREA_FLAGS flags;/* Flags modifying LFS behaviour. On Win2k +/* 14*/ RESTART_AREA_FLAGS flags;/* Flags modifying LFS behaviour. On Win2k and presumably earlier this is always 0. On WinXP and presumably later, if the logfile was shutdown cleanly, the second bit, @@ -196,15 +182,13 @@ typedef struct { clean. If on the other hand the logfile is open and this bit is clear, we can be almost certain that the logfile is dirty. */ - /* 16*/ - le32 seq_number_bits; /* How many bits to use for the sequence +/* 16*/ le32 seq_number_bits; /* How many bits to use for the sequence number. This is calculated as 67 - the number of bits required to store the logfile size in bytes and this can be used in with the specified file_size as a consistency check. */ - /* 20*/ - le16 restart_area_length;/* Length of the restart area including the +/* 20*/ le16 restart_area_length;/* Length of the restart area including the client array. Following checks required if version matches. Otherwise, skip them. restart_area_offset + restart_area_length @@ -212,8 +196,7 @@ typedef struct { restart_area_length has to be >= client_array_offset + (log_clients * sizeof(log client record)). */ - /* 22*/ - le16 client_array_offset;/* Offset from the start of this record to +/* 22*/ le16 client_array_offset;/* Offset from the start of this record to the first log client record if versions are matched. When creating, set this to be after this restart area structure, aligned @@ -235,8 +218,7 @@ typedef struct { the client array. This probably means that the RESTART_AREA record is actually bigger in WinXP and later. */ - /* 24*/ - sle64 file_size; /* Usable byte size of the log file. If the +/* 24*/ sle64 file_size; /* Usable byte size of the log file. If the restart_area_offset + the offset of the file_size are > 510 then corruption has occurred. This is the very first check when @@ -249,12 +231,10 @@ typedef struct { then it has to be at least big enough to store the two restart pages and 48 (0x30) log record pages. */ - /* 32*/ - le32 last_lsn_data_length;/* Length of data of last LSN, not including +/* 32*/ le32 last_lsn_data_length;/* Length of data of last LSN, not including the log record header. On create set to 0. */ - /* 36*/ - le16 log_record_header_length;/* Byte size of the log record header. +/* 36*/ le16 log_record_header_length;/* Byte size of the log record header. If the version matches then check that the value of log_record_header_length is a multiple of 8, i.e. @@ -262,21 +242,18 @@ typedef struct { log_record_header_length. When creating set it to sizeof(LOG_RECORD_HEADER), aligned to 8 bytes. */ - /* 38*/ - le16 log_page_data_offset;/* Offset to the start of data in a log record +/* 38*/ le16 log_page_data_offset;/* Offset to the start of data in a log record page. Must be a multiple of 8. On create set it to immediately after the update sequence array of the log record page. */ - /* 40*/ - le32 restart_log_open_count;/* A counter that gets incremented every +/* 40*/ le32 restart_log_open_count;/* A counter that gets incremented every time the logfile is restarted which happens at mount time when the logfile is opened. When creating set to a random value. Win2k sets it to the low 32 bits of the current system time in NTFS format (see time.h). */ - /* 44*/ - le32 reserved; /* Reserved/alignment to 8-byte boundary. */ - /* sizeof() = 48 (0x30) bytes */ +/* 44*/ le32 reserved; /* Reserved/alignment to 8-byte boundary. */ +/* sizeof() = 48 (0x30) bytes */ } __attribute__((__packed__)) RESTART_AREA; /** @@ -286,46 +263,38 @@ typedef struct { * RESTART_AREA to the client_array_offset value found in it. */ typedef struct { - /*Ofs*/ - /* 0*/ - leLSN oldest_lsn; /* Oldest LSN needed by this client. On create +/*Ofs*/ +/* 0*/ leLSN oldest_lsn; /* Oldest LSN needed by this client. On create set to 0. */ - /* 8*/ - leLSN client_restart_lsn;/* LSN at which this client needs to restart +/* 8*/ leLSN client_restart_lsn;/* LSN at which this client needs to restart the volume, i.e. the current position within the log file. At present, if clean this should = current_lsn in restart area but it probably also = current_lsn when dirty most of the time. At create set to 0. */ - /* 16*/ - le16 prev_client; /* The offset to the previous log client record +/* 16*/ le16 prev_client; /* The offset to the previous log client record in the array of log client records. LOGFILE_NO_CLIENT means there is no previous client record, i.e. this is the first one. This is always LOGFILE_NO_CLIENT. */ - /* 18*/ - le16 next_client; /* The offset to the next log client record in +/* 18*/ le16 next_client; /* The offset to the next log client record in the array of log client records. LOGFILE_NO_CLIENT means there are no next client records, i.e. this is the last one. This is always LOGFILE_NO_CLIENT. */ - /* 20*/ - le16 seq_number; /* On Win2k and presumably earlier, this is set +/* 20*/ le16 seq_number; /* On Win2k and presumably earlier, this is set to zero every time the logfile is restarted and it is incremented when the logfile is closed at dismount time. Thus it is 0 when dirty and 1 when clean. On WinXP and presumably later, this is always 0. */ - /* 22*/ - u8 reserved[6]; /* Reserved/alignment. */ - /* 28*/ - le32 client_name_length;/* Length of client name in bytes. Should +/* 22*/ u8 reserved[6]; /* Reserved/alignment. */ +/* 28*/ le32 client_name_length;/* Length of client name in bytes. Should always be 8. */ - /* 32*/ - ntfschar client_name[64];/* Name of the client in Unicode. Should +/* 32*/ ntfschar client_name[64];/* Name of the client in Unicode. Should always be "NTFS" with the remaining bytes set to 0. */ - /* sizeof() = 160 (0xa0) bytes */ +/* sizeof() = 160 (0xa0) bytes */ } __attribute__((__packed__)) LOG_CLIENT_RECORD; /** @@ -337,28 +306,28 @@ typedef struct { * this specified anywhere?). */ typedef struct { - /* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ - NTFS_RECORD_TYPES magic;/* Usually the magic is "RCRD". */ - u16 usa_ofs; /* See NTFS_RECORD definition in layout.h. +/* 0 NTFS_RECORD; -- Unfolded here as gcc doesn't like unnamed structs. */ + NTFS_RECORD_TYPES magic;/* Usually the magic is "RCRD". */ + u16 usa_ofs; /* See NTFS_RECORD definition in layout.h. When creating, set this to be immediately after this header structure (without any alignment). */ - u16 usa_count; /* See NTFS_RECORD definition in layout.h. */ + u16 usa_count; /* See NTFS_RECORD definition in layout.h. */ - union { - LSN last_lsn; - s64 file_offset; - } __attribute__((__packed__)) copy; - u32 flags; - u16 page_count; - u16 page_position; - union { - struct { - u16 next_record_offset; - u8 reserved[6]; - LSN last_end_lsn; - } __attribute__((__packed__)) packed; - } __attribute__((__packed__)) header; + union { + LSN last_lsn; + s64 file_offset; + } __attribute__((__packed__)) copy; + u32 flags; + u16 page_count; + u16 page_position; + union { + struct { + u16 next_record_offset; + u8 reserved[6]; + LSN last_end_lsn; + } __attribute__((__packed__)) packed; + } __attribute__((__packed__)) header; } __attribute__((__packed__)) RECORD_PAGE_HEADER; /** @@ -367,18 +336,18 @@ typedef struct { * (Or is it log record pages?) */ typedef enum { - LOG_RECORD_MULTI_PAGE = const_cpu_to_le16(0x0001), /* ??? */ - LOG_RECORD_SIZE_PLACE_HOLDER = 0xffff, - /* This has nothing to do with the log record. It is only so - gcc knows to make the flags 16-bit. */ + LOG_RECORD_MULTI_PAGE = const_cpu_to_le16(0x0001), /* ??? */ + LOG_RECORD_SIZE_PLACE_HOLDER = 0xffff, + /* This has nothing to do with the log record. It is only so + gcc knows to make the flags 16-bit. */ } __attribute__((__packed__)) LOG_RECORD_FLAGS; /** * struct LOG_CLIENT_ID - The log client id structure identifying a log client. */ typedef struct { - u16 seq_number; - u16 client_index; + u16 seq_number; + u16 client_index; } __attribute__((__packed__)) LOG_CLIENT_ID; /** @@ -387,35 +356,35 @@ typedef struct { * Each log record seems to have a constant size of 0x70 bytes. */ typedef struct { - LSN this_lsn; - LSN client_previous_lsn; - LSN client_undo_next_lsn; - u32 client_data_length; - LOG_CLIENT_ID client_id; - u32 record_type; - u32 transaction_id; - u16 flags; - u16 reserved_or_alignment[3]; - /* Now are at ofs 0x30 into struct. */ - u16 redo_operation; - u16 undo_operation; - u16 redo_offset; - u16 redo_length; - u16 undo_offset; - u16 undo_length; - u16 target_attribute; - u16 lcns_to_follow; /* Number of lcn_list entries + LSN this_lsn; + LSN client_previous_lsn; + LSN client_undo_next_lsn; + u32 client_data_length; + LOG_CLIENT_ID client_id; + u32 record_type; + u32 transaction_id; + u16 flags; + u16 reserved_or_alignment[3]; +/* Now are at ofs 0x30 into struct. */ + u16 redo_operation; + u16 undo_operation; + u16 redo_offset; + u16 redo_length; + u16 undo_offset; + u16 undo_length; + u16 target_attribute; + u16 lcns_to_follow; /* Number of lcn_list entries following this entry. */ - /* Now at ofs 0x40. */ - u16 record_offset; - u16 attribute_offset; - u32 alignment_or_reserved; - VCN target_vcn; - /* Now at ofs 0x50. */ - struct { /* Only present if lcns_to_follow +/* Now at ofs 0x40. */ + u16 record_offset; + u16 attribute_offset; + u32 alignment_or_reserved; + VCN target_vcn; +/* Now at ofs 0x50. */ + struct { /* Only present if lcns_to_follow is not 0. */ - LCN lcn; - } __attribute__((__packed__)) lcn_list[0]; + LCN lcn; + } __attribute__((__packed__)) lcn_list[0]; } __attribute__((__packed__)) LOG_RECORD; extern BOOL ntfs_check_logfile(ntfs_attr *log_na, RESTART_PAGE_HEADER **rp); diff --git a/source/libntfs/logging.c b/source/libntfs/logging.c index ab66cf82..385bcaa6 100644 --- a/source/libntfs/logging.c +++ b/source/libntfs/logging.c @@ -68,9 +68,9 @@ static int tab; * @handler: Function to perform the actual logging */ struct ntfs_logging { - u32 levels; - u32 flags; - ntfs_log_handler *handler BROKEN_GCC_FORMAT_ATTRIBUTE; + u32 levels; + u32 flags; + ntfs_log_handler *handler BROKEN_GCC_FORMAT_ATTRIBUTE; }; /** @@ -79,17 +79,17 @@ struct ntfs_logging { */ static struct ntfs_logging ntfs_log = { #ifdef DEBUG - NTFS_LOG_LEVEL_DEBUG | NTFS_LOG_LEVEL_TRACE | NTFS_LOG_LEVEL_ENTER | - NTFS_LOG_LEVEL_LEAVE | + NTFS_LOG_LEVEL_DEBUG | NTFS_LOG_LEVEL_TRACE | NTFS_LOG_LEVEL_ENTER | + NTFS_LOG_LEVEL_LEAVE | #endif - NTFS_LOG_LEVEL_INFO | NTFS_LOG_LEVEL_QUIET | NTFS_LOG_LEVEL_WARNING | - NTFS_LOG_LEVEL_ERROR | NTFS_LOG_LEVEL_PERROR | NTFS_LOG_LEVEL_CRITICAL | - NTFS_LOG_LEVEL_PROGRESS, - NTFS_LOG_FLAG_ONLYNAME, + NTFS_LOG_LEVEL_INFO | NTFS_LOG_LEVEL_QUIET | NTFS_LOG_LEVEL_WARNING | + NTFS_LOG_LEVEL_ERROR | NTFS_LOG_LEVEL_PERROR | NTFS_LOG_LEVEL_CRITICAL | + NTFS_LOG_LEVEL_PROGRESS, + NTFS_LOG_FLAG_ONLYNAME, #ifdef DEBUG - ntfs_log_handler_outerr + ntfs_log_handler_outerr #else - ntfs_log_handler_null + ntfs_log_handler_null #endif }; @@ -101,8 +101,9 @@ static struct ntfs_logging ntfs_log = { * * Returns: Log levels in a 32-bit field */ -u32 ntfs_log_get_levels(void) { - return ntfs_log.levels; +u32 ntfs_log_get_levels(void) +{ + return ntfs_log.levels; } /** @@ -114,11 +115,12 @@ u32 ntfs_log_get_levels(void) { * * Returns: Log levels that were enabled before the call */ -u32 ntfs_log_set_levels(u32 levels) { - u32 old; - old = ntfs_log.levels; - ntfs_log.levels |= levels; - return old; +u32 ntfs_log_set_levels(u32 levels) +{ + u32 old; + old = ntfs_log.levels; + ntfs_log.levels |= levels; + return old; } /** @@ -130,11 +132,12 @@ u32 ntfs_log_set_levels(u32 levels) { * * Returns: Log levels that were enabled before the call */ -u32 ntfs_log_clear_levels(u32 levels) { - u32 old; - old = ntfs_log.levels; - ntfs_log.levels &= (~levels); - return old; +u32 ntfs_log_clear_levels(u32 levels) +{ + u32 old; + old = ntfs_log.levels; + ntfs_log.levels &= (~levels); + return old; } @@ -145,8 +148,9 @@ u32 ntfs_log_clear_levels(u32 levels) { * * Returns: Logging flags in a 32-bit field */ -u32 ntfs_log_get_flags(void) { - return ntfs_log.flags; +u32 ntfs_log_get_flags(void) +{ + return ntfs_log.flags; } /** @@ -158,11 +162,12 @@ u32 ntfs_log_get_flags(void) { * * Returns: Logging flags that were enabled before the call */ -u32 ntfs_log_set_flags(u32 flags) { - u32 old; - old = ntfs_log.flags; - ntfs_log.flags |= flags; - return old; +u32 ntfs_log_set_flags(u32 flags) +{ + u32 old; + old = ntfs_log.flags; + ntfs_log.flags |= flags; + return old; } /** @@ -174,11 +179,12 @@ u32 ntfs_log_set_flags(u32 flags) { * * Returns: Logging flags that were enabled before the call */ -u32 ntfs_log_clear_flags(u32 flags) { - u32 old; - old = ntfs_log.flags; - ntfs_log.flags &= (~flags); - return old; +u32 ntfs_log_clear_flags(u32 flags) +{ + u32 old; + old = ntfs_log.flags; + ntfs_log.flags &= (~flags); + return old; } @@ -191,31 +197,32 @@ u32 ntfs_log_clear_flags(u32 flags) { * * Returns: "string" Prefix to be used */ -static FILE * ntfs_log_get_stream(u32 level) { - FILE *stream; +static FILE * ntfs_log_get_stream(u32 level) +{ + FILE *stream; - switch (level) { - case NTFS_LOG_LEVEL_INFO: - case NTFS_LOG_LEVEL_QUIET: - case NTFS_LOG_LEVEL_PROGRESS: - case NTFS_LOG_LEVEL_VERBOSE: - stream = stdout; - break; + switch (level) { + case NTFS_LOG_LEVEL_INFO: + case NTFS_LOG_LEVEL_QUIET: + case NTFS_LOG_LEVEL_PROGRESS: + case NTFS_LOG_LEVEL_VERBOSE: + stream = stdout; + break; - case NTFS_LOG_LEVEL_DEBUG: - case NTFS_LOG_LEVEL_TRACE: - case NTFS_LOG_LEVEL_ENTER: - case NTFS_LOG_LEVEL_LEAVE: - case NTFS_LOG_LEVEL_WARNING: - case NTFS_LOG_LEVEL_ERROR: - case NTFS_LOG_LEVEL_CRITICAL: - case NTFS_LOG_LEVEL_PERROR: - default: - stream = stderr; - break; - } + case NTFS_LOG_LEVEL_DEBUG: + case NTFS_LOG_LEVEL_TRACE: + case NTFS_LOG_LEVEL_ENTER: + case NTFS_LOG_LEVEL_LEAVE: + case NTFS_LOG_LEVEL_WARNING: + case NTFS_LOG_LEVEL_ERROR: + case NTFS_LOG_LEVEL_CRITICAL: + case NTFS_LOG_LEVEL_PERROR: + default: + stream = stderr; + break; + } - return stream; + return stream; } /** @@ -226,46 +233,47 @@ static FILE * ntfs_log_get_stream(u32 level) { * * Returns: "string" Prefix to be used */ -static const char * ntfs_log_get_prefix(u32 level) { - const char *prefix; +static const char * ntfs_log_get_prefix(u32 level) +{ + const char *prefix; - switch (level) { - case NTFS_LOG_LEVEL_DEBUG: - prefix = "DEBUG: "; - break; - case NTFS_LOG_LEVEL_TRACE: - prefix = "TRACE: "; - break; - case NTFS_LOG_LEVEL_QUIET: - prefix = "QUIET: "; - break; - case NTFS_LOG_LEVEL_INFO: - prefix = "INFO: "; - break; - case NTFS_LOG_LEVEL_VERBOSE: - prefix = "VERBOSE: "; - break; - case NTFS_LOG_LEVEL_PROGRESS: - prefix = "PROGRESS: "; - break; - case NTFS_LOG_LEVEL_WARNING: - prefix = "WARNING: "; - break; - case NTFS_LOG_LEVEL_ERROR: - prefix = "ERROR: "; - break; - case NTFS_LOG_LEVEL_PERROR: - prefix = "ERROR: "; - break; - case NTFS_LOG_LEVEL_CRITICAL: - prefix = "CRITICAL: "; - break; - default: - prefix = ""; - break; - } + switch (level) { + case NTFS_LOG_LEVEL_DEBUG: + prefix = "DEBUG: "; + break; + case NTFS_LOG_LEVEL_TRACE: + prefix = "TRACE: "; + break; + case NTFS_LOG_LEVEL_QUIET: + prefix = "QUIET: "; + break; + case NTFS_LOG_LEVEL_INFO: + prefix = "INFO: "; + break; + case NTFS_LOG_LEVEL_VERBOSE: + prefix = "VERBOSE: "; + break; + case NTFS_LOG_LEVEL_PROGRESS: + prefix = "PROGRESS: "; + break; + case NTFS_LOG_LEVEL_WARNING: + prefix = "WARNING: "; + break; + case NTFS_LOG_LEVEL_ERROR: + prefix = "ERROR: "; + break; + case NTFS_LOG_LEVEL_PERROR: + prefix = "ERROR: "; + break; + case NTFS_LOG_LEVEL_CRITICAL: + prefix = "CRITICAL: "; + break; + default: + prefix = ""; + break; + } - return prefix; + return prefix; } @@ -276,15 +284,16 @@ static const char * ntfs_log_get_prefix(u32 level) { * This alternate handler will be called for all future logging requests. * If no @handler is specified, logging will revert to the default handler. */ -void ntfs_log_set_handler(ntfs_log_handler *handler) { - if (handler) { - ntfs_log.handler = handler; +void ntfs_log_set_handler(ntfs_log_handler *handler) +{ + if (handler) { + ntfs_log.handler = handler; #ifdef HAVE_SYSLOG_H - if (handler == ntfs_log_handler_syslog) - openlog("ntfs-3g", LOG_PID, LOG_USER); + if (handler == ntfs_log_handler_syslog) + openlog("ntfs-3g", LOG_PID, LOG_USER); #endif - } else - ntfs_log.handler = ntfs_log_handler_null; + } else + ntfs_log.handler = ntfs_log_handler_null; } /** @@ -305,21 +314,22 @@ void ntfs_log_set_handler(ntfs_log_handler *handler) { * num Number of output characters */ int ntfs_log_redirect(const char *function, const char *file, - int line, u32 level, void *data, const char *format, ...) { - int olderr = errno; - int ret; - va_list args; + int line, u32 level, void *data, const char *format, ...) +{ + int olderr = errno; + int ret; + va_list args; - if (!(ntfs_log.levels & level)) /* Don't log this message */ - return 0; + if (!(ntfs_log.levels & level)) /* Don't log this message */ + return 0; - va_start(args, format); - errno = olderr; - ret = ntfs_log.handler(function, file, line, level, data, format, args); - va_end(args); + va_start(args, format); + errno = olderr; + ret = ntfs_log.handler(function, file, line, level, data, format, args); + va_end(args); - errno = olderr; - return ret; + errno = olderr; + return ret; } @@ -346,34 +356,35 @@ int ntfs_log_redirect(const char *function, const char *file, #define LOG_LINE_LEN 512 int ntfs_log_handler_syslog(const char *function __attribute__((unused)), - const char *file __attribute__((unused)), - int line __attribute__((unused)), u32 level, - void *data __attribute__((unused)), - const char *format, va_list args) { - char logbuf[LOG_LINE_LEN]; - int ret, olderr = errno; + const char *file __attribute__((unused)), + int line __attribute__((unused)), u32 level, + void *data __attribute__((unused)), + const char *format, va_list args) +{ + char logbuf[LOG_LINE_LEN]; + int ret, olderr = errno; #ifndef DEBUG - if ((level & NTFS_LOG_LEVEL_PERROR) && errno == ENOSPC) - return 1; -#endif - ret = vsnprintf(logbuf, LOG_LINE_LEN, format, args); - if (ret < 0) { - vsyslog(LOG_NOTICE, format, args); - ret = 1; - goto out; - } - - if ((LOG_LINE_LEN > ret + 3) && (level & NTFS_LOG_LEVEL_PERROR)) { - strncat(logbuf, ": ", LOG_LINE_LEN - ret - 1); - strncat(logbuf, strerror(olderr), LOG_LINE_LEN - (ret + 3)); - ret = strlen(logbuf); - } - - syslog(LOG_NOTICE, "%s", logbuf); + if ((level & NTFS_LOG_LEVEL_PERROR) && errno == ENOSPC) + return 1; +#endif + ret = vsnprintf(logbuf, LOG_LINE_LEN, format, args); + if (ret < 0) { + vsyslog(LOG_NOTICE, format, args); + ret = 1; + goto out; + } + + if ((LOG_LINE_LEN > ret + 3) && (level & NTFS_LOG_LEVEL_PERROR)) { + strncat(logbuf, ": ", LOG_LINE_LEN - ret - 1); + strncat(logbuf, strerror(olderr), LOG_LINE_LEN - (ret + 3)); + ret = strlen(logbuf); + } + + syslog(LOG_NOTICE, "%s", logbuf); out: - errno = olderr; - return ret; + errno = olderr; + return ret; } #endif @@ -399,57 +410,58 @@ out: * num Number of output characters */ int ntfs_log_handler_fprintf(const char *function, const char *file, - int line, u32 level, void *data, const char *format, va_list args) { + int line, u32 level, void *data, const char *format, va_list args) +{ #ifdef DEBUG - int i; + int i; #endif - int ret = 0; - int olderr = errno; - FILE *stream; + int ret = 0; + int olderr = errno; + FILE *stream; - if (!data) /* Interpret data as a FILE stream. */ - return 0; /* If it's NULL, we can't do anything. */ - stream = (FILE*)data; + if (!data) /* Interpret data as a FILE stream. */ + return 0; /* If it's NULL, we can't do anything. */ + stream = (FILE*)data; #ifdef DEBUG - if (level == NTFS_LOG_LEVEL_LEAVE) { - if (tab) - tab--; - return 0; - } + if (level == NTFS_LOG_LEVEL_LEAVE) { + if (tab) + tab--; + return 0; + } + + for (i = 0; i < tab; i++) + ret += fprintf(stream, " "); +#endif + if ((ntfs_log.flags & NTFS_LOG_FLAG_ONLYNAME) && + (strchr(file, PATH_SEP))) /* Abbreviate the filename */ + file = strrchr(file, PATH_SEP) + 1; - for (i = 0; i < tab; i++) - ret += fprintf(stream, " "); -#endif - if ((ntfs_log.flags & NTFS_LOG_FLAG_ONLYNAME) && - (strchr(file, PATH_SEP))) /* Abbreviate the filename */ - file = strrchr(file, PATH_SEP) + 1; + if (ntfs_log.flags & NTFS_LOG_FLAG_PREFIX) /* Prefix the output */ + ret += fprintf(stream, "%s", ntfs_log_get_prefix(level)); - if (ntfs_log.flags & NTFS_LOG_FLAG_PREFIX) /* Prefix the output */ - ret += fprintf(stream, "%s", ntfs_log_get_prefix(level)); + if (ntfs_log.flags & NTFS_LOG_FLAG_FILENAME) /* Source filename */ + ret += fprintf(stream, "%s ", file); - if (ntfs_log.flags & NTFS_LOG_FLAG_FILENAME) /* Source filename */ - ret += fprintf(stream, "%s ", file); + if (ntfs_log.flags & NTFS_LOG_FLAG_LINE) /* Source line number */ + ret += fprintf(stream, "(%d) ", line); - if (ntfs_log.flags & NTFS_LOG_FLAG_LINE) /* Source line number */ - ret += fprintf(stream, "(%d) ", line); + if ((ntfs_log.flags & NTFS_LOG_FLAG_FUNCTION) || /* Source function */ + (level & NTFS_LOG_LEVEL_TRACE) || (level & NTFS_LOG_LEVEL_ENTER)) + ret += fprintf(stream, "%s(): ", function); - if ((ntfs_log.flags & NTFS_LOG_FLAG_FUNCTION) || /* Source function */ - (level & NTFS_LOG_LEVEL_TRACE) || (level & NTFS_LOG_LEVEL_ENTER)) - ret += fprintf(stream, "%s(): ", function); + ret += vfprintf(stream, format, args); - ret += vfprintf(stream, format, args); - - if (level & NTFS_LOG_LEVEL_PERROR) - ret += fprintf(stream, ": %s\n", strerror(olderr)); + if (level & NTFS_LOG_LEVEL_PERROR) + ret += fprintf(stream, ": %s\n", strerror(olderr)); #ifdef DEBUG - if (level == NTFS_LOG_LEVEL_ENTER) - tab++; -#endif - fflush(stream); - errno = olderr; - return ret; + if (level == NTFS_LOG_LEVEL_ENTER) + tab++; +#endif + fflush(stream); + errno = olderr; + return ret; } /** @@ -468,9 +480,10 @@ int ntfs_log_handler_fprintf(const char *function, const char *file, * Returns: 0 Message wasn't logged */ int ntfs_log_handler_null(const char *function __attribute__((unused)), const char *file __attribute__((unused)), - int line __attribute__((unused)), u32 level __attribute__((unused)), void *data __attribute__((unused)), - const char *format __attribute__((unused)), va_list args __attribute__((unused))) { - return 0; + int line __attribute__((unused)), u32 level __attribute__((unused)), void *data __attribute__((unused)), + const char *format __attribute__((unused)), va_list args __attribute__((unused))) +{ + return 0; } /** @@ -495,11 +508,12 @@ int ntfs_log_handler_null(const char *function __attribute__((unused)), const ch * num Number of output characters */ int ntfs_log_handler_stdout(const char *function, const char *file, - int line, u32 level, void *data, const char *format, va_list args) { - if (!data) - data = stdout; + int line, u32 level, void *data, const char *format, va_list args) +{ + if (!data) + data = stdout; - return ntfs_log_handler_fprintf(function, file, line, level, data, format, args); + return ntfs_log_handler_fprintf(function, file, line, level, data, format, args); } /** @@ -525,11 +539,12 @@ int ntfs_log_handler_stdout(const char *function, const char *file, * num Number of output characters */ int ntfs_log_handler_outerr(const char *function, const char *file, - int line, u32 level, void *data, const char *format, va_list args) { - if (!data) - data = ntfs_log_get_stream(level); + int line, u32 level, void *data, const char *format, va_list args) +{ + if (!data) + data = ntfs_log_get_stream(level); - return ntfs_log_handler_fprintf(function, file, line, level, data, format, args); + return ntfs_log_handler_fprintf(function, file, line, level, data, format, args); } /** @@ -554,11 +569,12 @@ int ntfs_log_handler_outerr(const char *function, const char *file, * num Number of output characters */ int ntfs_log_handler_stderr(const char *function, const char *file, - int line, u32 level, void *data, const char *format, va_list args) { - if (!data) - data = stderr; + int line, u32 level, void *data, const char *format, va_list args) +{ + if (!data) + data = stderr; - return ntfs_log_handler_fprintf(function, file, line, level, data, format, args); + return ntfs_log_handler_fprintf(function, file, line, level, data, format, args); } @@ -575,22 +591,23 @@ int ntfs_log_handler_stderr(const char *function, const char *file, * Returns: TRUE Option understood * FALSE Invalid log option */ -BOOL ntfs_log_parse_option(const char *option) { - if (strcmp(option, "--log-debug") == 0) { - ntfs_log_set_levels(NTFS_LOG_LEVEL_DEBUG); - return TRUE; - } else if (strcmp(option, "--log-verbose") == 0) { - ntfs_log_set_levels(NTFS_LOG_LEVEL_VERBOSE); - return TRUE; - } else if (strcmp(option, "--log-quiet") == 0) { - ntfs_log_clear_levels(NTFS_LOG_LEVEL_QUIET); - return TRUE; - } else if (strcmp(option, "--log-trace") == 0) { - ntfs_log_set_levels(NTFS_LOG_LEVEL_TRACE); - return TRUE; - } +BOOL ntfs_log_parse_option(const char *option) +{ + if (strcmp(option, "--log-debug") == 0) { + ntfs_log_set_levels(NTFS_LOG_LEVEL_DEBUG); + return TRUE; + } else if (strcmp(option, "--log-verbose") == 0) { + ntfs_log_set_levels(NTFS_LOG_LEVEL_VERBOSE); + return TRUE; + } else if (strcmp(option, "--log-quiet") == 0) { + ntfs_log_clear_levels(NTFS_LOG_LEVEL_QUIET); + return TRUE; + } else if (strcmp(option, "--log-trace") == 0) { + ntfs_log_set_levels(NTFS_LOG_LEVEL_TRACE); + return TRUE; + } - ntfs_log_debug("Unknown logging option '%s'\n", option); - return FALSE; + ntfs_log_debug("Unknown logging option '%s'\n", option); + return FALSE; } diff --git a/source/libntfs/logging.h b/source/libntfs/logging.h index 9ed873de..401f5c97 100644 --- a/source/libntfs/logging.h +++ b/source/libntfs/logging.h @@ -35,11 +35,11 @@ /* Function prototype for the logging handlers */ typedef int (ntfs_log_handler)(const char *function, const char *file, int line, - u32 level, void *data, const char *format, va_list args); + u32 level, void *data, const char *format, va_list args); /* Set the logging handler from one of the functions, below. */ -void ntfs_log_set_handler(ntfs_log_handler *handler - __attribute__((format(printf, 6, 0)))); +void ntfs_log_set_handler(ntfs_log_handler *handler + __attribute__((format(printf, 6, 0)))); /* Logging handlers */ ntfs_log_handler ntfs_log_handler_syslog __attribute__((format(printf, 6, 0))); @@ -63,8 +63,8 @@ u32 ntfs_log_get_flags(void); BOOL ntfs_log_parse_option(const char *option); int ntfs_log_redirect(const char *function, const char *file, int line, - u32 level, void *data, const char *format, ...) -__attribute__((format(printf, 6, 7))); + u32 level, void *data, const char *format, ...) + __attribute__((format(printf, 6, 7))); /* Logging levels - Determine what gets logged */ #define NTFS_LOG_LEVEL_DEBUG (1 << 0) /* x = 42 */ diff --git a/source/libntfs/mem_allocate.h b/source/libntfs/mem_allocate.h index c0183f3a..600e5a93 100644 --- a/source/libntfs/mem_allocate.h +++ b/source/libntfs/mem_allocate.h @@ -29,11 +29,11 @@ static inline void* ntfs_alloc (size_t size) { } static inline void* ntfs_align (size_t size) { -#ifdef __wii__ + #ifdef __wii__ return memalign(32, size); -#else + #else return malloc(size); -#endif + #endif } static inline void ntfs_free (void* mem) { diff --git a/source/libntfs/mft.c b/source/libntfs/mft.c index 86cb5efd..ce138d2e 100644 --- a/source/libntfs/mft.c +++ b/source/libntfs/mft.c @@ -79,40 +79,41 @@ * NOTE: @b has to be at least of size @count * vol->mft_record_size. */ int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, - const s64 count, MFT_RECORD *b) { - s64 br; - VCN m; + const s64 count, MFT_RECORD *b) +{ + s64 br; + VCN m; - ntfs_log_trace("inode %llu\n", (unsigned long long)MREF(mref)); - - if (!vol || !vol->mft_na || !b || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s: b=%p count=%lld mft=%llu", __FUNCTION__, - b, (long long)count, (unsigned long long)MREF(mref)); - return -1; - } - m = MREF(mref); - /* Refuse to read non-allocated mft records. */ - if (m + count > vol->mft_na->initialized_size >> - vol->mft_record_size_bits) { - errno = ESPIPE; - ntfs_log_perror("Trying to read non-allocated mft records " - "(%lld > %lld)", (long long)m + count, - (long long)vol->mft_na->initialized_size >> - vol->mft_record_size_bits); - return -1; - } - br = ntfs_attr_mst_pread(vol->mft_na, m << vol->mft_record_size_bits, - count, vol->mft_record_size, b); - if (br != count) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read of MFT, mft=%llu count=%lld " - "br=%lld", (long long)m, (long long)count, - (long long)br); - return -1; - } - return 0; + ntfs_log_trace("inode %llu\n", (unsigned long long)MREF(mref)); + + if (!vol || !vol->mft_na || !b || count < 0) { + errno = EINVAL; + ntfs_log_perror("%s: b=%p count=%lld mft=%llu", __FUNCTION__, + b, (long long)count, (unsigned long long)MREF(mref)); + return -1; + } + m = MREF(mref); + /* Refuse to read non-allocated mft records. */ + if (m + count > vol->mft_na->initialized_size >> + vol->mft_record_size_bits) { + errno = ESPIPE; + ntfs_log_perror("Trying to read non-allocated mft records " + "(%lld > %lld)", (long long)m + count, + (long long)vol->mft_na->initialized_size >> + vol->mft_record_size_bits); + return -1; + } + br = ntfs_attr_mst_pread(vol->mft_na, m << vol->mft_record_size_bits, + count, vol->mft_record_size, b); + if (br != count) { + if (br != -1) + errno = EIO; + ntfs_log_perror("Failed to read of MFT, mft=%llu count=%lld " + "br=%lld", (long long)m, (long long)count, + (long long)br); + return -1; + } + return 0; } /** @@ -140,104 +141,106 @@ int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, * the copied buffer to the mft mirror, too. */ int ntfs_mft_records_write(const ntfs_volume *vol, const MFT_REF mref, - const s64 count, MFT_RECORD *b) { - s64 bw; - VCN m; - void *bmirr = NULL; - int cnt = 0, res = 0; + const s64 count, MFT_RECORD *b) +{ + s64 bw; + VCN m; + void *bmirr = NULL; + int cnt = 0, res = 0; - if (!vol || !vol->mft_na || vol->mftmirr_size <= 0 || !b || count < 0) { - errno = EINVAL; - return -1; - } - m = MREF(mref); - /* Refuse to write non-allocated mft records. */ - if (m + count > vol->mft_na->initialized_size >> - vol->mft_record_size_bits) { - errno = ESPIPE; - ntfs_log_perror("Trying to write non-allocated mft records " - "(%lld > %lld)", (long long)m + count, - (long long)vol->mft_na->initialized_size >> - vol->mft_record_size_bits); - return -1; - } - if (m < vol->mftmirr_size) { - if (!vol->mftmirr_na) { - errno = EINVAL; - return -1; - } - cnt = vol->mftmirr_size - m; - if (cnt > count) - cnt = count; - bmirr = ntfs_malloc(cnt * vol->mft_record_size); - if (!bmirr) - return -1; - memcpy(bmirr, b, cnt * vol->mft_record_size); - } - bw = ntfs_attr_mst_pwrite(vol->mft_na, m << vol->mft_record_size_bits, - count, vol->mft_record_size, b); - if (bw != count) { - if (bw != -1) - errno = EIO; - if (bw >= 0) - ntfs_log_debug("Error: partial write while writing $Mft " - "record(s)!\n"); - else - ntfs_log_perror("Error writing $Mft record(s)"); - res = errno; - } - if (bmirr && bw > 0) { - if (bw < cnt) - cnt = bw; - bw = ntfs_attr_mst_pwrite(vol->mftmirr_na, - m << vol->mft_record_size_bits, cnt, - vol->mft_record_size, bmirr); - if (bw != cnt) { - if (bw != -1) - errno = EIO; - ntfs_log_debug("Error: failed to sync $MFTMirr! Run " - "chkdsk.\n"); - res = errno; - } - } - free(bmirr); - if (!res) - return res; - errno = res; - return -1; + if (!vol || !vol->mft_na || vol->mftmirr_size <= 0 || !b || count < 0) { + errno = EINVAL; + return -1; + } + m = MREF(mref); + /* Refuse to write non-allocated mft records. */ + if (m + count > vol->mft_na->initialized_size >> + vol->mft_record_size_bits) { + errno = ESPIPE; + ntfs_log_perror("Trying to write non-allocated mft records " + "(%lld > %lld)", (long long)m + count, + (long long)vol->mft_na->initialized_size >> + vol->mft_record_size_bits); + return -1; + } + if (m < vol->mftmirr_size) { + if (!vol->mftmirr_na) { + errno = EINVAL; + return -1; + } + cnt = vol->mftmirr_size - m; + if (cnt > count) + cnt = count; + bmirr = ntfs_malloc(cnt * vol->mft_record_size); + if (!bmirr) + return -1; + memcpy(bmirr, b, cnt * vol->mft_record_size); + } + bw = ntfs_attr_mst_pwrite(vol->mft_na, m << vol->mft_record_size_bits, + count, vol->mft_record_size, b); + if (bw != count) { + if (bw != -1) + errno = EIO; + if (bw >= 0) + ntfs_log_debug("Error: partial write while writing $Mft " + "record(s)!\n"); + else + ntfs_log_perror("Error writing $Mft record(s)"); + res = errno; + } + if (bmirr && bw > 0) { + if (bw < cnt) + cnt = bw; + bw = ntfs_attr_mst_pwrite(vol->mftmirr_na, + m << vol->mft_record_size_bits, cnt, + vol->mft_record_size, bmirr); + if (bw != cnt) { + if (bw != -1) + errno = EIO; + ntfs_log_debug("Error: failed to sync $MFTMirr! Run " + "chkdsk.\n"); + res = errno; + } + } + free(bmirr); + if (!res) + return res; + errno = res; + return -1; } -int ntfs_mft_record_check(const ntfs_volume *vol, const MFT_REF mref, - MFT_RECORD *m) { - ATTR_RECORD *a; - int ret = -1; - - if (!ntfs_is_file_record(m->magic)) { - ntfs_log_error("Record %llu has no FILE magic (0x%x)\n", - (unsigned long long)MREF(mref), *(le32 *)m); - goto err_out; - } - - if (le32_to_cpu(m->bytes_allocated) != vol->mft_record_size) { - ntfs_log_error("Record %llu has corrupt allocation size " - "(%u <> %u)\n", (unsigned long long)MREF(mref), - vol->mft_record_size, - le32_to_cpu(m->bytes_allocated)); - goto err_out; - } - - a = (ATTR_RECORD *)((char *)m + le16_to_cpu(m->attrs_offset)); - if (p2n(a) < p2n(m) || (char *)a > (char *)m + vol->mft_record_size) { - ntfs_log_error("Record %llu is corrupt\n", - (unsigned long long)MREF(mref)); - goto err_out; - } - - ret = 0; +int ntfs_mft_record_check(const ntfs_volume *vol, const MFT_REF mref, + MFT_RECORD *m) +{ + ATTR_RECORD *a; + int ret = -1; + + if (!ntfs_is_file_record(m->magic)) { + ntfs_log_error("Record %llu has no FILE magic (0x%x)\n", + (unsigned long long)MREF(mref), *(le32 *)m); + goto err_out; + } + + if (le32_to_cpu(m->bytes_allocated) != vol->mft_record_size) { + ntfs_log_error("Record %llu has corrupt allocation size " + "(%u <> %u)\n", (unsigned long long)MREF(mref), + vol->mft_record_size, + le32_to_cpu(m->bytes_allocated)); + goto err_out; + } + + a = (ATTR_RECORD *)((char *)m + le16_to_cpu(m->attrs_offset)); + if (p2n(a) < p2n(m) || (char *)a > (char *)m + vol->mft_record_size) { + ntfs_log_error("Record %llu is corrupt\n", + (unsigned long long)MREF(mref)); + goto err_out; + } + + ret = 0; err_out: - if (ret) - errno = EIO; - return ret; + if (ret) + errno = EIO; + return ret; } /** @@ -272,42 +275,43 @@ err_out: * check if desired. */ int ntfs_file_record_read(const ntfs_volume *vol, const MFT_REF mref, - MFT_RECORD **mrec, ATTR_RECORD **attr) { - MFT_RECORD *m; + MFT_RECORD **mrec, ATTR_RECORD **attr) +{ + MFT_RECORD *m; - if (!vol || !mrec) { - errno = EINVAL; - ntfs_log_perror("%s: mrec=%p", __FUNCTION__, mrec); - return -1; - } + if (!vol || !mrec) { + errno = EINVAL; + ntfs_log_perror("%s: mrec=%p", __FUNCTION__, mrec); + return -1; + } + + m = *mrec; + if (!m) { + m = ntfs_malloc(vol->mft_record_size); + if (!m) + return -1; + } + if (ntfs_mft_record_read(vol, mref, m)) + goto err_out; - m = *mrec; - if (!m) { - m = ntfs_malloc(vol->mft_record_size); - if (!m) - return -1; - } - if (ntfs_mft_record_read(vol, mref, m)) - goto err_out; - - if (ntfs_mft_record_check(vol, mref, m)) - goto err_out; - - if (MSEQNO(mref) && MSEQNO(mref) != le16_to_cpu(m->sequence_number)) { - ntfs_log_error("Record %llu has wrong SeqNo (%d <> %d)\n", - (unsigned long long)MREF(mref), MSEQNO(mref), - le16_to_cpu(m->sequence_number)); - errno = EIO; - goto err_out; - } - *mrec = m; - if (attr) - *attr = (ATTR_RECORD*)((char*)m + le16_to_cpu(m->attrs_offset)); - return 0; + if (ntfs_mft_record_check(vol, mref, m)) + goto err_out; + + if (MSEQNO(mref) && MSEQNO(mref) != le16_to_cpu(m->sequence_number)) { + ntfs_log_error("Record %llu has wrong SeqNo (%d <> %d)\n", + (unsigned long long)MREF(mref), MSEQNO(mref), + le16_to_cpu(m->sequence_number)); + errno = EIO; + goto err_out; + } + *mrec = m; + if (attr) + *attr = (ATTR_RECORD*)((char*)m + le16_to_cpu(m->attrs_offset)); + return 0; err_out: - if (m != *mrec) - free(m); - return -1; + if (m != *mrec) + free(m); + return -1; } /** @@ -324,69 +328,70 @@ err_out: * On success return 0 and on error return -1 with errno set to the error code. */ int ntfs_mft_record_layout(const ntfs_volume *vol, const MFT_REF mref, - MFT_RECORD *mrec) { - ATTR_RECORD *a; + MFT_RECORD *mrec) +{ + ATTR_RECORD *a; - if (!vol || !mrec) { - errno = EINVAL; - ntfs_log_perror("%s: mrec=%p", __FUNCTION__, mrec); - return -1; - } - /* Aligned to 2-byte boundary. */ - if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver)) - mrec->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1); - else { - /* Abort if mref is > 32 bits. */ - if (MREF(mref) & 0x0000ffff00000000ull) { - errno = ERANGE; - ntfs_log_perror("Mft reference exceeds 32 bits"); - return -1; - } - mrec->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1); - /* - * Set the NTFS 3.1+ specific fields while we know that the - * volume version is 3.1+. - */ - mrec->reserved = cpu_to_le16(0); - mrec->mft_record_number = cpu_to_le32(MREF(mref)); - } - mrec->magic = magic_FILE; - if (vol->mft_record_size >= NTFS_BLOCK_SIZE) - mrec->usa_count = cpu_to_le16(vol->mft_record_size / - NTFS_BLOCK_SIZE + 1); - else { - mrec->usa_count = cpu_to_le16(1); - ntfs_log_error("Sector size is bigger than MFT record size. " - "Setting usa_count to 1. If Windows chkdsk " - "reports this as corruption, please email %s " - "stating that you saw this message and that " - "the file system created was corrupt. " - "Thank you.\n", NTFS_DEV_LIST); - } - /* Set the update sequence number to 1. */ - *(u16*)((u8*)mrec + le16_to_cpu(mrec->usa_ofs)) = cpu_to_le16(1); - mrec->lsn = cpu_to_le64(0ull); - mrec->sequence_number = cpu_to_le16(1); - mrec->link_count = cpu_to_le16(0); - /* Aligned to 8-byte boundary. */ - mrec->attrs_offset = cpu_to_le16((le16_to_cpu(mrec->usa_ofs) + - (le16_to_cpu(mrec->usa_count) << 1) + 7) & ~7); - mrec->flags = cpu_to_le16(0); - /* - * Using attrs_offset plus eight bytes (for the termination attribute), - * aligned to 8-byte boundary. - */ - mrec->bytes_in_use = cpu_to_le32((le16_to_cpu(mrec->attrs_offset) + 8 + - 7) & ~7); - mrec->bytes_allocated = cpu_to_le32(vol->mft_record_size); - mrec->base_mft_record = cpu_to_le64((MFT_REF)0); - mrec->next_attr_instance = cpu_to_le16(0); - a = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset)); - a->type = AT_END; - a->length = cpu_to_le32(0); - /* Finally, clear the unused part of the mft record. */ - memset((u8*)a + 8, 0, vol->mft_record_size - ((u8*)a + 8 - (u8*)mrec)); - return 0; + if (!vol || !mrec) { + errno = EINVAL; + ntfs_log_perror("%s: mrec=%p", __FUNCTION__, mrec); + return -1; + } + /* Aligned to 2-byte boundary. */ + if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver)) + mrec->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1); + else { + /* Abort if mref is > 32 bits. */ + if (MREF(mref) & 0x0000ffff00000000ull) { + errno = ERANGE; + ntfs_log_perror("Mft reference exceeds 32 bits"); + return -1; + } + mrec->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1); + /* + * Set the NTFS 3.1+ specific fields while we know that the + * volume version is 3.1+. + */ + mrec->reserved = cpu_to_le16(0); + mrec->mft_record_number = cpu_to_le32(MREF(mref)); + } + mrec->magic = magic_FILE; + if (vol->mft_record_size >= NTFS_BLOCK_SIZE) + mrec->usa_count = cpu_to_le16(vol->mft_record_size / + NTFS_BLOCK_SIZE + 1); + else { + mrec->usa_count = cpu_to_le16(1); + ntfs_log_error("Sector size is bigger than MFT record size. " + "Setting usa_count to 1. If Windows chkdsk " + "reports this as corruption, please email %s " + "stating that you saw this message and that " + "the file system created was corrupt. " + "Thank you.\n", NTFS_DEV_LIST); + } + /* Set the update sequence number to 1. */ + *(u16*)((u8*)mrec + le16_to_cpu(mrec->usa_ofs)) = cpu_to_le16(1); + mrec->lsn = cpu_to_le64(0ull); + mrec->sequence_number = cpu_to_le16(1); + mrec->link_count = cpu_to_le16(0); + /* Aligned to 8-byte boundary. */ + mrec->attrs_offset = cpu_to_le16((le16_to_cpu(mrec->usa_ofs) + + (le16_to_cpu(mrec->usa_count) << 1) + 7) & ~7); + mrec->flags = cpu_to_le16(0); + /* + * Using attrs_offset plus eight bytes (for the termination attribute), + * aligned to 8-byte boundary. + */ + mrec->bytes_in_use = cpu_to_le32((le16_to_cpu(mrec->attrs_offset) + 8 + + 7) & ~7); + mrec->bytes_allocated = cpu_to_le32(vol->mft_record_size); + mrec->base_mft_record = cpu_to_le64((MFT_REF)0); + mrec->next_attr_instance = cpu_to_le16(0); + a = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset)); + a->type = AT_END; + a->length = cpu_to_le32(0); + /* Finally, clear the unused part of the mft record. */ + memset((u8*)a + 8, 0, vol->mft_record_size - ((u8*)a + 8 - (u8*)mrec)); + return 0; } /** @@ -399,28 +404,29 @@ int ntfs_mft_record_layout(const ntfs_volume *vol, const MFT_REF mref, * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_mft_record_format(const ntfs_volume *vol, const MFT_REF mref) { - MFT_RECORD *m; - int ret = -1; +int ntfs_mft_record_format(const ntfs_volume *vol, const MFT_REF mref) +{ + MFT_RECORD *m; + int ret = -1; - ntfs_log_enter("Entering\n"); - - m = ntfs_calloc(vol->mft_record_size); - if (!m) - goto out; - - if (ntfs_mft_record_layout(vol, mref, m)) - goto free_m; - - if (ntfs_mft_record_write(vol, mref, m)) - goto free_m; - - ret = 0; + ntfs_log_enter("Entering\n"); + + m = ntfs_calloc(vol->mft_record_size); + if (!m) + goto out; + + if (ntfs_mft_record_layout(vol, mref, m)) + goto free_m; + + if (ntfs_mft_record_write(vol, mref, m)) + goto free_m; + + ret = 0; free_m: - free(m); -out: - ntfs_log_leave("\n"); - return ret; + free(m); +out: + ntfs_log_leave("\n"); + return ret; } static const char *es = " Leaving inconsistent metadata. Run chkdsk."; @@ -433,14 +439,16 @@ static const char *es = " Leaving inconsistent metadata. Run chkdsk."; * * Returns: */ -static inline unsigned int ntfs_ffz(unsigned int word) { - return ffs(~word) - 1; +static inline unsigned int ntfs_ffz(unsigned int word) +{ + return ffs(~word) - 1; } -static int ntfs_is_mft(ntfs_inode *ni) { - if (ni && ni->mft_no == FILE_MFT) - return 1; - return 0; +static int ntfs_is_mft(ntfs_inode *ni) +{ + if (ni && ni->mft_no == FILE_MFT) + return 1; + return 0; } #ifndef PAGE_SIZE @@ -466,362 +474,365 @@ static int ntfs_is_mft(ntfs_inode *ni) { * error code. An error code of ENOSPC means that there are no free mft * records in the currently initialized mft bitmap. */ -static int ntfs_mft_bitmap_find_free_rec(ntfs_volume *vol, ntfs_inode *base_ni) { - s64 pass_end, ll, data_pos, pass_start, ofs, bit; - ntfs_attr *mftbmp_na; - u8 *buf, *byte; - unsigned int size; - u8 pass, b; - int ret = -1; +static int ntfs_mft_bitmap_find_free_rec(ntfs_volume *vol, ntfs_inode *base_ni) +{ + s64 pass_end, ll, data_pos, pass_start, ofs, bit; + ntfs_attr *mftbmp_na; + u8 *buf, *byte; + unsigned int size; + u8 pass, b; + int ret = -1; - ntfs_log_enter("Entering\n"); - - mftbmp_na = vol->mftbmp_na; - /* - * Set the end of the pass making sure we do not overflow the mft - * bitmap. - */ - size = PAGE_SIZE; - pass_end = vol->mft_na->allocated_size >> vol->mft_record_size_bits; - ll = mftbmp_na->initialized_size << 3; - if (pass_end > ll) - pass_end = ll; - pass = 1; - if (!base_ni) - data_pos = vol->mft_data_pos; - else - data_pos = base_ni->mft_no + 1; - if (data_pos < RESERVED_MFT_RECORDS) - data_pos = RESERVED_MFT_RECORDS; - if (data_pos >= pass_end) { - data_pos = RESERVED_MFT_RECORDS; - pass = 2; - /* This happens on a freshly formatted volume. */ - if (data_pos >= pass_end) { - errno = ENOSPC; - goto leave; - } - } - if (ntfs_is_mft(base_ni)) { - data_pos = 0; - pass = 2; - } - pass_start = data_pos; - buf = ntfs_malloc(PAGE_SIZE); - if (!buf) - goto leave; - - ntfs_log_debug("Starting bitmap search: pass %u, pass_start 0x%llx, " - "pass_end 0x%llx, data_pos 0x%llx.\n", pass, - (long long)pass_start, (long long)pass_end, - (long long)data_pos); + ntfs_log_enter("Entering\n"); + + mftbmp_na = vol->mftbmp_na; + /* + * Set the end of the pass making sure we do not overflow the mft + * bitmap. + */ + size = PAGE_SIZE; + pass_end = vol->mft_na->allocated_size >> vol->mft_record_size_bits; + ll = mftbmp_na->initialized_size << 3; + if (pass_end > ll) + pass_end = ll; + pass = 1; + if (!base_ni) + data_pos = vol->mft_data_pos; + else + data_pos = base_ni->mft_no + 1; + if (data_pos < RESERVED_MFT_RECORDS) + data_pos = RESERVED_MFT_RECORDS; + if (data_pos >= pass_end) { + data_pos = RESERVED_MFT_RECORDS; + pass = 2; + /* This happens on a freshly formatted volume. */ + if (data_pos >= pass_end) { + errno = ENOSPC; + goto leave; + } + } + if (ntfs_is_mft(base_ni)) { + data_pos = 0; + pass = 2; + } + pass_start = data_pos; + buf = ntfs_malloc(PAGE_SIZE); + if (!buf) + goto leave; + + ntfs_log_debug("Starting bitmap search: pass %u, pass_start 0x%llx, " + "pass_end 0x%llx, data_pos 0x%llx.\n", pass, + (long long)pass_start, (long long)pass_end, + (long long)data_pos); #ifdef DEBUG - byte = NULL; - b = 0; + byte = NULL; + b = 0; #endif - /* Loop until a free mft record is found. */ - for (; pass <= 2; size = PAGE_SIZE) { - /* Cap size to pass_end. */ - ofs = data_pos >> 3; - ll = ((pass_end + 7) >> 3) - ofs; - if (size > ll) - size = ll; - ll = ntfs_attr_pread(mftbmp_na, ofs, size, buf); - if (ll < 0) { - ntfs_log_perror("Failed to read $MFT bitmap"); - free(buf); - goto leave; - } - ntfs_log_debug("Read 0x%llx bytes.\n", (long long)ll); - /* If we read at least one byte, search @buf for a zero bit. */ - if (ll) { - size = ll << 3; - bit = data_pos & 7; - data_pos &= ~7ull; - ntfs_log_debug("Before inner for loop: size 0x%x, " - "data_pos 0x%llx, bit 0x%llx, " - "*byte 0x%hhx, b %u.\n", size, - (long long)data_pos, (long long)bit, - byte ? *byte : -1, b); - for (; bit < size && data_pos + bit < pass_end; - bit &= ~7ull, bit += 8) { - /* - * If we're extending $MFT and running out of the first - * mft record (base record) then give up searching since - * no guarantee that the found record will be accessible. - */ - if (ntfs_is_mft(base_ni) && bit > 400) - goto out; - - byte = buf + (bit >> 3); - if (*byte == 0xff) - continue; - - /* Note: ffz() result must be zero based. */ - b = ntfs_ffz((unsigned long)*byte); - if (b < 8 && b >= (bit & 7)) { - free(buf); - ret = data_pos + (bit & ~7ull) + b; - goto leave; - } - } - ntfs_log_debug("After inner for loop: size 0x%x, " - "data_pos 0x%llx, bit 0x%llx, " - "*byte 0x%hhx, b %u.\n", size, - (long long)data_pos, (long long)bit, - byte ? *byte : -1, b); - data_pos += size; - /* - * If the end of the pass has not been reached yet, - * continue searching the mft bitmap for a zero bit. - */ - if (data_pos < pass_end) - continue; - } - /* Do the next pass. */ - pass++; - if (pass == 2) { - /* - * Starting the second pass, in which we scan the first - * part of the zone which we omitted earlier. - */ - pass_end = pass_start; - data_pos = pass_start = RESERVED_MFT_RECORDS; - ntfs_log_debug("pass %i, pass_start 0x%llx, pass_end " - "0x%llx.\n", pass, (long long)pass_start, - (long long)pass_end); - if (data_pos >= pass_end) - break; - } - } - /* No free mft records in currently initialized mft bitmap. */ -out: - free(buf); - errno = ENOSPC; + /* Loop until a free mft record is found. */ + for (; pass <= 2; size = PAGE_SIZE) { + /* Cap size to pass_end. */ + ofs = data_pos >> 3; + ll = ((pass_end + 7) >> 3) - ofs; + if (size > ll) + size = ll; + ll = ntfs_attr_pread(mftbmp_na, ofs, size, buf); + if (ll < 0) { + ntfs_log_perror("Failed to read $MFT bitmap"); + free(buf); + goto leave; + } + ntfs_log_debug("Read 0x%llx bytes.\n", (long long)ll); + /* If we read at least one byte, search @buf for a zero bit. */ + if (ll) { + size = ll << 3; + bit = data_pos & 7; + data_pos &= ~7ull; + ntfs_log_debug("Before inner for loop: size 0x%x, " + "data_pos 0x%llx, bit 0x%llx, " + "*byte 0x%hhx, b %u.\n", size, + (long long)data_pos, (long long)bit, + byte ? *byte : -1, b); + for (; bit < size && data_pos + bit < pass_end; + bit &= ~7ull, bit += 8) { + /* + * If we're extending $MFT and running out of the first + * mft record (base record) then give up searching since + * no guarantee that the found record will be accessible. + */ + if (ntfs_is_mft(base_ni) && bit > 400) + goto out; + + byte = buf + (bit >> 3); + if (*byte == 0xff) + continue; + + /* Note: ffz() result must be zero based. */ + b = ntfs_ffz((unsigned long)*byte); + if (b < 8 && b >= (bit & 7)) { + free(buf); + ret = data_pos + (bit & ~7ull) + b; + goto leave; + } + } + ntfs_log_debug("After inner for loop: size 0x%x, " + "data_pos 0x%llx, bit 0x%llx, " + "*byte 0x%hhx, b %u.\n", size, + (long long)data_pos, (long long)bit, + byte ? *byte : -1, b); + data_pos += size; + /* + * If the end of the pass has not been reached yet, + * continue searching the mft bitmap for a zero bit. + */ + if (data_pos < pass_end) + continue; + } + /* Do the next pass. */ + pass++; + if (pass == 2) { + /* + * Starting the second pass, in which we scan the first + * part of the zone which we omitted earlier. + */ + pass_end = pass_start; + data_pos = pass_start = RESERVED_MFT_RECORDS; + ntfs_log_debug("pass %i, pass_start 0x%llx, pass_end " + "0x%llx.\n", pass, (long long)pass_start, + (long long)pass_end); + if (data_pos >= pass_end) + break; + } + } + /* No free mft records in currently initialized mft bitmap. */ +out: + free(buf); + errno = ENOSPC; leave: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } -static int ntfs_mft_attr_extend(ntfs_attr *na) { - int ret = STATUS_ERROR; - ntfs_log_enter("Entering\n"); +static int ntfs_mft_attr_extend(ntfs_attr *na) +{ + int ret = STATUS_ERROR; + ntfs_log_enter("Entering\n"); - if (!NInoAttrList(na->ni)) { - if (ntfs_inode_add_attrlist(na->ni)) { - ntfs_log_perror("%s: Can not add attrlist #3", __FUNCTION__); - goto out; - } - /* We can't sync the $MFT inode since its runlist is bogus. */ - ret = STATUS_KEEP_SEARCHING; - goto out; - } + if (!NInoAttrList(na->ni)) { + if (ntfs_inode_add_attrlist(na->ni)) { + ntfs_log_perror("%s: Can not add attrlist #3", __FUNCTION__); + goto out; + } + /* We can't sync the $MFT inode since its runlist is bogus. */ + ret = STATUS_KEEP_SEARCHING; + goto out; + } - if (ntfs_attr_update_mapping_pairs(na, 0)) { - ntfs_log_perror("%s: MP update failed", __FUNCTION__); - goto out; - } - - ret = STATUS_OK; -out: - ntfs_log_leave("\n"); - return ret; + if (ntfs_attr_update_mapping_pairs(na, 0)) { + ntfs_log_perror("%s: MP update failed", __FUNCTION__); + goto out; + } + + ret = STATUS_OK; +out: + ntfs_log_leave("\n"); + return ret; } /** * ntfs_mft_bitmap_extend_allocation_i - see ntfs_mft_bitmap_extend_allocation */ -static int ntfs_mft_bitmap_extend_allocation_i(ntfs_volume *vol) { - LCN lcn; - s64 ll = 0; /* silence compiler warning */ - ntfs_attr *mftbmp_na; - runlist_element *rl, *rl2 = NULL; /* silence compiler warning */ - ntfs_attr_search_ctx *ctx; - MFT_RECORD *m = NULL; /* silence compiler warning */ - ATTR_RECORD *a = NULL; /* silence compiler warning */ - int err, mp_size; - int ret = STATUS_ERROR; - u32 old_alen = 0; /* silence compiler warning */ - BOOL mp_rebuilt = FALSE; - BOOL update_mp = FALSE; +static int ntfs_mft_bitmap_extend_allocation_i(ntfs_volume *vol) +{ + LCN lcn; + s64 ll = 0; /* silence compiler warning */ + ntfs_attr *mftbmp_na; + runlist_element *rl, *rl2 = NULL; /* silence compiler warning */ + ntfs_attr_search_ctx *ctx; + MFT_RECORD *m = NULL; /* silence compiler warning */ + ATTR_RECORD *a = NULL; /* silence compiler warning */ + int err, mp_size; + int ret = STATUS_ERROR; + u32 old_alen = 0; /* silence compiler warning */ + BOOL mp_rebuilt = FALSE; + BOOL update_mp = FALSE; - mftbmp_na = vol->mftbmp_na; - /* - * Determine the last lcn of the mft bitmap. The allocated size of the - * mft bitmap cannot be zero so we are ok to do this. - */ - rl = ntfs_attr_find_vcn(mftbmp_na, (mftbmp_na->allocated_size - 1) >> - vol->cluster_size_bits); - if (!rl || !rl->length || rl->lcn < 0) { - ntfs_log_error("Failed to determine last allocated " - "cluster of mft bitmap attribute.\n"); - if (rl) - errno = EIO; - return STATUS_ERROR; - } - lcn = rl->lcn + rl->length; + mftbmp_na = vol->mftbmp_na; + /* + * Determine the last lcn of the mft bitmap. The allocated size of the + * mft bitmap cannot be zero so we are ok to do this. + */ + rl = ntfs_attr_find_vcn(mftbmp_na, (mftbmp_na->allocated_size - 1) >> + vol->cluster_size_bits); + if (!rl || !rl->length || rl->lcn < 0) { + ntfs_log_error("Failed to determine last allocated " + "cluster of mft bitmap attribute.\n"); + if (rl) + errno = EIO; + return STATUS_ERROR; + } + lcn = rl->lcn + rl->length; + + rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE); + if (!rl2) { + ntfs_log_error("Failed to allocate a cluster for " + "the mft bitmap.\n"); + return STATUS_ERROR; + } + rl = ntfs_runlists_merge(mftbmp_na->rl, rl2); + if (!rl) { + err = errno; + ntfs_log_error("Failed to merge runlists for mft " + "bitmap.\n"); + if (ntfs_cluster_free_from_rl(vol, rl2)) + ntfs_log_error("Failed to deallocate " + "cluster.%s\n", es); + free(rl2); + errno = err; + return STATUS_ERROR; + } + mftbmp_na->rl = rl; + ntfs_log_debug("Adding one run to mft bitmap.\n"); + /* Find the last run in the new runlist. */ + for (; rl[1].length; rl++) + ; + /* + * Update the attribute record as well. Note: @rl is the last + * (non-terminator) runlist element of mft bitmap. + */ + ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL); + if (!ctx) + goto undo_alloc; - rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE); - if (!rl2) { - ntfs_log_error("Failed to allocate a cluster for " - "the mft bitmap.\n"); - return STATUS_ERROR; - } - rl = ntfs_runlists_merge(mftbmp_na->rl, rl2); - if (!rl) { - err = errno; - ntfs_log_error("Failed to merge runlists for mft " - "bitmap.\n"); - if (ntfs_cluster_free_from_rl(vol, rl2)) - ntfs_log_error("Failed to deallocate " - "cluster.%s\n", es); - free(rl2); - errno = err; - return STATUS_ERROR; - } - mftbmp_na->rl = rl; - ntfs_log_debug("Adding one run to mft bitmap.\n"); - /* Find the last run in the new runlist. */ - for (; rl[1].length; rl++) - ; - /* - * Update the attribute record as well. Note: @rl is the last - * (non-terminator) runlist element of mft bitmap. - */ - ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL); - if (!ctx) - goto undo_alloc; - - if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, - mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx)) { - ntfs_log_error("Failed to find last attribute extent of " - "mft bitmap attribute.\n"); - goto undo_alloc; - } - m = ctx->mrec; - a = ctx->attr; - ll = sle64_to_cpu(a->lowest_vcn); - rl2 = ntfs_attr_find_vcn(mftbmp_na, ll); - if (!rl2 || !rl2->length) { - ntfs_log_error("Failed to determine previous last " - "allocated cluster of mft bitmap attribute.\n"); - if (rl2) - errno = EIO; - goto undo_alloc; - } - /* Get the size for the new mapping pairs array for this extent. */ - mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, INT_MAX); - if (mp_size <= 0) { - ntfs_log_error("Get size for mapping pairs failed for " - "mft bitmap attribute extent.\n"); - goto undo_alloc; - } - /* Expand the attribute record if necessary. */ - old_alen = le32_to_cpu(a->length); - if (ntfs_attr_record_resize(m, a, mp_size + - le16_to_cpu(a->mapping_pairs_offset))) { - ntfs_log_info("extending $MFT bitmap\n"); - ret = ntfs_mft_attr_extend(vol->mftbmp_na); - if (ret == STATUS_OK) - goto ok; - if (ret == STATUS_ERROR) { - ntfs_log_perror("%s: ntfs_mft_attr_extend failed", __FUNCTION__); - update_mp = TRUE; - } - goto undo_alloc; - } - mp_rebuilt = TRUE; - /* Generate the mapping pairs array directly into the attr record. */ - if (ntfs_mapping_pairs_build(vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), mp_size, rl2, ll, - NULL)) { - ntfs_log_error("Failed to build mapping pairs array for " - "mft bitmap attribute.\n"); - errno = EIO; - goto undo_alloc; - } - /* Update the highest_vcn. */ - a->highest_vcn = cpu_to_sle64(rl[1].vcn - 1); - /* - * We now have extended the mft bitmap allocated_size by one cluster. - * Reflect this in the ntfs_attr structure and the attribute record. - */ - if (a->lowest_vcn) { - /* - * We are not in the first attribute extent, switch to it, but - * first ensure the changes will make it to disk later. - */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, - mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) { - ntfs_log_error("Failed to find first attribute " - "extent of mft bitmap attribute.\n"); - goto restore_undo_alloc; - } - a = ctx->attr; - } + if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx)) { + ntfs_log_error("Failed to find last attribute extent of " + "mft bitmap attribute.\n"); + goto undo_alloc; + } + m = ctx->mrec; + a = ctx->attr; + ll = sle64_to_cpu(a->lowest_vcn); + rl2 = ntfs_attr_find_vcn(mftbmp_na, ll); + if (!rl2 || !rl2->length) { + ntfs_log_error("Failed to determine previous last " + "allocated cluster of mft bitmap attribute.\n"); + if (rl2) + errno = EIO; + goto undo_alloc; + } + /* Get the size for the new mapping pairs array for this extent. */ + mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, INT_MAX); + if (mp_size <= 0) { + ntfs_log_error("Get size for mapping pairs failed for " + "mft bitmap attribute extent.\n"); + goto undo_alloc; + } + /* Expand the attribute record if necessary. */ + old_alen = le32_to_cpu(a->length); + if (ntfs_attr_record_resize(m, a, mp_size + + le16_to_cpu(a->mapping_pairs_offset))) { + ntfs_log_info("extending $MFT bitmap\n"); + ret = ntfs_mft_attr_extend(vol->mftbmp_na); + if (ret == STATUS_OK) + goto ok; + if (ret == STATUS_ERROR) { + ntfs_log_perror("%s: ntfs_mft_attr_extend failed", __FUNCTION__); + update_mp = TRUE; + } + goto undo_alloc; + } + mp_rebuilt = TRUE; + /* Generate the mapping pairs array directly into the attr record. */ + if (ntfs_mapping_pairs_build(vol, (u8*)a + + le16_to_cpu(a->mapping_pairs_offset), mp_size, rl2, ll, + NULL)) { + ntfs_log_error("Failed to build mapping pairs array for " + "mft bitmap attribute.\n"); + errno = EIO; + goto undo_alloc; + } + /* Update the highest_vcn. */ + a->highest_vcn = cpu_to_sle64(rl[1].vcn - 1); + /* + * We now have extended the mft bitmap allocated_size by one cluster. + * Reflect this in the ntfs_attr structure and the attribute record. + */ + if (a->lowest_vcn) { + /* + * We are not in the first attribute extent, switch to it, but + * first ensure the changes will make it to disk later. + */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) { + ntfs_log_error("Failed to find first attribute " + "extent of mft bitmap attribute.\n"); + goto restore_undo_alloc; + } + a = ctx->attr; + } ok: - mftbmp_na->allocated_size += vol->cluster_size; - a->allocated_size = cpu_to_sle64(mftbmp_na->allocated_size); - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - return STATUS_OK; + mftbmp_na->allocated_size += vol->cluster_size; + a->allocated_size = cpu_to_sle64(mftbmp_na->allocated_size); + /* Ensure the changes make it to disk. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + return STATUS_OK; restore_undo_alloc: - err = errno; - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, - mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx)) { - ntfs_log_error("Failed to find last attribute extent of " - "mft bitmap attribute.%s\n", es); - ntfs_attr_put_search_ctx(ctx); - mftbmp_na->allocated_size += vol->cluster_size; - /* - * The only thing that is now wrong is ->allocated_size of the - * base attribute extent which chkdsk should be able to fix. - */ - errno = err; - return STATUS_ERROR; - } - m = ctx->mrec; - a = ctx->attr; - a->highest_vcn = cpu_to_sle64(rl[1].vcn - 2); - errno = err; + err = errno; + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx)) { + ntfs_log_error("Failed to find last attribute extent of " + "mft bitmap attribute.%s\n", es); + ntfs_attr_put_search_ctx(ctx); + mftbmp_na->allocated_size += vol->cluster_size; + /* + * The only thing that is now wrong is ->allocated_size of the + * base attribute extent which chkdsk should be able to fix. + */ + errno = err; + return STATUS_ERROR; + } + m = ctx->mrec; + a = ctx->attr; + a->highest_vcn = cpu_to_sle64(rl[1].vcn - 2); + errno = err; undo_alloc: - err = errno; + err = errno; - /* Remove the last run from the runlist. */ - lcn = rl->lcn; - rl->lcn = rl[1].lcn; - rl->length = 0; - - /* FIXME: use an ntfs_cluster_free_* function */ - if (ntfs_bitmap_clear_bit(vol->lcnbmp_na, lcn)) - ntfs_log_error("Failed to free cluster.%s\n", es); - else - vol->free_clusters++; - if (mp_rebuilt) { - if (ntfs_mapping_pairs_build(vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), - old_alen - le16_to_cpu(a->mapping_pairs_offset), - rl2, ll, NULL)) - ntfs_log_error("Failed to restore mapping " - "pairs array.%s\n", es); - if (ntfs_attr_record_resize(m, a, old_alen)) - ntfs_log_error("Failed to restore attribute " - "record.%s\n", es); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - } - if (update_mp) { - if (ntfs_attr_update_mapping_pairs(vol->mftbmp_na, 0)) - ntfs_log_perror("%s: MP update failed", __FUNCTION__); - } - if (ctx) - ntfs_attr_put_search_ctx(ctx); - errno = err; - return ret; + /* Remove the last run from the runlist. */ + lcn = rl->lcn; + rl->lcn = rl[1].lcn; + rl->length = 0; + + /* FIXME: use an ntfs_cluster_free_* function */ + if (ntfs_bitmap_clear_bit(vol->lcnbmp_na, lcn)) + ntfs_log_error("Failed to free cluster.%s\n", es); + else + vol->free_clusters++; + if (mp_rebuilt) { + if (ntfs_mapping_pairs_build(vol, (u8*)a + + le16_to_cpu(a->mapping_pairs_offset), + old_alen - le16_to_cpu(a->mapping_pairs_offset), + rl2, ll, NULL)) + ntfs_log_error("Failed to restore mapping " + "pairs array.%s\n", es); + if (ntfs_attr_record_resize(m, a, old_alen)) + ntfs_log_error("Failed to restore attribute " + "record.%s\n", es); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + } + if (update_mp) { + if (ntfs_attr_update_mapping_pairs(vol->mftbmp_na, 0)) + ntfs_log_perror("%s: MP update failed", __FUNCTION__); + } + if (ctx) + ntfs_attr_put_search_ctx(ctx); + errno = err; + return ret; } /** @@ -835,13 +846,14 @@ undo_alloc: * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_bitmap_extend_allocation(ntfs_volume *vol) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_mft_bitmap_extend_allocation_i(vol); - ntfs_log_leave("\n"); - return ret; +static int ntfs_mft_bitmap_extend_allocation(ntfs_volume *vol) +{ + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_mft_bitmap_extend_allocation_i(vol); + ntfs_log_leave("\n"); + return ret; } /** * ntfs_mft_bitmap_extend_initialized - extend mft bitmap initialized data @@ -855,85 +867,86 @@ static int ntfs_mft_bitmap_extend_allocation(ntfs_volume *vol) { * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_bitmap_extend_initialized(ntfs_volume *vol) { - s64 old_data_size, old_initialized_size, ll; - ntfs_attr *mftbmp_na; - ntfs_attr_search_ctx *ctx; - ATTR_RECORD *a; - int err; - int ret = -1; +static int ntfs_mft_bitmap_extend_initialized(ntfs_volume *vol) +{ + s64 old_data_size, old_initialized_size, ll; + ntfs_attr *mftbmp_na; + ntfs_attr_search_ctx *ctx; + ATTR_RECORD *a; + int err; + int ret = -1; - ntfs_log_enter("Entering\n"); + ntfs_log_enter("Entering\n"); + + mftbmp_na = vol->mftbmp_na; + ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL); + if (!ctx) + goto out; - mftbmp_na = vol->mftbmp_na; - ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL); - if (!ctx) - goto out; + if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) { + ntfs_log_error("Failed to find first attribute extent of " + "mft bitmap attribute.\n"); + err = errno; + goto put_err_out; + } + a = ctx->attr; + old_data_size = mftbmp_na->data_size; + old_initialized_size = mftbmp_na->initialized_size; + mftbmp_na->initialized_size += 8; + a->initialized_size = cpu_to_sle64(mftbmp_na->initialized_size); + if (mftbmp_na->initialized_size > mftbmp_na->data_size) { + mftbmp_na->data_size = mftbmp_na->initialized_size; + a->data_size = cpu_to_sle64(mftbmp_na->data_size); + } + /* Ensure the changes make it to disk. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + /* Initialize the mft bitmap attribute value with zeroes. */ + ll = 0; + ll = ntfs_attr_pwrite(mftbmp_na, old_initialized_size, 8, &ll); + if (ll == 8) { + ntfs_log_debug("Wrote eight initialized bytes to mft bitmap.\n"); + vol->free_mft_records += (8 * 8); + ret = 0; + goto out; + } + ntfs_log_error("Failed to write to mft bitmap.\n"); + err = errno; + if (ll >= 0) + err = EIO; + /* Try to recover from the error. */ + ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL); + if (!ctx) + goto err_out; - if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, - mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) { - ntfs_log_error("Failed to find first attribute extent of " - "mft bitmap attribute.\n"); - err = errno; - goto put_err_out; - } - a = ctx->attr; - old_data_size = mftbmp_na->data_size; - old_initialized_size = mftbmp_na->initialized_size; - mftbmp_na->initialized_size += 8; - a->initialized_size = cpu_to_sle64(mftbmp_na->initialized_size); - if (mftbmp_na->initialized_size > mftbmp_na->data_size) { - mftbmp_na->data_size = mftbmp_na->initialized_size; - a->data_size = cpu_to_sle64(mftbmp_na->data_size); - } - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - /* Initialize the mft bitmap attribute value with zeroes. */ - ll = 0; - ll = ntfs_attr_pwrite(mftbmp_na, old_initialized_size, 8, &ll); - if (ll == 8) { - ntfs_log_debug("Wrote eight initialized bytes to mft bitmap.\n"); - vol->free_mft_records += (8 * 8); - ret = 0; - goto out; - } - ntfs_log_error("Failed to write to mft bitmap.\n"); - err = errno; - if (ll >= 0) - err = EIO; - /* Try to recover from the error. */ - ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL); - if (!ctx) - goto err_out; - - if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, - mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) { - ntfs_log_error("Failed to find first attribute extent of " - "mft bitmap attribute.%s\n", es); + if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, 0, NULL, 0, ctx)) { + ntfs_log_error("Failed to find first attribute extent of " + "mft bitmap attribute.%s\n", es); put_err_out: - ntfs_attr_put_search_ctx(ctx); - goto err_out; - } - a = ctx->attr; - mftbmp_na->initialized_size = old_initialized_size; - a->initialized_size = cpu_to_sle64(old_initialized_size); - if (mftbmp_na->data_size != old_data_size) { - mftbmp_na->data_size = old_data_size; - a->data_size = cpu_to_sle64(old_data_size); - } - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - ntfs_log_debug("Restored status of mftbmp: allocated_size 0x%llx, " - "data_size 0x%llx, initialized_size 0x%llx.\n", - (long long)mftbmp_na->allocated_size, - (long long)mftbmp_na->data_size, - (long long)mftbmp_na->initialized_size); + ntfs_attr_put_search_ctx(ctx); + goto err_out; + } + a = ctx->attr; + mftbmp_na->initialized_size = old_initialized_size; + a->initialized_size = cpu_to_sle64(old_initialized_size); + if (mftbmp_na->data_size != old_data_size) { + mftbmp_na->data_size = old_data_size; + a->data_size = cpu_to_sle64(old_data_size); + } + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + ntfs_log_debug("Restored status of mftbmp: allocated_size 0x%llx, " + "data_size 0x%llx, initialized_size 0x%llx.\n", + (long long)mftbmp_na->allocated_size, + (long long)mftbmp_na->data_size, + (long long)mftbmp_na->initialized_size); err_out: - errno = err; + errno = err; out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; } /** @@ -949,540 +962,544 @@ out: * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_data_extend_allocation(ntfs_volume *vol) { - LCN lcn; - VCN old_last_vcn; - s64 min_nr, nr, ll = 0; /* silence compiler warning */ - ntfs_attr *mft_na; - runlist_element *rl, *rl2; - ntfs_attr_search_ctx *ctx; - MFT_RECORD *m = NULL; /* silence compiler warning */ - ATTR_RECORD *a = NULL; /* silence compiler warning */ - int err, mp_size; - int ret = STATUS_ERROR; - u32 old_alen = 0; /* silence compiler warning */ - BOOL mp_rebuilt = FALSE; - BOOL update_mp = FALSE; +static int ntfs_mft_data_extend_allocation(ntfs_volume *vol) +{ + LCN lcn; + VCN old_last_vcn; + s64 min_nr, nr, ll = 0; /* silence compiler warning */ + ntfs_attr *mft_na; + runlist_element *rl, *rl2; + ntfs_attr_search_ctx *ctx; + MFT_RECORD *m = NULL; /* silence compiler warning */ + ATTR_RECORD *a = NULL; /* silence compiler warning */ + int err, mp_size; + int ret = STATUS_ERROR; + u32 old_alen = 0; /* silence compiler warning */ + BOOL mp_rebuilt = FALSE; + BOOL update_mp = FALSE; - ntfs_log_enter("Extending mft data allocation.\n"); + ntfs_log_enter("Extending mft data allocation.\n"); + + mft_na = vol->mft_na; + /* + * Determine the preferred allocation location, i.e. the last lcn of + * the mft data attribute. The allocated size of the mft data + * attribute cannot be zero so we are ok to do this. + */ + rl = ntfs_attr_find_vcn(mft_na, + (mft_na->allocated_size - 1) >> vol->cluster_size_bits); + + if (!rl || !rl->length || rl->lcn < 0) { + ntfs_log_error("Failed to determine last allocated " + "cluster of mft data attribute.\n"); + if (rl) + errno = EIO; + goto out; + } + + lcn = rl->lcn + rl->length; + ntfs_log_debug("Last lcn of mft data attribute is 0x%llx.\n", (long long)lcn); + /* Minimum allocation is one mft record worth of clusters. */ + min_nr = vol->mft_record_size >> vol->cluster_size_bits; + if (!min_nr) + min_nr = 1; + /* Want to allocate 16 mft records worth of clusters. */ + nr = vol->mft_record_size << 4 >> vol->cluster_size_bits; + if (!nr) + nr = min_nr; + + old_last_vcn = rl[1].vcn; + do { + rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE); + if (rl2) + break; + if (errno != ENOSPC || nr == min_nr) { + ntfs_log_perror("Failed to allocate (%lld) clusters " + "for $MFT", (long long)nr); + goto out; + } + /* + * There is not enough space to do the allocation, but there + * might be enough space to do a minimal allocation so try that + * before failing. + */ + nr = min_nr; + ntfs_log_debug("Retrying mft data allocation with minimal cluster " + "count %lli.\n", (long long)nr); + } while (1); + + ntfs_log_debug("Allocated %lld clusters.\n", (long long)nr); + + rl = ntfs_runlists_merge(mft_na->rl, rl2); + if (!rl) { + err = errno; + ntfs_log_error("Failed to merge runlists for mft data " + "attribute.\n"); + if (ntfs_cluster_free_from_rl(vol, rl2)) + ntfs_log_error("Failed to deallocate clusters " + "from the mft data attribute.%s\n", es); + free(rl2); + errno = err; + goto out; + } + mft_na->rl = rl; + + /* Find the last run in the new runlist. */ + for (; rl[1].length; rl++) + ; + /* Update the attribute record as well. */ + ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL); + if (!ctx) + goto undo_alloc; - mft_na = vol->mft_na; - /* - * Determine the preferred allocation location, i.e. the last lcn of - * the mft data attribute. The allocated size of the mft data - * attribute cannot be zero so we are ok to do this. - */ - rl = ntfs_attr_find_vcn(mft_na, - (mft_na->allocated_size - 1) >> vol->cluster_size_bits); - - if (!rl || !rl->length || rl->lcn < 0) { - ntfs_log_error("Failed to determine last allocated " - "cluster of mft data attribute.\n"); - if (rl) - errno = EIO; - goto out; - } - - lcn = rl->lcn + rl->length; - ntfs_log_debug("Last lcn of mft data attribute is 0x%llx.\n", (long long)lcn); - /* Minimum allocation is one mft record worth of clusters. */ - min_nr = vol->mft_record_size >> vol->cluster_size_bits; - if (!min_nr) - min_nr = 1; - /* Want to allocate 16 mft records worth of clusters. */ - nr = vol->mft_record_size << 4 >> vol->cluster_size_bits; - if (!nr) - nr = min_nr; - - old_last_vcn = rl[1].vcn; - do { - rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE); - if (rl2) - break; - if (errno != ENOSPC || nr == min_nr) { - ntfs_log_perror("Failed to allocate (%lld) clusters " - "for $MFT", (long long)nr); - goto out; - } - /* - * There is not enough space to do the allocation, but there - * might be enough space to do a minimal allocation so try that - * before failing. - */ - nr = min_nr; - ntfs_log_debug("Retrying mft data allocation with minimal cluster " - "count %lli.\n", (long long)nr); - } while (1); - - ntfs_log_debug("Allocated %lld clusters.\n", (long long)nr); - - rl = ntfs_runlists_merge(mft_na->rl, rl2); - if (!rl) { - err = errno; - ntfs_log_error("Failed to merge runlists for mft data " - "attribute.\n"); - if (ntfs_cluster_free_from_rl(vol, rl2)) - ntfs_log_error("Failed to deallocate clusters " - "from the mft data attribute.%s\n", es); - free(rl2); - errno = err; - goto out; - } - mft_na->rl = rl; - - /* Find the last run in the new runlist. */ - for (; rl[1].length; rl++) - ; - /* Update the attribute record as well. */ - ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL); - if (!ctx) - goto undo_alloc; - - if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, - rl[1].vcn, NULL, 0, ctx)) { - ntfs_log_error("Failed to find last attribute extent of " - "mft data attribute.\n"); - goto undo_alloc; - } - m = ctx->mrec; - a = ctx->attr; - ll = sle64_to_cpu(a->lowest_vcn); - rl2 = ntfs_attr_find_vcn(mft_na, ll); - if (!rl2 || !rl2->length) { - ntfs_log_error("Failed to determine previous last " - "allocated cluster of mft data attribute.\n"); - if (rl2) - errno = EIO; - goto undo_alloc; - } - /* Get the size for the new mapping pairs array for this extent. */ - mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, INT_MAX); - if (mp_size <= 0) { - ntfs_log_error("Get size for mapping pairs failed for " - "mft data attribute extent.\n"); - goto undo_alloc; - } - /* Expand the attribute record if necessary. */ - old_alen = le32_to_cpu(a->length); - if (ntfs_attr_record_resize(m, a, - mp_size + le16_to_cpu(a->mapping_pairs_offset))) { - ret = ntfs_mft_attr_extend(vol->mft_na); - if (ret == STATUS_OK) - goto ok; - if (ret == STATUS_ERROR) { - ntfs_log_perror("%s: ntfs_mft_attr_extend failed", __FUNCTION__); - update_mp = TRUE; - } - goto undo_alloc; - } - mp_rebuilt = TRUE; - /* - * Generate the mapping pairs array directly into the attribute record. - */ - if (ntfs_mapping_pairs_build(vol, - (u8*)a + le16_to_cpu(a->mapping_pairs_offset), mp_size, - rl2, ll, NULL)) { - ntfs_log_error("Failed to build mapping pairs array of " - "mft data attribute.\n"); - errno = EIO; - goto undo_alloc; - } - /* Update the highest_vcn. */ - a->highest_vcn = cpu_to_sle64(rl[1].vcn - 1); - /* - * We now have extended the mft data allocated_size by nr clusters. - * Reflect this in the ntfs_attr structure and the attribute record. - * @rl is the last (non-terminator) runlist element of mft data - * attribute. - */ - if (a->lowest_vcn) { - /* - * We are not in the first attribute extent, switch to it, but - * first ensure the changes will make it to disk later. - */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(mft_na->type, mft_na->name, - mft_na->name_len, 0, 0, NULL, 0, ctx)) { - ntfs_log_error("Failed to find first attribute " - "extent of mft data attribute.\n"); - goto restore_undo_alloc; - } - a = ctx->attr; - } + if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, + rl[1].vcn, NULL, 0, ctx)) { + ntfs_log_error("Failed to find last attribute extent of " + "mft data attribute.\n"); + goto undo_alloc; + } + m = ctx->mrec; + a = ctx->attr; + ll = sle64_to_cpu(a->lowest_vcn); + rl2 = ntfs_attr_find_vcn(mft_na, ll); + if (!rl2 || !rl2->length) { + ntfs_log_error("Failed to determine previous last " + "allocated cluster of mft data attribute.\n"); + if (rl2) + errno = EIO; + goto undo_alloc; + } + /* Get the size for the new mapping pairs array for this extent. */ + mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, INT_MAX); + if (mp_size <= 0) { + ntfs_log_error("Get size for mapping pairs failed for " + "mft data attribute extent.\n"); + goto undo_alloc; + } + /* Expand the attribute record if necessary. */ + old_alen = le32_to_cpu(a->length); + if (ntfs_attr_record_resize(m, a, + mp_size + le16_to_cpu(a->mapping_pairs_offset))) { + ret = ntfs_mft_attr_extend(vol->mft_na); + if (ret == STATUS_OK) + goto ok; + if (ret == STATUS_ERROR) { + ntfs_log_perror("%s: ntfs_mft_attr_extend failed", __FUNCTION__); + update_mp = TRUE; + } + goto undo_alloc; + } + mp_rebuilt = TRUE; + /* + * Generate the mapping pairs array directly into the attribute record. + */ + if (ntfs_mapping_pairs_build(vol, + (u8*)a + le16_to_cpu(a->mapping_pairs_offset), mp_size, + rl2, ll, NULL)) { + ntfs_log_error("Failed to build mapping pairs array of " + "mft data attribute.\n"); + errno = EIO; + goto undo_alloc; + } + /* Update the highest_vcn. */ + a->highest_vcn = cpu_to_sle64(rl[1].vcn - 1); + /* + * We now have extended the mft data allocated_size by nr clusters. + * Reflect this in the ntfs_attr structure and the attribute record. + * @rl is the last (non-terminator) runlist element of mft data + * attribute. + */ + if (a->lowest_vcn) { + /* + * We are not in the first attribute extent, switch to it, but + * first ensure the changes will make it to disk later. + */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(mft_na->type, mft_na->name, + mft_na->name_len, 0, 0, NULL, 0, ctx)) { + ntfs_log_error("Failed to find first attribute " + "extent of mft data attribute.\n"); + goto restore_undo_alloc; + } + a = ctx->attr; + } ok: - mft_na->allocated_size += nr << vol->cluster_size_bits; - a->allocated_size = cpu_to_sle64(mft_na->allocated_size); - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - ret = STATUS_OK; + mft_na->allocated_size += nr << vol->cluster_size_bits; + a->allocated_size = cpu_to_sle64(mft_na->allocated_size); + /* Ensure the changes make it to disk. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + ret = STATUS_OK; out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave("\n"); + return ret; restore_undo_alloc: - err = errno; - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, - rl[1].vcn, NULL, 0, ctx)) { - ntfs_log_error("Failed to find last attribute extent of " - "mft data attribute.%s\n", es); - ntfs_attr_put_search_ctx(ctx); - mft_na->allocated_size += nr << vol->cluster_size_bits; - /* - * The only thing that is now wrong is ->allocated_size of the - * base attribute extent which chkdsk should be able to fix. - */ - errno = err; - ret = STATUS_ERROR; - goto out; - } - m = ctx->mrec; - a = ctx->attr; - a->highest_vcn = cpu_to_sle64(old_last_vcn - 1); - errno = err; + err = errno; + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, + rl[1].vcn, NULL, 0, ctx)) { + ntfs_log_error("Failed to find last attribute extent of " + "mft data attribute.%s\n", es); + ntfs_attr_put_search_ctx(ctx); + mft_na->allocated_size += nr << vol->cluster_size_bits; + /* + * The only thing that is now wrong is ->allocated_size of the + * base attribute extent which chkdsk should be able to fix. + */ + errno = err; + ret = STATUS_ERROR; + goto out; + } + m = ctx->mrec; + a = ctx->attr; + a->highest_vcn = cpu_to_sle64(old_last_vcn - 1); + errno = err; undo_alloc: - err = errno; - if (ntfs_cluster_free(vol, mft_na, old_last_vcn, -1) < 0) - ntfs_log_error("Failed to free clusters from mft data " - "attribute.%s\n", es); - if (ntfs_rl_truncate(&mft_na->rl, old_last_vcn)) - ntfs_log_error("Failed to truncate mft data attribute " - "runlist.%s\n", es); - if (mp_rebuilt) { - if (ntfs_mapping_pairs_build(vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), - old_alen - le16_to_cpu(a->mapping_pairs_offset), - rl2, ll, NULL)) - ntfs_log_error("Failed to restore mapping pairs " - "array.%s\n", es); - if (ntfs_attr_record_resize(m, a, old_alen)) - ntfs_log_error("Failed to restore attribute " - "record.%s\n", es); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - } - if (update_mp) { - if (ntfs_attr_update_mapping_pairs(vol->mft_na, 0)) - ntfs_log_perror("%s: MP update failed", __FUNCTION__); - } - if (ctx) - ntfs_attr_put_search_ctx(ctx); - errno = err; - goto out; + err = errno; + if (ntfs_cluster_free(vol, mft_na, old_last_vcn, -1) < 0) + ntfs_log_error("Failed to free clusters from mft data " + "attribute.%s\n", es); + if (ntfs_rl_truncate(&mft_na->rl, old_last_vcn)) + ntfs_log_error("Failed to truncate mft data attribute " + "runlist.%s\n", es); + if (mp_rebuilt) { + if (ntfs_mapping_pairs_build(vol, (u8*)a + + le16_to_cpu(a->mapping_pairs_offset), + old_alen - le16_to_cpu(a->mapping_pairs_offset), + rl2, ll, NULL)) + ntfs_log_error("Failed to restore mapping pairs " + "array.%s\n", es); + if (ntfs_attr_record_resize(m, a, old_alen)) + ntfs_log_error("Failed to restore attribute " + "record.%s\n", es); + ntfs_inode_mark_dirty(ctx->ntfs_ino); + } + if (update_mp) { + if (ntfs_attr_update_mapping_pairs(vol->mft_na, 0)) + ntfs_log_perror("%s: MP update failed", __FUNCTION__); + } + if (ctx) + ntfs_attr_put_search_ctx(ctx); + errno = err; + goto out; } -static int ntfs_mft_record_init(ntfs_volume *vol, s64 size) { - int ret = -1; - ntfs_attr *mft_na, *mftbmp_na; - s64 old_data_initialized, old_data_size; - ntfs_attr_search_ctx *ctx; - - ntfs_log_enter("Entering\n"); - - /* NOTE: Caller must sanity check vol, vol->mft_na and vol->mftbmp_na */ - - mft_na = vol->mft_na; - mftbmp_na = vol->mftbmp_na; - - /* - * The mft record is outside the initialized data. Extend the mft data - * attribute until it covers the allocated record. The loop is only - * actually traversed more than once when a freshly formatted volume - * is first written to so it optimizes away nicely in the common case. - */ - ntfs_log_debug("Status of mft data before extension: " - "allocated_size 0x%llx, data_size 0x%llx, " - "initialized_size 0x%llx.\n", - (long long)mft_na->allocated_size, - (long long)mft_na->data_size, - (long long)mft_na->initialized_size); - while (size > mft_na->allocated_size) { - if (ntfs_mft_data_extend_allocation(vol) == STATUS_ERROR) - goto out; - ntfs_log_debug("Status of mft data after allocation extension: " - "allocated_size 0x%llx, data_size 0x%llx, " - "initialized_size 0x%llx.\n", - (long long)mft_na->allocated_size, - (long long)mft_na->data_size, - (long long)mft_na->initialized_size); - } - - old_data_initialized = mft_na->initialized_size; - old_data_size = mft_na->data_size; - - /* - * Extend mft data initialized size (and data size of course) to reach - * the allocated mft record, formatting the mft records along the way. - * Note: We only modify the ntfs_attr structure as that is all that is - * needed by ntfs_mft_record_format(). We will update the attribute - * record itself in one fell swoop later on. - */ - while (size > mft_na->initialized_size) { - s64 ll2 = mft_na->initialized_size >> vol->mft_record_size_bits; - mft_na->initialized_size += vol->mft_record_size; - if (mft_na->initialized_size > mft_na->data_size) - mft_na->data_size = mft_na->initialized_size; - ntfs_log_debug("Initializing mft record 0x%llx.\n", (long long)ll2); - if (ntfs_mft_record_format(vol, ll2) < 0) { - ntfs_log_perror("Failed to format mft record"); - goto undo_data_init; - } - } - - /* Update the mft data attribute record to reflect the new sizes. */ - ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL); - if (!ctx) - goto undo_data_init; - - if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, - 0, NULL, 0, ctx)) { - ntfs_log_error("Failed to find first attribute extent of " - "mft data attribute.\n"); - ntfs_attr_put_search_ctx(ctx); - goto undo_data_init; - } - ctx->attr->initialized_size = cpu_to_sle64(mft_na->initialized_size); - ctx->attr->data_size = cpu_to_sle64(mft_na->data_size); - ctx->attr->allocated_size = cpu_to_sle64(mft_na->allocated_size); - - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - ntfs_log_debug("Status of mft data after mft record initialization: " - "allocated_size 0x%llx, data_size 0x%llx, " - "initialized_size 0x%llx.\n", - (long long)mft_na->allocated_size, - (long long)mft_na->data_size, - (long long)mft_na->initialized_size); - - /* Sanity checks. */ - if (mft_na->data_size > mft_na->allocated_size || - mft_na->initialized_size > mft_na->data_size) - NTFS_BUG("mft_na sanity checks failed"); - - /* Sync MFT to minimize data loss if there won't be clean unmount. */ - if (ntfs_inode_sync(mft_na->ni)) - goto undo_data_init; - - ret = 0; -out: - ntfs_log_leave("\n"); - return ret; +static int ntfs_mft_record_init(ntfs_volume *vol, s64 size) +{ + int ret = -1; + ntfs_attr *mft_na, *mftbmp_na; + s64 old_data_initialized, old_data_size; + ntfs_attr_search_ctx *ctx; + + ntfs_log_enter("Entering\n"); + + /* NOTE: Caller must sanity check vol, vol->mft_na and vol->mftbmp_na */ + + mft_na = vol->mft_na; + mftbmp_na = vol->mftbmp_na; + + /* + * The mft record is outside the initialized data. Extend the mft data + * attribute until it covers the allocated record. The loop is only + * actually traversed more than once when a freshly formatted volume + * is first written to so it optimizes away nicely in the common case. + */ + ntfs_log_debug("Status of mft data before extension: " + "allocated_size 0x%llx, data_size 0x%llx, " + "initialized_size 0x%llx.\n", + (long long)mft_na->allocated_size, + (long long)mft_na->data_size, + (long long)mft_na->initialized_size); + while (size > mft_na->allocated_size) { + if (ntfs_mft_data_extend_allocation(vol) == STATUS_ERROR) + goto out; + ntfs_log_debug("Status of mft data after allocation extension: " + "allocated_size 0x%llx, data_size 0x%llx, " + "initialized_size 0x%llx.\n", + (long long)mft_na->allocated_size, + (long long)mft_na->data_size, + (long long)mft_na->initialized_size); + } + + old_data_initialized = mft_na->initialized_size; + old_data_size = mft_na->data_size; + + /* + * Extend mft data initialized size (and data size of course) to reach + * the allocated mft record, formatting the mft records along the way. + * Note: We only modify the ntfs_attr structure as that is all that is + * needed by ntfs_mft_record_format(). We will update the attribute + * record itself in one fell swoop later on. + */ + while (size > mft_na->initialized_size) { + s64 ll2 = mft_na->initialized_size >> vol->mft_record_size_bits; + mft_na->initialized_size += vol->mft_record_size; + if (mft_na->initialized_size > mft_na->data_size) + mft_na->data_size = mft_na->initialized_size; + ntfs_log_debug("Initializing mft record 0x%llx.\n", (long long)ll2); + if (ntfs_mft_record_format(vol, ll2) < 0) { + ntfs_log_perror("Failed to format mft record"); + goto undo_data_init; + } + } + + /* Update the mft data attribute record to reflect the new sizes. */ + ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL); + if (!ctx) + goto undo_data_init; + if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, + 0, NULL, 0, ctx)) { + ntfs_log_error("Failed to find first attribute extent of " + "mft data attribute.\n"); + ntfs_attr_put_search_ctx(ctx); + goto undo_data_init; + } + ctx->attr->initialized_size = cpu_to_sle64(mft_na->initialized_size); + ctx->attr->data_size = cpu_to_sle64(mft_na->data_size); + ctx->attr->allocated_size = cpu_to_sle64(mft_na->allocated_size); + + /* Ensure the changes make it to disk. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + ntfs_log_debug("Status of mft data after mft record initialization: " + "allocated_size 0x%llx, data_size 0x%llx, " + "initialized_size 0x%llx.\n", + (long long)mft_na->allocated_size, + (long long)mft_na->data_size, + (long long)mft_na->initialized_size); + + /* Sanity checks. */ + if (mft_na->data_size > mft_na->allocated_size || + mft_na->initialized_size > mft_na->data_size) + NTFS_BUG("mft_na sanity checks failed"); + + /* Sync MFT to minimize data loss if there won't be clean unmount. */ + if (ntfs_inode_sync(mft_na->ni)) + goto undo_data_init; + + ret = 0; +out: + ntfs_log_leave("\n"); + return ret; + undo_data_init: - mft_na->initialized_size = old_data_initialized; - mft_na->data_size = old_data_size; - goto out; + mft_na->initialized_size = old_data_initialized; + mft_na->data_size = old_data_size; + goto out; } -static int ntfs_mft_rec_init(ntfs_volume *vol, s64 size) { - int ret = -1; - ntfs_attr *mft_na, *mftbmp_na; - s64 old_data_initialized, old_data_size; - ntfs_attr_search_ctx *ctx; +static int ntfs_mft_rec_init(ntfs_volume *vol, s64 size) +{ + int ret = -1; + ntfs_attr *mft_na, *mftbmp_na; + s64 old_data_initialized, old_data_size; + ntfs_attr_search_ctx *ctx; + + ntfs_log_enter("Entering\n"); + + mft_na = vol->mft_na; + mftbmp_na = vol->mftbmp_na; + + if (size > mft_na->allocated_size || size > mft_na->initialized_size) { + errno = EIO; + ntfs_log_perror("%s: unexpected $MFT sizes, see below", __FUNCTION__); + ntfs_log_error("$MFT: size=%lld allocated_size=%lld " + "data_size=%lld initialized_size=%lld\n", + (long long)size, + (long long)mft_na->allocated_size, + (long long)mft_na->data_size, + (long long)mft_na->initialized_size); + goto out; + } + + old_data_initialized = mft_na->initialized_size; + old_data_size = mft_na->data_size; + + /* Update the mft data attribute record to reflect the new sizes. */ + ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL); + if (!ctx) + goto undo_data_init; - ntfs_log_enter("Entering\n"); - - mft_na = vol->mft_na; - mftbmp_na = vol->mftbmp_na; - - if (size > mft_na->allocated_size || size > mft_na->initialized_size) { - errno = EIO; - ntfs_log_perror("%s: unexpected $MFT sizes, see below", __FUNCTION__); - ntfs_log_error("$MFT: size=%lld allocated_size=%lld " - "data_size=%lld initialized_size=%lld\n", - (long long)size, - (long long)mft_na->allocated_size, - (long long)mft_na->data_size, - (long long)mft_na->initialized_size); - goto out; - } - - old_data_initialized = mft_na->initialized_size; - old_data_size = mft_na->data_size; - - /* Update the mft data attribute record to reflect the new sizes. */ - ctx = ntfs_attr_get_search_ctx(mft_na->ni, NULL); - if (!ctx) - goto undo_data_init; - - if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, - 0, NULL, 0, ctx)) { - ntfs_log_error("Failed to find first attribute extent of " - "mft data attribute.\n"); - ntfs_attr_put_search_ctx(ctx); - goto undo_data_init; - } - ctx->attr->initialized_size = cpu_to_sle64(mft_na->initialized_size); - ctx->attr->data_size = cpu_to_sle64(mft_na->data_size); - - /* CHECKME: ctx->attr->allocation_size is already ok? */ - - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - - /* Sanity checks. */ - if (mft_na->data_size > mft_na->allocated_size || - mft_na->initialized_size > mft_na->data_size) - NTFS_BUG("mft_na sanity checks failed"); -out: - ntfs_log_leave("\n"); - return ret; + if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, + 0, NULL, 0, ctx)) { + ntfs_log_error("Failed to find first attribute extent of " + "mft data attribute.\n"); + ntfs_attr_put_search_ctx(ctx); + goto undo_data_init; + } + ctx->attr->initialized_size = cpu_to_sle64(mft_na->initialized_size); + ctx->attr->data_size = cpu_to_sle64(mft_na->data_size); + /* CHECKME: ctx->attr->allocation_size is already ok? */ + + /* Ensure the changes make it to disk. */ + ntfs_inode_mark_dirty(ctx->ntfs_ino); + ntfs_attr_put_search_ctx(ctx); + + /* Sanity checks. */ + if (mft_na->data_size > mft_na->allocated_size || + mft_na->initialized_size > mft_na->data_size) + NTFS_BUG("mft_na sanity checks failed"); +out: + ntfs_log_leave("\n"); + return ret; + undo_data_init: - mft_na->initialized_size = old_data_initialized; - mft_na->data_size = old_data_size; - goto out; + mft_na->initialized_size = old_data_initialized; + mft_na->data_size = old_data_size; + goto out; } -static ntfs_inode *ntfs_mft_rec_alloc(ntfs_volume *vol) { - s64 ll, bit; - ntfs_attr *mft_na, *mftbmp_na; - MFT_RECORD *m; - ntfs_inode *ni = NULL; - ntfs_inode *base_ni; - int err; - le16 seq_no, usn; +static ntfs_inode *ntfs_mft_rec_alloc(ntfs_volume *vol) +{ + s64 ll, bit; + ntfs_attr *mft_na, *mftbmp_na; + MFT_RECORD *m; + ntfs_inode *ni = NULL; + ntfs_inode *base_ni; + int err; + le16 seq_no, usn; - ntfs_log_enter("Entering\n"); + ntfs_log_enter("Entering\n"); - mft_na = vol->mft_na; - mftbmp_na = vol->mftbmp_na; + mft_na = vol->mft_na; + mftbmp_na = vol->mftbmp_na; - base_ni = mft_na->ni; + base_ni = mft_na->ni; - bit = ntfs_mft_bitmap_find_free_rec(vol, base_ni); - if (bit >= 0) - goto found_free_rec; + bit = ntfs_mft_bitmap_find_free_rec(vol, base_ni); + if (bit >= 0) + goto found_free_rec; - if (errno != ENOSPC) - goto out; - - errno = ENOSPC; - /* strerror() is intentionally used below, we want to log this error. */ - ntfs_log_error("No free mft record for $MFT: %s\n", strerror(errno)); - goto err_out; + if (errno != ENOSPC) + goto out; + + errno = ENOSPC; + /* strerror() is intentionally used below, we want to log this error. */ + ntfs_log_error("No free mft record for $MFT: %s\n", strerror(errno)); + goto err_out; found_free_rec: - if (ntfs_bitmap_set_bit(mftbmp_na, bit)) { - ntfs_log_error("Failed to allocate bit in mft bitmap #2\n"); - goto err_out; - } + if (ntfs_bitmap_set_bit(mftbmp_na, bit)) { + ntfs_log_error("Failed to allocate bit in mft bitmap #2\n"); + goto err_out; + } + + ll = (bit + 1) << vol->mft_record_size_bits; + if (ll > mft_na->initialized_size) + if (ntfs_mft_rec_init(vol, ll) < 0) + goto undo_mftbmp_alloc; + /* + * We now have allocated and initialized the mft record. Need to read + * it from disk and re-format it, preserving the sequence number if it + * is not zero as well as the update sequence number if it is not zero + * or -1 (0xffff). + */ + m = ntfs_malloc(vol->mft_record_size); + if (!m) + goto undo_mftbmp_alloc; + + if (ntfs_mft_record_read(vol, bit, m)) { + free(m); + goto undo_mftbmp_alloc; + } + /* Sanity check that the mft record is really not in use. */ + if (ntfs_is_file_record(m->magic) && (m->flags & MFT_RECORD_IN_USE)) { + ntfs_log_error("Inode %lld is used but it wasn't marked in " + "$MFT bitmap. Fixed.\n", (long long)bit); + free(m); + goto undo_mftbmp_alloc; + } - ll = (bit + 1) << vol->mft_record_size_bits; - if (ll > mft_na->initialized_size) - if (ntfs_mft_rec_init(vol, ll) < 0) - goto undo_mftbmp_alloc; - /* - * We now have allocated and initialized the mft record. Need to read - * it from disk and re-format it, preserving the sequence number if it - * is not zero as well as the update sequence number if it is not zero - * or -1 (0xffff). - */ - m = ntfs_malloc(vol->mft_record_size); - if (!m) - goto undo_mftbmp_alloc; + seq_no = m->sequence_number; + usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)); + if (ntfs_mft_record_layout(vol, bit, m)) { + ntfs_log_error("Failed to re-format mft record.\n"); + free(m); + goto undo_mftbmp_alloc; + } + if (seq_no) + m->sequence_number = seq_no; + seq_no = usn; + if (seq_no && seq_no != const_cpu_to_le16(0xffff)) + *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn; + /* Set the mft record itself in use. */ + m->flags |= MFT_RECORD_IN_USE; + /* Now need to open an ntfs inode for the mft record. */ + ni = ntfs_inode_allocate(vol); + if (!ni) { + ntfs_log_error("Failed to allocate buffer for inode.\n"); + free(m); + goto undo_mftbmp_alloc; + } + ni->mft_no = bit; + ni->mrec = m; + /* + * If we are allocating an extent mft record, make the opened inode an + * extent inode and attach it to the base inode. Also, set the base + * mft record reference in the extent inode. + */ + ni->nr_extents = -1; + ni->base_ni = base_ni; + m->base_mft_record = MK_LE_MREF(base_ni->mft_no, + le16_to_cpu(base_ni->mrec->sequence_number)); + /* + * Attach the extent inode to the base inode, reallocating + * memory if needed. + */ + if (!(base_ni->nr_extents & 3)) { + ntfs_inode **extent_nis; + int i; - if (ntfs_mft_record_read(vol, bit, m)) { - free(m); - goto undo_mftbmp_alloc; - } - /* Sanity check that the mft record is really not in use. */ - if (ntfs_is_file_record(m->magic) && (m->flags & MFT_RECORD_IN_USE)) { - ntfs_log_error("Inode %lld is used but it wasn't marked in " - "$MFT bitmap. Fixed.\n", (long long)bit); - free(m); - goto undo_mftbmp_alloc; - } - - seq_no = m->sequence_number; - usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)); - if (ntfs_mft_record_layout(vol, bit, m)) { - ntfs_log_error("Failed to re-format mft record.\n"); - free(m); - goto undo_mftbmp_alloc; - } - if (seq_no) - m->sequence_number = seq_no; - seq_no = usn; - if (seq_no && seq_no != const_cpu_to_le16(0xffff)) - *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn; - /* Set the mft record itself in use. */ - m->flags |= MFT_RECORD_IN_USE; - /* Now need to open an ntfs inode for the mft record. */ - ni = ntfs_inode_allocate(vol); - if (!ni) { - ntfs_log_error("Failed to allocate buffer for inode.\n"); - free(m); - goto undo_mftbmp_alloc; - } - ni->mft_no = bit; - ni->mrec = m; - /* - * If we are allocating an extent mft record, make the opened inode an - * extent inode and attach it to the base inode. Also, set the base - * mft record reference in the extent inode. - */ - ni->nr_extents = -1; - ni->base_ni = base_ni; - m->base_mft_record = MK_LE_MREF(base_ni->mft_no, - le16_to_cpu(base_ni->mrec->sequence_number)); - /* - * Attach the extent inode to the base inode, reallocating - * memory if needed. - */ - if (!(base_ni->nr_extents & 3)) { - ntfs_inode **extent_nis; - int i; - - i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *); - extent_nis = ntfs_malloc(i); - if (!extent_nis) { - free(m); - free(ni); - goto undo_mftbmp_alloc; - } - if (base_ni->nr_extents) { - memcpy(extent_nis, base_ni->extent_nis, - i - 4 * sizeof(ntfs_inode *)); - free(base_ni->extent_nis); - } - base_ni->extent_nis = extent_nis; - } - base_ni->extent_nis[base_ni->nr_extents++] = ni; - - /* Make sure the allocated inode is written out to disk later. */ - ntfs_inode_mark_dirty(ni); - /* Initialize time, allocated and data size in ntfs_inode struct. */ - ni->data_size = ni->allocated_size = 0; - ni->flags = 0; - ni->creation_time = ni->last_data_change_time = - ni->last_mft_change_time = - ni->last_access_time = time(NULL); - set_nino_flag(ni, TimesDirty); - /* Update the default mft allocation position if it was used. */ - if (!base_ni) - vol->mft_data_pos = bit + 1; - /* Return the opened, allocated inode of the allocated mft record. */ - ntfs_log_error("allocated %sinode %lld\n", - base_ni ? "extent " : "", (long long)bit); + i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *); + extent_nis = ntfs_malloc(i); + if (!extent_nis) { + free(m); + free(ni); + goto undo_mftbmp_alloc; + } + if (base_ni->nr_extents) { + memcpy(extent_nis, base_ni->extent_nis, + i - 4 * sizeof(ntfs_inode *)); + free(base_ni->extent_nis); + } + base_ni->extent_nis = extent_nis; + } + base_ni->extent_nis[base_ni->nr_extents++] = ni; + + /* Make sure the allocated inode is written out to disk later. */ + ntfs_inode_mark_dirty(ni); + /* Initialize time, allocated and data size in ntfs_inode struct. */ + ni->data_size = ni->allocated_size = 0; + ni->flags = 0; + ni->creation_time = ni->last_data_change_time = + ni->last_mft_change_time = + ni->last_access_time = time(NULL); + set_nino_flag(ni, TimesDirty); + /* Update the default mft allocation position if it was used. */ + if (!base_ni) + vol->mft_data_pos = bit + 1; + /* Return the opened, allocated inode of the allocated mft record. */ + ntfs_log_error("allocated %sinode %lld\n", + base_ni ? "extent " : "", (long long)bit); out: - ntfs_log_leave("\n"); - return ni; + ntfs_log_leave("\n"); + return ni; undo_mftbmp_alloc: - err = errno; - if (ntfs_bitmap_clear_bit(mftbmp_na, bit)) - ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es); - errno = err; + err = errno; + if (ntfs_bitmap_clear_bit(mftbmp_na, bit)) + ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es); + errno = err; err_out: - if (!errno) - errno = EIO; - ni = NULL; - goto out; + if (!errno) + errno = EIO; + ni = NULL; + goto out; } /** @@ -1568,224 +1585,225 @@ err_out: * when reading the bitmap but if we are careful, we should be able to avoid * all problems. */ -ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, ntfs_inode *base_ni) { - s64 ll, bit; - ntfs_attr *mft_na, *mftbmp_na; - MFT_RECORD *m; - ntfs_inode *ni = NULL; - int err; - le16 seq_no, usn; +ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, ntfs_inode *base_ni) +{ + s64 ll, bit; + ntfs_attr *mft_na, *mftbmp_na; + MFT_RECORD *m; + ntfs_inode *ni = NULL; + int err; + le16 seq_no, usn; - if (base_ni) - ntfs_log_enter("Entering (allocating an extent mft record for " - "base mft record %lld).\n", - (long long)base_ni->mft_no); - else - ntfs_log_enter("Entering (allocating a base mft record)\n"); - if (!vol || !vol->mft_na || !vol->mftbmp_na) { - errno = EINVAL; - goto out; - } + if (base_ni) + ntfs_log_enter("Entering (allocating an extent mft record for " + "base mft record %lld).\n", + (long long)base_ni->mft_no); + else + ntfs_log_enter("Entering (allocating a base mft record)\n"); + if (!vol || !vol->mft_na || !vol->mftbmp_na) { + errno = EINVAL; + goto out; + } + + if (ntfs_is_mft(base_ni)) { + ni = ntfs_mft_rec_alloc(vol); + goto out; + } - if (ntfs_is_mft(base_ni)) { - ni = ntfs_mft_rec_alloc(vol); - goto out; - } + mft_na = vol->mft_na; + mftbmp_na = vol->mftbmp_na; +retry: + bit = ntfs_mft_bitmap_find_free_rec(vol, base_ni); + if (bit >= 0) { + ntfs_log_debug("found free record (#1) at %lld\n", + (long long)bit); + goto found_free_rec; + } + if (errno != ENOSPC) + goto out; + /* + * No free mft records left. If the mft bitmap already covers more + * than the currently used mft records, the next records are all free, + * so we can simply allocate the first unused mft record. + * Note: We also have to make sure that the mft bitmap at least covers + * the first 24 mft records as they are special and whilst they may not + * be in use, we do not allocate from them. + */ + ll = mft_na->initialized_size >> vol->mft_record_size_bits; + if (mftbmp_na->initialized_size << 3 > ll && + mftbmp_na->initialized_size > RESERVED_MFT_RECORDS / 8) { + bit = ll; + if (bit < RESERVED_MFT_RECORDS) + bit = RESERVED_MFT_RECORDS; + ntfs_log_debug("found free record (#2) at %lld\n", + (long long)bit); + goto found_free_rec; + } + /* + * The mft bitmap needs to be expanded until it covers the first unused + * mft record that we can allocate. + * Note: The smallest mft record we allocate is mft record 24. + */ + ntfs_log_debug("Status of mftbmp before extension: allocated_size 0x%llx, " + "data_size 0x%llx, initialized_size 0x%llx.\n", + (long long)mftbmp_na->allocated_size, + (long long)mftbmp_na->data_size, + (long long)mftbmp_na->initialized_size); + if (mftbmp_na->initialized_size + 8 > mftbmp_na->allocated_size) { - mft_na = vol->mft_na; - mftbmp_na = vol->mftbmp_na; -retry: - bit = ntfs_mft_bitmap_find_free_rec(vol, base_ni); - if (bit >= 0) { - ntfs_log_debug("found free record (#1) at %lld\n", - (long long)bit); - goto found_free_rec; - } - if (errno != ENOSPC) - goto out; - /* - * No free mft records left. If the mft bitmap already covers more - * than the currently used mft records, the next records are all free, - * so we can simply allocate the first unused mft record. - * Note: We also have to make sure that the mft bitmap at least covers - * the first 24 mft records as they are special and whilst they may not - * be in use, we do not allocate from them. - */ - ll = mft_na->initialized_size >> vol->mft_record_size_bits; - if (mftbmp_na->initialized_size << 3 > ll && - mftbmp_na->initialized_size > RESERVED_MFT_RECORDS / 8) { - bit = ll; - if (bit < RESERVED_MFT_RECORDS) - bit = RESERVED_MFT_RECORDS; - ntfs_log_debug("found free record (#2) at %lld\n", - (long long)bit); - goto found_free_rec; - } - /* - * The mft bitmap needs to be expanded until it covers the first unused - * mft record that we can allocate. - * Note: The smallest mft record we allocate is mft record 24. - */ - ntfs_log_debug("Status of mftbmp before extension: allocated_size 0x%llx, " - "data_size 0x%llx, initialized_size 0x%llx.\n", - (long long)mftbmp_na->allocated_size, - (long long)mftbmp_na->data_size, - (long long)mftbmp_na->initialized_size); - if (mftbmp_na->initialized_size + 8 > mftbmp_na->allocated_size) { + int ret = ntfs_mft_bitmap_extend_allocation(vol); - int ret = ntfs_mft_bitmap_extend_allocation(vol); + if (ret == STATUS_ERROR) + goto err_out; + if (ret == STATUS_KEEP_SEARCHING) { + ret = ntfs_mft_bitmap_extend_allocation(vol); + if (ret != STATUS_OK) + goto err_out; + } - if (ret == STATUS_ERROR) - goto err_out; - if (ret == STATUS_KEEP_SEARCHING) { - ret = ntfs_mft_bitmap_extend_allocation(vol); - if (ret != STATUS_OK) - goto err_out; - } - - ntfs_log_debug("Status of mftbmp after allocation extension: " - "allocated_size 0x%llx, data_size 0x%llx, " - "initialized_size 0x%llx.\n", - (long long)mftbmp_na->allocated_size, - (long long)mftbmp_na->data_size, - (long long)mftbmp_na->initialized_size); - } - /* - * We now have sufficient allocated space, extend the initialized_size - * as well as the data_size if necessary and fill the new space with - * zeroes. - */ - bit = mftbmp_na->initialized_size << 3; - if (ntfs_mft_bitmap_extend_initialized(vol)) - goto err_out; - ntfs_log_debug("Status of mftbmp after initialized extension: " - "allocated_size 0x%llx, data_size 0x%llx, " - "initialized_size 0x%llx.\n", - (long long)mftbmp_na->allocated_size, - (long long)mftbmp_na->data_size, - (long long)mftbmp_na->initialized_size); - ntfs_log_debug("found free record (#3) at %lld\n", (long long)bit); + ntfs_log_debug("Status of mftbmp after allocation extension: " + "allocated_size 0x%llx, data_size 0x%llx, " + "initialized_size 0x%llx.\n", + (long long)mftbmp_na->allocated_size, + (long long)mftbmp_na->data_size, + (long long)mftbmp_na->initialized_size); + } + /* + * We now have sufficient allocated space, extend the initialized_size + * as well as the data_size if necessary and fill the new space with + * zeroes. + */ + bit = mftbmp_na->initialized_size << 3; + if (ntfs_mft_bitmap_extend_initialized(vol)) + goto err_out; + ntfs_log_debug("Status of mftbmp after initialized extension: " + "allocated_size 0x%llx, data_size 0x%llx, " + "initialized_size 0x%llx.\n", + (long long)mftbmp_na->allocated_size, + (long long)mftbmp_na->data_size, + (long long)mftbmp_na->initialized_size); + ntfs_log_debug("found free record (#3) at %lld\n", (long long)bit); found_free_rec: - /* @bit is the found free mft record, allocate it in the mft bitmap. */ - if (ntfs_bitmap_set_bit(mftbmp_na, bit)) { - ntfs_log_error("Failed to allocate bit in mft bitmap.\n"); - goto err_out; - } + /* @bit is the found free mft record, allocate it in the mft bitmap. */ + if (ntfs_bitmap_set_bit(mftbmp_na, bit)) { + ntfs_log_error("Failed to allocate bit in mft bitmap.\n"); + goto err_out; + } + + /* The mft bitmap is now uptodate. Deal with mft data attribute now. */ + ll = (bit + 1) << vol->mft_record_size_bits; + if (ll > mft_na->initialized_size) + if (ntfs_mft_record_init(vol, ll) < 0) + goto undo_mftbmp_alloc; - /* The mft bitmap is now uptodate. Deal with mft data attribute now. */ - ll = (bit + 1) << vol->mft_record_size_bits; - if (ll > mft_na->initialized_size) - if (ntfs_mft_record_init(vol, ll) < 0) - goto undo_mftbmp_alloc; + /* + * We now have allocated and initialized the mft record. Need to read + * it from disk and re-format it, preserving the sequence number if it + * is not zero as well as the update sequence number if it is not zero + * or -1 (0xffff). + */ + m = ntfs_malloc(vol->mft_record_size); + if (!m) + goto undo_mftbmp_alloc; + + if (ntfs_mft_record_read(vol, bit, m)) { + free(m); + goto undo_mftbmp_alloc; + } + /* Sanity check that the mft record is really not in use. */ + if (ntfs_is_file_record(m->magic) && (m->flags & MFT_RECORD_IN_USE)) { + ntfs_log_error("Inode %lld is used but it wasn't marked in " + "$MFT bitmap. Fixed.\n", (long long)bit); + free(m); + goto retry; + } + seq_no = m->sequence_number; + usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)); + if (ntfs_mft_record_layout(vol, bit, m)) { + ntfs_log_error("Failed to re-format mft record.\n"); + free(m); + goto undo_mftbmp_alloc; + } + if (seq_no) + m->sequence_number = seq_no; + seq_no = usn; + if (seq_no && seq_no != const_cpu_to_le16(0xffff)) + *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn; + /* Set the mft record itself in use. */ + m->flags |= MFT_RECORD_IN_USE; + /* Now need to open an ntfs inode for the mft record. */ + ni = ntfs_inode_allocate(vol); + if (!ni) { + ntfs_log_error("Failed to allocate buffer for inode.\n"); + free(m); + goto undo_mftbmp_alloc; + } + ni->mft_no = bit; + ni->mrec = m; + /* + * If we are allocating an extent mft record, make the opened inode an + * extent inode and attach it to the base inode. Also, set the base + * mft record reference in the extent inode. + */ + if (base_ni) { + ni->nr_extents = -1; + ni->base_ni = base_ni; + m->base_mft_record = MK_LE_MREF(base_ni->mft_no, + le16_to_cpu(base_ni->mrec->sequence_number)); + /* + * Attach the extent inode to the base inode, reallocating + * memory if needed. + */ + if (!(base_ni->nr_extents & 3)) { + ntfs_inode **extent_nis; + int i; - /* - * We now have allocated and initialized the mft record. Need to read - * it from disk and re-format it, preserving the sequence number if it - * is not zero as well as the update sequence number if it is not zero - * or -1 (0xffff). - */ - m = ntfs_malloc(vol->mft_record_size); - if (!m) - goto undo_mftbmp_alloc; - - if (ntfs_mft_record_read(vol, bit, m)) { - free(m); - goto undo_mftbmp_alloc; - } - /* Sanity check that the mft record is really not in use. */ - if (ntfs_is_file_record(m->magic) && (m->flags & MFT_RECORD_IN_USE)) { - ntfs_log_error("Inode %lld is used but it wasn't marked in " - "$MFT bitmap. Fixed.\n", (long long)bit); - free(m); - goto retry; - } - seq_no = m->sequence_number; - usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)); - if (ntfs_mft_record_layout(vol, bit, m)) { - ntfs_log_error("Failed to re-format mft record.\n"); - free(m); - goto undo_mftbmp_alloc; - } - if (seq_no) - m->sequence_number = seq_no; - seq_no = usn; - if (seq_no && seq_no != const_cpu_to_le16(0xffff)) - *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn; - /* Set the mft record itself in use. */ - m->flags |= MFT_RECORD_IN_USE; - /* Now need to open an ntfs inode for the mft record. */ - ni = ntfs_inode_allocate(vol); - if (!ni) { - ntfs_log_error("Failed to allocate buffer for inode.\n"); - free(m); - goto undo_mftbmp_alloc; - } - ni->mft_no = bit; - ni->mrec = m; - /* - * If we are allocating an extent mft record, make the opened inode an - * extent inode and attach it to the base inode. Also, set the base - * mft record reference in the extent inode. - */ - if (base_ni) { - ni->nr_extents = -1; - ni->base_ni = base_ni; - m->base_mft_record = MK_LE_MREF(base_ni->mft_no, - le16_to_cpu(base_ni->mrec->sequence_number)); - /* - * Attach the extent inode to the base inode, reallocating - * memory if needed. - */ - if (!(base_ni->nr_extents & 3)) { - ntfs_inode **extent_nis; - int i; - - i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *); - extent_nis = ntfs_malloc(i); - if (!extent_nis) { - free(m); - free(ni); - goto undo_mftbmp_alloc; - } - if (base_ni->nr_extents) { - memcpy(extent_nis, base_ni->extent_nis, - i - 4 * sizeof(ntfs_inode *)); - free(base_ni->extent_nis); - } - base_ni->extent_nis = extent_nis; - } - base_ni->extent_nis[base_ni->nr_extents++] = ni; - } - /* Make sure the allocated inode is written out to disk later. */ - ntfs_inode_mark_dirty(ni); - /* Initialize time, allocated and data size in ntfs_inode struct. */ - ni->data_size = ni->allocated_size = 0; - ni->flags = 0; - ni->creation_time = ni->last_data_change_time = - ni->last_mft_change_time = - ni->last_access_time = time(NULL); - set_nino_flag(ni, TimesDirty); - /* Update the default mft allocation position if it was used. */ - if (!base_ni) - vol->mft_data_pos = bit + 1; - /* Return the opened, allocated inode of the allocated mft record. */ - ntfs_log_debug("allocated %sinode 0x%llx.\n", - base_ni ? "extent " : "", (long long)bit); - vol->free_mft_records--; + i = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *); + extent_nis = ntfs_malloc(i); + if (!extent_nis) { + free(m); + free(ni); + goto undo_mftbmp_alloc; + } + if (base_ni->nr_extents) { + memcpy(extent_nis, base_ni->extent_nis, + i - 4 * sizeof(ntfs_inode *)); + free(base_ni->extent_nis); + } + base_ni->extent_nis = extent_nis; + } + base_ni->extent_nis[base_ni->nr_extents++] = ni; + } + /* Make sure the allocated inode is written out to disk later. */ + ntfs_inode_mark_dirty(ni); + /* Initialize time, allocated and data size in ntfs_inode struct. */ + ni->data_size = ni->allocated_size = 0; + ni->flags = 0; + ni->creation_time = ni->last_data_change_time = + ni->last_mft_change_time = + ni->last_access_time = time(NULL); + set_nino_flag(ni, TimesDirty); + /* Update the default mft allocation position if it was used. */ + if (!base_ni) + vol->mft_data_pos = bit + 1; + /* Return the opened, allocated inode of the allocated mft record. */ + ntfs_log_debug("allocated %sinode 0x%llx.\n", + base_ni ? "extent " : "", (long long)bit); + vol->free_mft_records--; out: - ntfs_log_leave("\n"); - return ni; + ntfs_log_leave("\n"); + return ni; undo_mftbmp_alloc: - err = errno; - if (ntfs_bitmap_clear_bit(mftbmp_na, bit)) - ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es); - errno = err; + err = errno; + if (ntfs_bitmap_clear_bit(mftbmp_na, bit)) + ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es); + errno = err; err_out: - if (!errno) - errno = EIO; - ni = NULL; - goto out; + if (!errno) + errno = EIO; + ni = NULL; + goto out; } /** @@ -1799,67 +1817,68 @@ err_out: * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_mft_record_free(ntfs_volume *vol, ntfs_inode *ni) { - u64 mft_no; - int err; - u16 seq_no; - le16 old_seq_no; +int ntfs_mft_record_free(ntfs_volume *vol, ntfs_inode *ni) +{ + u64 mft_no; + int err; + u16 seq_no; + le16 old_seq_no; - ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no); + ntfs_log_trace("Entering for inode 0x%llx.\n", (long long) ni->mft_no); - if (!vol || !vol->mftbmp_na || !ni) { - errno = EINVAL; - return -1; - } + if (!vol || !vol->mftbmp_na || !ni) { + errno = EINVAL; + return -1; + } - /* Cache the mft reference for later. */ - mft_no = ni->mft_no; + /* Cache the mft reference for later. */ + mft_no = ni->mft_no; - /* Mark the mft record as not in use. */ - ni->mrec->flags &= ~MFT_RECORD_IN_USE; + /* Mark the mft record as not in use. */ + ni->mrec->flags &= ~MFT_RECORD_IN_USE; - /* Increment the sequence number, skipping zero, if it is not zero. */ - old_seq_no = ni->mrec->sequence_number; - seq_no = le16_to_cpu(old_seq_no); - if (seq_no == 0xffff) - seq_no = 1; - else if (seq_no) - seq_no++; - ni->mrec->sequence_number = cpu_to_le16(seq_no); + /* Increment the sequence number, skipping zero, if it is not zero. */ + old_seq_no = ni->mrec->sequence_number; + seq_no = le16_to_cpu(old_seq_no); + if (seq_no == 0xffff) + seq_no = 1; + else if (seq_no) + seq_no++; + ni->mrec->sequence_number = cpu_to_le16(seq_no); - /* Set the inode dirty and write it out. */ - ntfs_inode_mark_dirty(ni); - if (ntfs_inode_sync(ni)) { - err = errno; - goto sync_rollback; - } + /* Set the inode dirty and write it out. */ + ntfs_inode_mark_dirty(ni); + if (ntfs_inode_sync(ni)) { + err = errno; + goto sync_rollback; + } - /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */ - if (ntfs_bitmap_clear_bit(vol->mftbmp_na, mft_no)) { - err = errno; - // FIXME: If ntfs_bitmap_clear_run() guarantees rollback on - // error, this could be changed to goto sync_rollback; - goto bitmap_rollback; - } + /* Clear the bit in the $MFT/$BITMAP corresponding to this record. */ + if (ntfs_bitmap_clear_bit(vol->mftbmp_na, mft_no)) { + err = errno; + // FIXME: If ntfs_bitmap_clear_run() guarantees rollback on + // error, this could be changed to goto sync_rollback; + goto bitmap_rollback; + } - /* Throw away the now freed inode. */ - if (!ntfs_inode_close(ni)) { - vol->free_mft_records++; - return 0; - } - err = errno; + /* Throw away the now freed inode. */ + if (!ntfs_inode_close(ni)) { + vol->free_mft_records++; + return 0; + } + err = errno; - /* Rollback what we did... */ + /* Rollback what we did... */ bitmap_rollback: - if (ntfs_bitmap_set_bit(vol->mftbmp_na, mft_no)) - ntfs_log_debug("Eeek! Rollback failed in ntfs_mft_record_free(). " - "Leaving inconsistent metadata!\n"); + if (ntfs_bitmap_set_bit(vol->mftbmp_na, mft_no)) + ntfs_log_debug("Eeek! Rollback failed in ntfs_mft_record_free(). " + "Leaving inconsistent metadata!\n"); sync_rollback: - ni->mrec->flags |= MFT_RECORD_IN_USE; - ni->mrec->sequence_number = old_seq_no; - ntfs_inode_mark_dirty(ni); - errno = err; - return -1; + ni->mrec->flags |= MFT_RECORD_IN_USE; + ni->mrec->sequence_number = old_seq_no; + ntfs_inode_mark_dirty(ni); + errno = err; + return -1; } /** @@ -1868,20 +1887,21 @@ sync_rollback: * * On success return 0 and on error return -1 with errno set. */ -int ntfs_mft_usn_dec(MFT_RECORD *mrec) { - u16 usn; - le16 *usnp; +int ntfs_mft_usn_dec(MFT_RECORD *mrec) +{ + u16 usn; + le16 *usnp; - if (!mrec) { - errno = EINVAL; - return -1; - } - usnp = (le16*)((char*)mrec + le16_to_cpu(mrec->usa_ofs)); - usn = le16_to_cpup(usnp); - if (usn-- <= 1) - usn = 0xfffe; - *usnp = cpu_to_le16(usn); + if (!mrec) { + errno = EINVAL; + return -1; + } + usnp = (le16*)((char*)mrec + le16_to_cpu(mrec->usa_ofs)); + usn = le16_to_cpup(usnp); + if (usn-- <= 1) + usn = 0xfffe; + *usnp = cpu_to_le16(usn); - return 0; + return 0; } diff --git a/source/libntfs/mft.h b/source/libntfs/mft.h index 6792b13f..bb15f0f3 100644 --- a/source/libntfs/mft.h +++ b/source/libntfs/mft.h @@ -30,7 +30,7 @@ #include "logging.h" extern int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, - const s64 count, MFT_RECORD *b); + const s64 count, MFT_RECORD *b); /** * ntfs_mft_record_read - read a record from the mft @@ -48,23 +48,24 @@ extern int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, * NOTE: @b has to be at least of size vol->mft_record_size. */ static __inline__ int ntfs_mft_record_read(const ntfs_volume *vol, - const MFT_REF mref, MFT_RECORD *b) { - int ret; - - ntfs_log_enter("Entering for inode %lld\n", (long long)MREF(mref)); - ret = ntfs_mft_records_read(vol, mref, 1, b); - ntfs_log_leave("\n"); - return ret; + const MFT_REF mref, MFT_RECORD *b) +{ + int ret; + + ntfs_log_enter("Entering for inode %lld\n", (long long)MREF(mref)); + ret = ntfs_mft_records_read(vol, mref, 1, b); + ntfs_log_leave("\n"); + return ret; } -extern int ntfs_mft_record_check(const ntfs_volume *vol, const MFT_REF mref, - MFT_RECORD *m); +extern int ntfs_mft_record_check(const ntfs_volume *vol, const MFT_REF mref, + MFT_RECORD *m); extern int ntfs_file_record_read(const ntfs_volume *vol, const MFT_REF mref, - MFT_RECORD **mrec, ATTR_RECORD **attr); + MFT_RECORD **mrec, ATTR_RECORD **attr); extern int ntfs_mft_records_write(const ntfs_volume *vol, const MFT_REF mref, - const s64 count, MFT_RECORD *b); + const s64 count, MFT_RECORD *b); /** * ntfs_mft_record_write - write an mft record to disk @@ -82,13 +83,14 @@ extern int ntfs_mft_records_write(const ntfs_volume *vol, const MFT_REF mref, * NOTE: @b has to be at least of size vol->mft_record_size. */ static __inline__ int ntfs_mft_record_write(const ntfs_volume *vol, - const MFT_REF mref, MFT_RECORD *b) { - int ret; - - ntfs_log_enter("Entering for inode %lld\n", (long long)MREF(mref)); - ret = ntfs_mft_records_write(vol, mref, 1, b); - ntfs_log_leave("\n"); - return ret; + const MFT_REF mref, MFT_RECORD *b) +{ + int ret; + + ntfs_log_enter("Entering for inode %lld\n", (long long)MREF(mref)); + ret = ntfs_mft_records_write(vol, mref, 1, b); + ntfs_log_leave("\n"); + return ret; } /** @@ -107,15 +109,16 @@ static __inline__ int ntfs_mft_record_write(const ntfs_volume *vol, * non-existent (don't know if Windows' NTFS driver/chkdsk wouldn't view this * as corruption in itself though). */ -static __inline__ u32 ntfs_mft_record_get_data_size(const MFT_RECORD *m) { - if (!m || !ntfs_is_mft_record(m->magic)) - return 0; - /* Get the number of used bytes and return it. */ - return le32_to_cpu(m->bytes_in_use); +static __inline__ u32 ntfs_mft_record_get_data_size(const MFT_RECORD *m) +{ + if (!m || !ntfs_is_mft_record(m->magic)) + return 0; + /* Get the number of used bytes and return it. */ + return le32_to_cpu(m->bytes_in_use); } extern int ntfs_mft_record_layout(const ntfs_volume *vol, const MFT_REF mref, - MFT_RECORD *mrec); + MFT_RECORD *mrec); extern int ntfs_mft_record_format(const ntfs_volume *vol, const MFT_REF mref); diff --git a/source/libntfs/misc.c b/source/libntfs/misc.c index 6b6dcead..8e662a6a 100644 --- a/source/libntfs/misc.c +++ b/source/libntfs/misc.c @@ -39,25 +39,27 @@ /** * ntfs_calloc - * + * * Return a pointer to the allocated memory or NULL if the request fails. */ -void *ntfs_calloc(size_t size) { - void *p; - - p = calloc(1, size); - if (!p) - ntfs_log_perror("Failed to calloc %lld bytes", (long long)size); - return p; +void *ntfs_calloc(size_t size) +{ + void *p; + + p = calloc(1, size); + if (!p) + ntfs_log_perror("Failed to calloc %lld bytes", (long long)size); + return p; } -void *ntfs_malloc(size_t size) { - void *p; - - p = malloc(size); - if (!p) - ntfs_log_perror("Failed to malloc %lld bytes", (long long)size); - return p; +void *ntfs_malloc(size_t size) +{ + void *p; + + p = malloc(size); + if (!p) + ntfs_log_perror("Failed to malloc %lld bytes", (long long)size); + return p; } /* @@ -83,36 +85,37 @@ void *ntfs_malloc(size_t size) { */ struct CACHED_GENERIC *ntfs_fetch_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *wanted, cache_compare compare) { - struct CACHED_GENERIC *current; - struct CACHED_GENERIC *previous; + const struct CACHED_GENERIC *wanted, cache_compare compare) +{ + struct CACHED_GENERIC *current; + struct CACHED_GENERIC *previous; - current = (struct CACHED_GENERIC*)NULL; - if (cache) { - /* - * Search sequentially in LRU list - */ - current = cache->most_recent_entry; - previous = (struct CACHED_GENERIC*)NULL; - while (current - && compare(current, wanted)) { - previous = current; - current = current->next; - } - if (current) - cache->hits++; - if (current && previous) { - /* - * found and not at head of list, unlink from current - * position and relink as head of list - */ - previous->next = current->next; - current->next = cache->most_recent_entry; - cache->most_recent_entry = current; - } - cache->reads++; - } - return (current); + current = (struct CACHED_GENERIC*)NULL; + if (cache) { + /* + * Search sequentially in LRU list + */ + current = cache->most_recent_entry; + previous = (struct CACHED_GENERIC*)NULL; + while (current + && compare(current, wanted)) { + previous = current; + current = current->next; + } + if (current) + cache->hits++; + if (current && previous) { + /* + * found and not at head of list, unlink from current + * position and relink as head of list + */ + previous->next = current->next; + current->next = cache->most_recent_entry; + cache->most_recent_entry = current; + } + cache->reads++; + } + return (current); } /* @@ -121,92 +124,93 @@ struct CACHED_GENERIC *ntfs_fetch_cache(struct CACHE_HEADER *cache, */ struct CACHED_GENERIC *ntfs_enter_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, cache_compare compare) { - struct CACHED_GENERIC *current; - struct CACHED_GENERIC *previous; - struct CACHED_GENERIC *before; + const struct CACHED_GENERIC *item, cache_compare compare) +{ + struct CACHED_GENERIC *current; + struct CACHED_GENERIC *previous; + struct CACHED_GENERIC *before; - current = (struct CACHED_GENERIC*)NULL; - if (cache) { + current = (struct CACHED_GENERIC*)NULL; + if (cache) { - /* - * Search sequentially in LRU list to locate the end, - * and find out whether the entry is already in list - * As we normally go to the end, no statistics is - * kept. - */ - current = cache->most_recent_entry; - previous = (struct CACHED_GENERIC*)NULL; - before = (struct CACHED_GENERIC*)NULL; - while (current - && compare(current, item)) { - before = previous; - previous = current; - current = current->next; - } + /* + * Search sequentially in LRU list to locate the end, + * and find out whether the entry is already in list + * As we normally go to the end, no statistics is + * kept. + */ + current = cache->most_recent_entry; + previous = (struct CACHED_GENERIC*)NULL; + before = (struct CACHED_GENERIC*)NULL; + while (current + && compare(current, item)) { + before = previous; + previous = current; + current = current->next; + } - if (!current) { - /* - * Not in list, get a free entry or reuse the - * last entry, and relink as head of list - * Note : we assume at least three entries, so - * before, previous and first are different when - * an entry is reused. - */ + if (!current) { + /* + * Not in list, get a free entry or reuse the + * last entry, and relink as head of list + * Note : we assume at least three entries, so + * before, previous and first are different when + * an entry is reused. + */ - if (cache->free_entry) { - current = cache->free_entry; - cache->free_entry = cache->free_entry->next; - if (item->varsize) { - current->variable = ntfs_malloc( - item->varsize); - } else - current->variable = (void*)NULL; - current->varsize = item->varsize; - } else { - before->next = (struct CACHED_GENERIC*)NULL; - current = previous; - if (item->varsize) { - if (current->varsize) - current->variable = realloc( - current->variable, - item->varsize); - else - current->variable = ntfs_malloc( - item->varsize); - } else { - if (current->varsize) - free(current->variable); - current->variable = (void*)NULL; - } - current->varsize = item->varsize; - } - current->next = cache->most_recent_entry; - cache->most_recent_entry = current; - memcpy(current->fixed, item->fixed, cache->fixed_size); - if (item->varsize) { - if (current->variable) { - memcpy(current->variable, - item->variable, item->varsize); - } else { - /* - * no more memory for variable part - * recycle entry in free list - * not an error, just uncacheable - */ - cache->most_recent_entry = current->next; - current->next = cache->free_entry; - cache->free_entry = current; - current = (struct CACHED_GENERIC*)NULL; - } - } else { - current->variable = (void*)NULL; - current->varsize = 0; - } - } - cache->writes++; - } - return (current); + if (cache->free_entry) { + current = cache->free_entry; + cache->free_entry = cache->free_entry->next; + if (item->varsize) { + current->variable = ntfs_malloc( + item->varsize); + } else + current->variable = (void*)NULL; + current->varsize = item->varsize; + } else { + before->next = (struct CACHED_GENERIC*)NULL; + current = previous; + if (item->varsize) { + if (current->varsize) + current->variable = realloc( + current->variable, + item->varsize); + else + current->variable = ntfs_malloc( + item->varsize); + } else { + if (current->varsize) + free(current->variable); + current->variable = (void*)NULL; + } + current->varsize = item->varsize; + } + current->next = cache->most_recent_entry; + cache->most_recent_entry = current; + memcpy(current->fixed, item->fixed, cache->fixed_size); + if (item->varsize) { + if (current->variable) { + memcpy(current->variable, + item->variable, item->varsize); + } else { + /* + * no more memory for variable part + * recycle entry in free list + * not an error, just uncacheable + */ + cache->most_recent_entry = current->next; + current->next = cache->free_entry; + cache->free_entry = current; + current = (struct CACHED_GENERIC*)NULL; + } + } else { + current->variable = (void*)NULL; + current->varsize = 0; + } + } + cache->writes++; + } + return (current); } /* @@ -222,60 +226,62 @@ struct CACHED_GENERIC *ntfs_enter_cache(struct CACHE_HEADER *cache, */ int ntfs_invalidate_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, cache_compare compare) { - struct CACHED_GENERIC *current; - struct CACHED_GENERIC *previous; - int count; + const struct CACHED_GENERIC *item, cache_compare compare) +{ + struct CACHED_GENERIC *current; + struct CACHED_GENERIC *previous; + int count; - current = (struct CACHED_GENERIC*)NULL; - count = 0; - if (cache) { - /* - * Search sequentially in LRU list - */ - current = cache->most_recent_entry; - previous = (struct CACHED_GENERIC*)NULL; - while (current) { - if (!compare(current, item)) { - /* - * Relink into free list - */ - if (previous) - previous->next = current->next; - else - cache->most_recent_entry = current->next; - current->next = cache->free_entry; - cache->free_entry = current; - if (current->variable) - free(current->variable); - current->varsize = 0; - if (previous) - current = previous->next; - else - current = cache->most_recent_entry; - count++; - } else { - previous = current; - current = current->next; - } - } - } - return (count); + current = (struct CACHED_GENERIC*)NULL; + count = 0; + if (cache) { + /* + * Search sequentially in LRU list + */ + current = cache->most_recent_entry; + previous = (struct CACHED_GENERIC*)NULL; + while (current) { + if (!compare(current, item)) { + /* + * Relink into free list + */ + if (previous) + previous->next = current->next; + else + cache->most_recent_entry = current->next; + current->next = cache->free_entry; + cache->free_entry = current; + if (current->variable) + free(current->variable); + current->varsize = 0; + if (previous) + current = previous->next; + else + current = cache->most_recent_entry; + count++; + } else { + previous = current; + current = current->next; + } + } + } + return (count); } /* * Free memory allocated to a cache */ -static void ntfs_free_cache(struct CACHE_HEADER *cache) { - struct CACHED_GENERIC *entry; +static void ntfs_free_cache(struct CACHE_HEADER *cache) +{ + struct CACHED_GENERIC *entry; - if (cache) { - for (entry=cache->most_recent_entry; entry; entry=entry->next) - if (entry->variable) - free(entry->variable); - free(cache); - } + if (cache) { + for (entry=cache->most_recent_entry; entry; entry=entry->next) + if (entry->variable) + free(entry->variable); + free(cache); + } } /* @@ -285,38 +291,39 @@ static void ntfs_free_cache(struct CACHE_HEADER *cache) { */ static struct CACHE_HEADER *ntfs_create_cache(const char *name, - int full_item_size, int item_count) { - struct CACHE_HEADER *cache; - struct CACHED_GENERIC *p; - struct CACHED_GENERIC *q; - int i; + int full_item_size, int item_count) +{ + struct CACHE_HEADER *cache; + struct CACHED_GENERIC *p; + struct CACHED_GENERIC *q; + int i; - cache = (struct CACHE_HEADER*) - ntfs_malloc(sizeof(struct CACHE_HEADER) - + item_count*full_item_size); - if (cache) { - cache->name = name; - cache->fixed_size = full_item_size - sizeof(struct CACHED_GENERIC); - cache->reads = 0; - cache->writes = 0; - cache->hits = 0; - /* chain the entries, and mark an invalid entry */ - cache->most_recent_entry = (struct CACHED_GENERIC*)NULL; - cache->free_entry = &cache->entry[0]; - p = &cache->entry[0]; - for (i=0; i<(item_count - 1); i++) { - q = (struct CACHED_GENERIC*)((char*)p + full_item_size); - p->next = q; - p->variable = (void*)NULL; - p->varsize = 0; - p = q; - } - /* special for the last entry */ - p->next = (struct CACHED_GENERIC*)NULL; - p->variable = (void*)NULL; - p->varsize = 0; - } - return (cache); + cache = (struct CACHE_HEADER*) + ntfs_malloc(sizeof(struct CACHE_HEADER) + + item_count*full_item_size); + if (cache) { + cache->name = name; + cache->fixed_size = full_item_size - sizeof(struct CACHED_GENERIC); + cache->reads = 0; + cache->writes = 0; + cache->hits = 0; + /* chain the entries, and mark an invalid entry */ + cache->most_recent_entry = (struct CACHED_GENERIC*)NULL; + cache->free_entry = &cache->entry[0]; + p = &cache->entry[0]; + for (i=0; i<(item_count - 1); i++) { + q = (struct CACHED_GENERIC*)((char*)p + full_item_size); + p->next = q; + p->variable = (void*)NULL; + p->varsize = 0; + p = q; + } + /* special for the last entry */ + p->next = (struct CACHED_GENERIC*)NULL; + p->variable = (void*)NULL; + p->varsize = 0; + } + return (cache); } /* @@ -326,17 +333,18 @@ static struct CACHE_HEADER *ntfs_create_cache(const char *name, * just be not available */ -void ntfs_create_lru_caches(ntfs_volume *vol) { +void ntfs_create_lru_caches(ntfs_volume *vol) +{ #if CACHE_INODE_SIZE - /* inode cache */ - vol->xinode_cache = ntfs_create_cache("inode", - sizeof(struct CACHED_INODE), CACHE_INODE_SIZE); + /* inode cache */ + vol->xinode_cache = ntfs_create_cache("inode", + sizeof(struct CACHED_INODE), CACHE_INODE_SIZE); #endif - vol->securid_cache = ntfs_create_cache("securid", - sizeof(struct CACHED_SECURID), CACHE_SECURID_SIZE); + vol->securid_cache = ntfs_create_cache("securid", + sizeof(struct CACHED_SECURID), CACHE_SECURID_SIZE); #if CACHE_LEGACY_SIZE - vol->legacy_cache = ntfs_create_cache("legacy", - sizeof(struct CACHED_PERMISSIONS_LEGACY), CACHE_LEGACY_SIZE); + vol->legacy_cache = ntfs_create_cache("legacy", + sizeof(struct CACHED_PERMISSIONS_LEGACY), CACHE_LEGACY_SIZE); #endif } @@ -344,12 +352,13 @@ void ntfs_create_lru_caches(ntfs_volume *vol) { * Free all LRU caches */ -void ntfs_free_lru_caches(ntfs_volume *vol) { +void ntfs_free_lru_caches(ntfs_volume *vol) +{ #if CACHE_INODE_SIZE - ntfs_free_cache(vol->xinode_cache); + ntfs_free_cache(vol->xinode_cache); #endif - ntfs_free_cache(vol->securid_cache); + ntfs_free_cache(vol->securid_cache); #if CACHE_LEGACY_SIZE - ntfs_free_cache(vol->legacy_cache); + ntfs_free_cache(vol->legacy_cache); #endif } diff --git a/source/libntfs/misc.h b/source/libntfs/misc.h index bacde89e..dbdee9a9 100644 --- a/source/libntfs/misc.h +++ b/source/libntfs/misc.h @@ -27,43 +27,43 @@ #include "volume.h" struct CACHED_GENERIC { - struct CACHED_GENERIC *next; - void *variable; - size_t varsize; - void *fixed[0]; + struct CACHED_GENERIC *next; + void *variable; + size_t varsize; + void *fixed[0]; } ; struct CACHED_INODE { - struct CACHED_INODE *next; - const char *pathname; - size_t varsize; - /* above fields must match "struct CACHED_GENERIC" */ - u64 inum; + struct CACHED_INODE *next; + const char *pathname; + size_t varsize; + /* above fields must match "struct CACHED_GENERIC" */ + u64 inum; } ; typedef int (*cache_compare)(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *item); + const struct CACHED_GENERIC *item); struct CACHE_HEADER { - const char *name; - struct CACHED_GENERIC *most_recent_entry; - struct CACHED_GENERIC *free_entry; - unsigned long reads; - unsigned long writes; - unsigned long hits; - int fixed_size; - struct CACHED_GENERIC entry[0]; + const char *name; + struct CACHED_GENERIC *most_recent_entry; + struct CACHED_GENERIC *free_entry; + unsigned long reads; + unsigned long writes; + unsigned long hits; + int fixed_size; + struct CACHED_GENERIC entry[0]; } ; -/* cast to generic, avoiding gcc warnings */ + /* cast to generic, avoiding gcc warnings */ #define GENERIC(pstr) ((const struct CACHED_GENERIC*)(const void*)(pstr)) struct CACHED_GENERIC *ntfs_fetch_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *wanted, cache_compare compare); + const struct CACHED_GENERIC *wanted, cache_compare compare); struct CACHED_GENERIC *ntfs_enter_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, cache_compare compare); + const struct CACHED_GENERIC *item, cache_compare compare); int ntfs_invalidate_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, cache_compare compare); + const struct CACHED_GENERIC *item, cache_compare compare); void ntfs_create_lru_caches(ntfs_volume *vol); void ntfs_free_lru_caches(ntfs_volume *vol); diff --git a/source/libntfs/mst.c b/source/libntfs/mst.c index b45ecfe0..470942d6 100644 --- a/source/libntfs/mst.c +++ b/source/libntfs/mst.c @@ -47,74 +47,75 @@ * EIO Multi sector transfer error was detected. Magic of the NTFS * record in @b will have been set to "BAAD". */ -int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size) { - u16 usa_ofs, usa_count, usn; - u16 *usa_pos, *data_pos; +int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size) +{ + u16 usa_ofs, usa_count, usn; + u16 *usa_pos, *data_pos; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); - /* Setup the variables. */ - usa_ofs = le16_to_cpu(b->usa_ofs); - /* Decrement usa_count to get number of fixups. */ - usa_count = le16_to_cpu(b->usa_count) - 1; - /* Size and alignment checks. */ - if (size & (NTFS_BLOCK_SIZE - 1) || usa_ofs & 1 || - (u32)(usa_ofs + (usa_count * 2)) > size || - (size >> NTFS_BLOCK_SIZE_BITS) != usa_count) { - errno = EINVAL; - ntfs_log_perror("%s: magic: 0x%08x size: %d usa_ofs: %d " - "usa_count: %d", __FUNCTION__, *(le32 *)b, - size, usa_ofs, usa_count); - return -1; - } - /* Position of usn in update sequence array. */ - usa_pos = (u16*)b + usa_ofs/sizeof(u16); - /* - * The update sequence number which has to be equal to each of the - * u16 values before they are fixed up. Note no need to care for - * endianness since we are comparing and moving data for on disk - * structures which means the data is consistent. - If it is - * consistency the wrong endianness it doesn't make any difference. - */ - usn = *usa_pos; - /* - * Position in protected data of first u16 that needs fixing up. - */ - data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; - /* - * Check for incomplete multi sector transfer(s). - */ - while (usa_count--) { - if (*data_pos != usn) { - /* - * Incomplete multi sector transfer detected! )-: - * Set the magic to "BAAD" and return failure. - * Note that magic_BAAD is already converted to le32. - */ - errno = EIO; - ntfs_log_perror("Incomplete multi-sector transfer: " - "magic: 0x%08x size: %d usa_ofs: %d usa_count:" - " %d data: %d usn: %d", *(le32 *)b, size, - usa_ofs, usa_count, *data_pos, usn); - b->magic = magic_BAAD; - return -1; - } - data_pos += NTFS_BLOCK_SIZE/sizeof(u16); - } - /* Re-setup the variables. */ - usa_count = le16_to_cpu(b->usa_count) - 1; - data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; - /* Fixup all sectors. */ - while (usa_count--) { - /* - * Increment position in usa and restore original data from - * the usa into the data buffer. - */ - *data_pos = *(++usa_pos); - /* Increment position in data as well. */ - data_pos += NTFS_BLOCK_SIZE/sizeof(u16); - } - return 0; + /* Setup the variables. */ + usa_ofs = le16_to_cpu(b->usa_ofs); + /* Decrement usa_count to get number of fixups. */ + usa_count = le16_to_cpu(b->usa_count) - 1; + /* Size and alignment checks. */ + if (size & (NTFS_BLOCK_SIZE - 1) || usa_ofs & 1 || + (u32)(usa_ofs + (usa_count * 2)) > size || + (size >> NTFS_BLOCK_SIZE_BITS) != usa_count) { + errno = EINVAL; + ntfs_log_perror("%s: magic: 0x%08x size: %d usa_ofs: %d " + "usa_count: %d", __FUNCTION__, *(le32 *)b, + size, usa_ofs, usa_count); + return -1; + } + /* Position of usn in update sequence array. */ + usa_pos = (u16*)b + usa_ofs/sizeof(u16); + /* + * The update sequence number which has to be equal to each of the + * u16 values before they are fixed up. Note no need to care for + * endianness since we are comparing and moving data for on disk + * structures which means the data is consistent. - If it is + * consistency the wrong endianness it doesn't make any difference. + */ + usn = *usa_pos; + /* + * Position in protected data of first u16 that needs fixing up. + */ + data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; + /* + * Check for incomplete multi sector transfer(s). + */ + while (usa_count--) { + if (*data_pos != usn) { + /* + * Incomplete multi sector transfer detected! )-: + * Set the magic to "BAAD" and return failure. + * Note that magic_BAAD is already converted to le32. + */ + errno = EIO; + ntfs_log_perror("Incomplete multi-sector transfer: " + "magic: 0x%08x size: %d usa_ofs: %d usa_count:" + " %d data: %d usn: %d", *(le32 *)b, size, + usa_ofs, usa_count, *data_pos, usn); + b->magic = magic_BAAD; + return -1; + } + data_pos += NTFS_BLOCK_SIZE/sizeof(u16); + } + /* Re-setup the variables. */ + usa_count = le16_to_cpu(b->usa_count) - 1; + data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; + /* Fixup all sectors. */ + while (usa_count--) { + /* + * Increment position in usa and restore original data from + * the usa into the data buffer. + */ + *data_pos = *(++usa_pos); + /* Increment position in data as well. */ + data_pos += NTFS_BLOCK_SIZE/sizeof(u16); + } + return 0; } /** @@ -137,57 +138,58 @@ int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size) { * otherwise a random word will be used (whatever was in the record at that * position at that time). */ -int ntfs_mst_pre_write_fixup(NTFS_RECORD *b, const u32 size) { - u16 usa_ofs, usa_count, usn; - u16 *usa_pos, *data_pos; +int ntfs_mst_pre_write_fixup(NTFS_RECORD *b, const u32 size) +{ + u16 usa_ofs, usa_count, usn; + u16 *usa_pos, *data_pos; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); - /* Sanity check + only fixup if it makes sense. */ - if (!b || ntfs_is_baad_record(b->magic) || - ntfs_is_hole_record(b->magic)) { - errno = EINVAL; - ntfs_log_perror("%s: bad argument", __FUNCTION__); - return -1; - } - /* Setup the variables. */ - usa_ofs = le16_to_cpu(b->usa_ofs); - /* Decrement usa_count to get number of fixups. */ - usa_count = le16_to_cpu(b->usa_count) - 1; - /* Size and alignment checks. */ - if (size & (NTFS_BLOCK_SIZE - 1) || usa_ofs & 1 || - (u32)(usa_ofs + (usa_count * 2)) > size || - (size >> NTFS_BLOCK_SIZE_BITS) != usa_count) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } - /* Position of usn in update sequence array. */ - usa_pos = (u16*)((u8*)b + usa_ofs); - /* - * Cyclically increment the update sequence number - * (skipping 0 and -1, i.e. 0xffff). - */ - usn = le16_to_cpup(usa_pos) + 1; - if (usn == 0xffff || !usn) - usn = 1; - usn = cpu_to_le16(usn); - *usa_pos = usn; - /* Position in data of first u16 that needs fixing up. */ - data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; - /* Fixup all sectors. */ - while (usa_count--) { - /* - * Increment the position in the usa and save the - * original data from the data buffer into the usa. - */ - *(++usa_pos) = *data_pos; - /* Apply fixup to data. */ - *data_pos = usn; - /* Increment position in data as well. */ - data_pos += NTFS_BLOCK_SIZE/sizeof(u16); - } - return 0; + /* Sanity check + only fixup if it makes sense. */ + if (!b || ntfs_is_baad_record(b->magic) || + ntfs_is_hole_record(b->magic)) { + errno = EINVAL; + ntfs_log_perror("%s: bad argument", __FUNCTION__); + return -1; + } + /* Setup the variables. */ + usa_ofs = le16_to_cpu(b->usa_ofs); + /* Decrement usa_count to get number of fixups. */ + usa_count = le16_to_cpu(b->usa_count) - 1; + /* Size and alignment checks. */ + if (size & (NTFS_BLOCK_SIZE - 1) || usa_ofs & 1 || + (u32)(usa_ofs + (usa_count * 2)) > size || + (size >> NTFS_BLOCK_SIZE_BITS) != usa_count) { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return -1; + } + /* Position of usn in update sequence array. */ + usa_pos = (u16*)((u8*)b + usa_ofs); + /* + * Cyclically increment the update sequence number + * (skipping 0 and -1, i.e. 0xffff). + */ + usn = le16_to_cpup(usa_pos) + 1; + if (usn == 0xffff || !usn) + usn = 1; + usn = cpu_to_le16(usn); + *usa_pos = usn; + /* Position in data of first u16 that needs fixing up. */ + data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; + /* Fixup all sectors. */ + while (usa_count--) { + /* + * Increment the position in the usa and save the + * original data from the data buffer into the usa. + */ + *(++usa_pos) = *data_pos; + /* Apply fixup to data. */ + *data_pos = usn; + /* Increment position in data as well. */ + data_pos += NTFS_BLOCK_SIZE/sizeof(u16); + } + return 0; } /** @@ -199,30 +201,31 @@ int ntfs_mst_pre_write_fixup(NTFS_RECORD *b, const u32 size) { * ntfs_mst_pre_write_fixup(), thus the data will be fine or we would never * have gotten here. */ -void ntfs_mst_post_write_fixup(NTFS_RECORD *b) { - u16 *usa_pos, *data_pos; +void ntfs_mst_post_write_fixup(NTFS_RECORD *b) +{ + u16 *usa_pos, *data_pos; - u16 usa_ofs = le16_to_cpu(b->usa_ofs); - u16 usa_count = le16_to_cpu(b->usa_count) - 1; + u16 usa_ofs = le16_to_cpu(b->usa_ofs); + u16 usa_count = le16_to_cpu(b->usa_count) - 1; - ntfs_log_trace("Entering\n"); + ntfs_log_trace("Entering\n"); - /* Position of usn in update sequence array. */ - usa_pos = (u16*)b + usa_ofs/sizeof(u16); + /* Position of usn in update sequence array. */ + usa_pos = (u16*)b + usa_ofs/sizeof(u16); - /* Position in protected data of first u16 that needs fixing up. */ - data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; + /* Position in protected data of first u16 that needs fixing up. */ + data_pos = (u16*)b + NTFS_BLOCK_SIZE/sizeof(u16) - 1; - /* Fixup all sectors. */ - while (usa_count--) { - /* - * Increment position in usa and restore original data from - * the usa into the data buffer. - */ - *data_pos = *(++usa_pos); + /* Fixup all sectors. */ + while (usa_count--) { + /* + * Increment position in usa and restore original data from + * the usa into the data buffer. + */ + *data_pos = *(++usa_pos); - /* Increment position in data as well. */ - data_pos += NTFS_BLOCK_SIZE/sizeof(u16); - } + /* Increment position in data as well. */ + data_pos += NTFS_BLOCK_SIZE/sizeof(u16); + } } diff --git a/source/libntfs/ntfs.c b/source/libntfs/ntfs.c index 0467db1a..85a01159 100644 --- a/source/libntfs/ntfs.c +++ b/source/libntfs/ntfs.c @@ -67,42 +67,44 @@ static const devoptab_t devops_ntfs = { NULL /* Device data */ }; -void ntfsInit (void) { +void ntfsInit (void) +{ static bool isInit = false; - + // Initialise ntfs-3g (if not already done so) if (!isInit) { isInit = true; // Set the log handler -#ifdef NTFS_ENABLE_LOG + #ifdef NTFS_ENABLE_LOG ntfs_log_set_handler(ntfs_log_handler_stderr); -#else + #else ntfs_log_set_handler(ntfs_log_handler_null); -#endif + #endif // Set our current local ntfs_set_locale(); - + } - + return; } -int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { +int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) +{ MASTER_BOOT_RECORD mbr; PARTITION_RECORD *partition = NULL; sec_t partition_starts[NTFS_MAX_PARTITIONS] = {0}; int partition_count = 0; sec_t part_lba = 0; int i; - + union { u8 buffer[BYTES_PER_SECTOR]; MASTER_BOOT_RECORD mbr; EXTENDED_BOOT_RECORD ebr; NTFS_BOOT_SECTOR boot; } sector; - + // Sanity check if (!interface) { errno = EINVAL; @@ -110,10 +112,10 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { } if (!partitions) return 0; - + // Initialise ntfs-3g ntfsInit(); - + // Start the device and check that it is inserted if (!interface->startup()) { errno = EIO; @@ -122,7 +124,7 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { if (!interface->isInserted()) { return 0; } - + // Read the first sector on the device if (!interface->readSectors(0, 1, §or.buffer)) { errno = EIO; @@ -133,12 +135,12 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { if (sector.mbr.signature == MBR_SIGNATURE) { memcpy(&mbr, §or, sizeof(MASTER_BOOT_RECORD)); ntfs_log_debug("Valid Master Boot Record found\n"); - + // Search the partition table for all NTFS partitions (max. 4 primary partitions) for (i = 0; i < 4; i++) { partition = &mbr.partitions[i]; part_lba = le32_to_cpu(mbr.partitions[i].lba_start); - + ntfs_log_debug("Partition %i: %s, sector %d, type 0x%x\n", i + 1, partition->status == PARTITION_STATUS_BOOTABLE ? "bootable (active)" : "non-bootable", part_lba, partition->type); @@ -147,13 +149,13 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { switch (partition->type) { // Ignore empty partitions - case PARTITION_TYPE_EMPTY: - continue; - + case PARTITION_TYPE_EMPTY: + continue; + // NTFS partition - case PARTITION_TYPE_NTFS: { + case PARTITION_TYPE_NTFS: { ntfs_log_debug("Partition %i: Claims to be NTFS\n", i + 1); - + // Read and validate the NTFS partition if (interface->readSectors(part_lba, 1, §or)) { if (sector.boot.oem_id == NTFS_OEM_ID) { @@ -166,28 +168,28 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { ntfs_log_debug("Partition %i: Invalid NTFS boot sector, not actually NTFS\n", i + 1); } } - + break; - + } - + // DOS 3.3+ or Windows 95 extended partition - case PARTITION_TYPE_DOS33_EXTENDED: - case PARTITION_TYPE_WIN95_EXTENDED: { + case PARTITION_TYPE_DOS33_EXTENDED: + case PARTITION_TYPE_WIN95_EXTENDED: { ntfs_log_debug("Partition %i: Claims to be Extended\n", i + 1); - + // Walk the extended partition chain, finding all NTFS partitions within it sec_t ebr_lba = part_lba; sec_t next_erb_lba = 0; do { - + // Read and validate the extended boot record if (interface->readSectors(ebr_lba + next_erb_lba, 1, §or)) { if (sector.ebr.signature == EBR_SIGNATURE) { ntfs_log_debug("Logical Partition @ %d: type 0x%x\n", ebr_lba + next_erb_lba, sector.ebr.partition.status == PARTITION_STATUS_BOOTABLE ? "bootable (active)" : "non-bootable", sector.ebr.partition.type); - + // Get the start sector of the current partition // and the next extended boot record in the chain part_lba = ebr_lba + next_erb_lba + le32_to_cpu(sector.ebr.partition.lba_start); @@ -197,7 +199,7 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { if (interface->readSectors(part_lba, 1, §or)) { if (sector.boot.oem_id == NTFS_OEM_ID) { ntfs_log_debug("Logical Partition @ %d: Valid NTFS boot sector found\n", part_lba); - if (sector.ebr.partition.type != PARTITION_TYPE_NTFS) { + if(sector.ebr.partition.type != PARTITION_TYPE_NTFS) { ntfs_log_warning("Logical Partition @ %d: Is NTFS but type is 0x%x; 0x%x was expected\n", part_lba, sector.ebr.partition.type, PARTITION_TYPE_NTFS); } if (partition_count < NTFS_MAX_PARTITIONS) { @@ -211,22 +213,22 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { next_erb_lba = 0; } } - + } while (next_erb_lba); - + break; - + } - + // Unknown or unsupported partition type - default: { - + default: { + // Check if this partition has a valid NTFS boot record anyway, // it might be misrepresented due to a lazy partition editor if (interface->readSectors(part_lba, 1, §or)) { if (sector.boot.oem_id == NTFS_OEM_ID) { ntfs_log_debug("Partition %i: Valid NTFS boot sector found\n", i + 1); - if (partition->type != PARTITION_TYPE_NTFS) { + if(partition->type != PARTITION_TYPE_NTFS) { ntfs_log_warning("Partition %i: Is NTFS but type is 0x%x; 0x%x was expected\n", i + 1, partition->type, PARTITION_TYPE_NTFS); } if (partition_count < NTFS_MAX_PARTITIONS) { @@ -235,16 +237,16 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { } } } - + break; - + } - + } - + } - - // Else it is assumed this device has no master boot record + + // Else it is assumed this device has no master boot record } else { ntfs_log_debug("No Master Boot Record was found!\n"); @@ -260,12 +262,12 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { } } } - + } // Shutdown the device /*interface->shutdown();*/ - + // Return the found partitions (if any) if (partition_count > 0) { *partitions = (sec_t*)ntfs_alloc(sizeof(sec_t) * partition_count); @@ -274,11 +276,12 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) { return partition_count; } } - + return 0; } -int ntfsMountAll (ntfs_md **mounts, u32 flags) { +int ntfsMountAll (ntfs_md **mounts, u32 flags) +{ const INTERFACE_ID *discs = ntfsGetDiscInterfaces(); const INTERFACE_ID *disc = NULL; ntfs_md mount_points[NTFS_MAX_MOUNTS]; @@ -290,7 +293,7 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) { // Initialise ntfs-3g ntfsInit(); - + // Find and mount all NTFS partitions on all known devices for (i = 0; discs[i].name != NULL && discs[i].interface != NULL; i++) { disc = &discs[i]; @@ -299,7 +302,7 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) { for (j = 0, k = 0; j < partition_count; j++) { // Find the next unused mount name - do { + do { sprintf(name, "%s%i", NTFS_MOUNT_PREFIX, k++); if (k >= NTFS_MAX_MOUNTS) { ntfs_free(partitions); @@ -317,12 +320,12 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) { mount_count++; } } - + } ntfs_free(partitions); } } - + // Return the mounts (if any) if (mount_count > 0 && mounts) { *mounts = (ntfs_md*)ntfs_alloc(sizeof(ntfs_md) * mount_count); @@ -331,11 +334,12 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) { return mount_count; } } - + return 0; } -int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flags) { +int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flags) +{ const INTERFACE_ID *discs = ntfsGetDiscInterfaces(); const INTERFACE_ID *disc = NULL; ntfs_md mount_points[NTFS_MAX_MOUNTS]; @@ -344,7 +348,7 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag int partition_count = 0; char name[128]; int i, j, k; - + // Sanity check if (!interface) { errno = EINVAL; @@ -353,7 +357,7 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag // Initialise ntfs-3g ntfsInit(); - + // Find the specified device then find and mount all NTFS partitions on it for (i = 0; discs[i].name != NULL && discs[i].interface != NULL; i++) { if (discs[i].interface == interface) { @@ -361,9 +365,9 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag partition_count = ntfsFindPartitions(disc->interface, &partitions); if (partition_count > 0 && partitions) { for (j = 0, k = 0; j < partition_count; j++) { - + // Find the next unused mount name - do { + do { sprintf(name, "%s%i", NTFS_MOUNT_PREFIX, k++); if (k >= NTFS_MAX_MOUNTS) { ntfs_free(partitions); @@ -371,7 +375,7 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag return -1; } } while (ntfsGetDevice(name, false)); - + // Mount the partition if (mount_count < NTFS_MAX_MOUNTS) { if (ntfsMount(name, disc->interface, partitions[j], CACHE_DEFAULT_PAGE_SIZE, CACHE_DEFAULT_PAGE_COUNT, flags)) { @@ -381,7 +385,7 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag mount_count++; } } - + } ntfs_free(partitions); } @@ -394,7 +398,7 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag errno = ENODEV; return -1; } - + // Return the mounts (if any) if (mount_count > 0 && mounts) { *mounts = (ntfs_md*)ntfs_alloc(sizeof(ntfs_md) * mount_count); @@ -407,16 +411,17 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag return 0; } -bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSector, u32 cachePageCount, u32 cachePageSize, u32 flags) { +bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSector, u32 cachePageCount, u32 cachePageSize, u32 flags) +{ ntfs_vd *vd = NULL; gekko_fd *fd = NULL; - + // Sanity check if (!name || !interface) { errno = EINVAL; return -1; } - + // Initialise ntfs-3g ntfsInit(); @@ -425,20 +430,20 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe errno = EADDRINUSE; return false; } - + // Check that we can at least read from this device if (!(interface->features & FEATURE_MEDIUM_CANREAD)) { errno = EPERM; return false; } - + // Allocate the volume descriptor vd = (ntfs_vd*)ntfs_alloc(sizeof(ntfs_vd)); if (!vd) { errno = ENOMEM; return false; } - + // Setup the volume descriptor vd->id = interface->ioType; vd->flags = 0; @@ -449,7 +454,7 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe vd->atime = ((flags & NTFS_UPDATE_ACCESS_TIMES) ? ATIME_ENABLED : ATIME_DISABLED); vd->showHiddenFiles = (flags & NTFS_SHOW_HIDDEN_FILES); vd->showSystemFiles = (flags & NTFS_SHOW_SYSTEM_FILES); - + // Allocate the device driver descriptor fd = (gekko_fd*)ntfs_alloc(sizeof(gekko_fd)); if (!fd) { @@ -457,7 +462,7 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe errno = ENOMEM; return false; } - + // Setup the device driver descriptor fd->interface = interface; fd->startSector = startSector; @@ -465,7 +470,7 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe fd->sectorCount = 0; fd->cachePageCount = cachePageCount; fd->cachePageSize = cachePageSize; - + // Allocate the device driver vd->dev = ntfs_device_alloc(name, 0, &ntfs_device_gekko_io_ops, fd); if (!vd->dev) { @@ -473,56 +478,47 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe ntfs_free(vd); return false; } - + // Build the mount flags if (flags & NTFS_READ_ONLY) - vd->flags |= MS_RDONLY; - else { - if (!(interface->features & FEATURE_MEDIUM_CANWRITE)) - vd->flags |= MS_RDONLY; - if ((interface->features & FEATURE_MEDIUM_CANREAD) && (interface->features & FEATURE_MEDIUM_CANWRITE)) - vd->flags |= MS_EXCLUSIVE; + vd->flags |= MS_RDONLY; + else + { + if (!(interface->features & FEATURE_MEDIUM_CANWRITE)) + vd->flags |= MS_RDONLY; + if ((interface->features & FEATURE_MEDIUM_CANREAD) && (interface->features & FEATURE_MEDIUM_CANWRITE)) + vd->flags |= MS_EXCLUSIVE; } if (flags & NTFS_RECOVER) vd->flags |= MS_RECOVER; if (flags & NTFS_IGNORE_HIBERFILE) vd->flags |= MS_IGNORE_HIBERFILE; - + if (vd->flags & MS_RDONLY) ntfs_log_debug("Mounting \"%s\" as read-only\n", name); - + // Mount the device vd->vol = ntfs_device_mount(vd->dev, vd->flags); if (!vd->vol) { - switch (ntfs_volume_error(errno)) { - case NTFS_VOLUME_NOT_NTFS: - errno = EINVALPART; - break; - case NTFS_VOLUME_CORRUPT: - errno = EINVALPART; - break; - case NTFS_VOLUME_HIBERNATED: - errno = EHIBERNATED; - break; - case NTFS_VOLUME_UNCLEAN_UNMOUNT: - errno = EDIRTY; - break; - default: - errno = EINVAL; - break; + switch(ntfs_volume_error(errno)) { + case NTFS_VOLUME_NOT_NTFS: errno = EINVALPART; break; + case NTFS_VOLUME_CORRUPT: errno = EINVALPART; break; + case NTFS_VOLUME_HIBERNATED: errno = EHIBERNATED; break; + case NTFS_VOLUME_UNCLEAN_UNMOUNT: errno = EDIRTY; break; + default: errno = EINVAL; break; } ntfs_device_free(vd->dev); ntfs_free(vd); return false; } - + // Initialise the volume descriptor if (ntfsInitVolume(vd)) { ntfs_umount(vd->vol, true); ntfs_free(vd); return false; } - + // Add the device to the devoptab table if (ntfsAddDevice(name, vd)) { ntfsDeinitVolume(vd); @@ -530,45 +526,47 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe ntfs_free(vd); return false; } - + return true; } -void ntfsUnmount (const char *name, bool force) { +void ntfsUnmount (const char *name, bool force) +{ ntfs_vd *vd = NULL; // Get the devices volume descriptor vd = ntfsGetVolume(name); if (!vd) return; - + // Remove the device from the devoptab table ntfsRemoveDevice(name); - + // Deinitialise the volume descriptor ntfsDeinitVolume(vd); - + // Unmount the volume ntfs_umount(vd->vol, force); - + // Free the volume descriptor ntfs_free(vd); - + return; } -const char *ntfsGetVolumeName (const char *name) { +const char *ntfsGetVolumeName (const char *name) +{ ntfs_vd *vd = NULL; //ntfs_attr *na = NULL; //ntfschar *ulabel = NULL; //char *volumeName = NULL; - + // Sanity check if (!name) { errno = EINVAL; return NULL; } - + // Get the devices volume descriptor vd = ntfsGetVolume(name); if (!vd) { @@ -576,78 +574,79 @@ const char *ntfsGetVolumeName (const char *name) { return NULL; } return vd->vol->vol_name; - /* - - // If the volume name has already been cached then just use that - if (vd->name[0]) - return vd->name; - - // Lock - ntfsLock(vd); - - // Check if the volume name attribute exists - na = ntfs_attr_open(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0); - if (!na) { - ntfsUnlock(vd); - errno = ENOENT; - return false; - } - - // Allocate a buffer to store the raw volume name - ulabel = ntfs_alloc(na->data_size * sizeof(ntfschar)); - if (!ulabel) { - ntfsUnlock(vd); - errno = ENOMEM; - return false; - } - - // Read the volume name - if (ntfs_attr_pread(na, 0, na->data_size, ulabel) != na->data_size) { - ntfs_free(ulabel); - ntfsUnlock(vd); - errno = EIO; - return false; - } - - // Convert the volume name to the current local - if (ntfsUnicodeToLocal(ulabel, na->data_size, &volumeName, 0) < 0) { - errno = EINVAL; - ntfs_free(ulabel); - ntfsUnlock(vd); - return false; - } - - // If the volume name was read then cache it (for future fetches) - if (volumeName) - strcpy(vd->name, volumeName); - - // Close the volume name attribute - if (na) - ntfs_attr_close(na); - - // Clean up - ntfs_free(volumeName); - ntfs_free(ulabel); - - // Unlock - ntfsUnlock(vd); - +/* + + // If the volume name has already been cached then just use that + if (vd->name[0]) return vd->name; - */ + + // Lock + ntfsLock(vd); + + // Check if the volume name attribute exists + na = ntfs_attr_open(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0); + if (!na) { + ntfsUnlock(vd); + errno = ENOENT; + return false; + } + + // Allocate a buffer to store the raw volume name + ulabel = ntfs_alloc(na->data_size * sizeof(ntfschar)); + if (!ulabel) { + ntfsUnlock(vd); + errno = ENOMEM; + return false; + } + + // Read the volume name + if (ntfs_attr_pread(na, 0, na->data_size, ulabel) != na->data_size) { + ntfs_free(ulabel); + ntfsUnlock(vd); + errno = EIO; + return false; + } + + // Convert the volume name to the current local + if (ntfsUnicodeToLocal(ulabel, na->data_size, &volumeName, 0) < 0) { + errno = EINVAL; + ntfs_free(ulabel); + ntfsUnlock(vd); + return false; + } + + // If the volume name was read then cache it (for future fetches) + if (volumeName) + strcpy(vd->name, volumeName); + + // Close the volume name attribute + if (na) + ntfs_attr_close(na); + + // Clean up + ntfs_free(volumeName); + ntfs_free(ulabel); + + // Unlock + ntfsUnlock(vd); + + return vd->name; +*/ } -bool ntfsSetVolumeName (const char *name, const char *volumeName) { +bool ntfsSetVolumeName (const char *name, const char *volumeName) +{ ntfs_vd *vd = NULL; ntfs_attr *na = NULL; ntfschar *ulabel = NULL; int ulabel_len; - + // Sanity check if (!name) { errno = EINVAL; return false; } - + // Get the devices volume descriptor vd = ntfsGetVolume(name); if (!vd) { @@ -657,7 +656,7 @@ bool ntfsSetVolumeName (const char *name, const char *volumeName) { // Lock ntfsLock(vd); - + // Convert the new volume name to unicode ulabel_len = ntfsLocalToUnicode(volumeName, &ulabel) * sizeof(ntfschar); if (ulabel_len < 0) { @@ -665,59 +664,60 @@ bool ntfsSetVolumeName (const char *name, const char *volumeName) { errno = EINVAL; return false; } - + // Check if the volume name attribute exists na = ntfs_attr_open(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0); if (na) { - + // It does, resize it to match the length of the new volume name if (ntfs_attr_truncate(na, ulabel_len)) { ntfs_free(ulabel); ntfsUnlock(vd); return false; } - + // Write the new volume name if (ntfs_attr_pwrite(na, 0, ulabel_len, ulabel) != ulabel_len) { ntfs_free(ulabel); ntfsUnlock(vd); return false; } - + } else { - + // It doesn't, create it now if (ntfs_attr_add(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0, (u8*)ulabel, ulabel_len)) { ntfs_free(ulabel); ntfsUnlock(vd); return false; } - + } // Reset the volumes name cache (as it has now been changed) vd->name[0] = '\0'; - + // Close the volume name attribute if (na) ntfs_attr_close(na); - + // Sync the volume node if (ntfs_inode_sync(vd->vol->vol_ni)) { ntfs_free(ulabel); ntfsUnlock(vd); return false; } - + // Clean up ntfs_free(ulabel); - + // Unlock ntfsUnlock(vd); - + return true; } -const devoptab_t *ntfsGetDevOpTab (void) { +const devoptab_t *ntfsGetDevOpTab (void) +{ return &devops_ntfs; } diff --git a/source/libntfs/ntfs.h b/source/libntfs/ntfs.h index d3ba9012..3df8ed75 100644 --- a/source/libntfs/ntfs.h +++ b/source/libntfs/ntfs.h @@ -30,17 +30,17 @@ extern "C" { #include #include - /* NTFS errno values */ +/* NTFS errno values */ #define ENOPART 3000 /* No partition was found */ #define EINVALPART 3001 /* Specified partition is invalid or not supported */ #define EDIRTY 3002 /* Volume is dirty and NTFS_RECOVER was not specified during mount */ #define EHIBERNATED 3003 /* Volume is hibernated and NTFS_IGNORE_HIBERFILE was not specified during mount */ - /* NTFS cache options */ +/* NTFS cache options */ #define CACHE_DEFAULT_PAGE_COUNT 8 /* The default number of pages in the cache */ #define CACHE_DEFAULT_PAGE_SIZE 128 /* The default number of sectors per cache page */ - /* NTFS mount flags */ +/* NTFS mount flags */ #define NTFS_DEFAULT 0x00000000 /* Standard mount, expects a clean, non-hibernated volume */ #define NTFS_SHOW_HIDDEN_FILES 0x00000001 /* Display hidden files when enumerating directories */ #define NTFS_SHOW_SYSTEM_FILES 0x00000002 /* Display system files when enumerating directories */ @@ -51,93 +51,93 @@ extern "C" { #define NTFS_SU NTFS_SHOW_HIDDEN_FILES & NTFS_SHOW_SYSTEM_FILES #define NTFS_FORCE NTFS_RECOVER & NTFS_IGNORE_HIBERFILE - /** - * ntfs_md - NTFS mount descriptor - */ - typedef struct _ntfs_md { - char name[32]; /* Mount name (can be accessed as "name:/") */ - const DISC_INTERFACE *interface; /* Block device containing the mounted partition */ - sec_t startSector; /* Local block address to first sector of partition */ - } ntfs_md; +/** + * ntfs_md - NTFS mount descriptor + */ +typedef struct _ntfs_md { + char name[32]; /* Mount name (can be accessed as "name:/") */ + const DISC_INTERFACE *interface; /* Block device containing the mounted partition */ + sec_t startSector; /* Local block address to first sector of partition */ +} ntfs_md; - /** - * Find all NTFS partitions on a block device. - * - * @param INTERFACE The block device to search - * @param PARTITIONS (out) A pointer to receive the array of partition start sectors - * - * @return The number of entries in PARTITIONS or -1 if an error occurred (see errno) - * @note The caller is responsible for freeing PARTITIONS when finished with it - */ - extern int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions); +/** + * Find all NTFS partitions on a block device. + * + * @param INTERFACE The block device to search + * @param PARTITIONS (out) A pointer to receive the array of partition start sectors + * + * @return The number of entries in PARTITIONS or -1 if an error occurred (see errno) + * @note The caller is responsible for freeing PARTITIONS when finished with it + */ +extern int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions); - /** - * Mount all NTFS partitions on all inserted block devices. - * - * @param MOUNTS (out) A pointer to receive the array of mount descriptors - * @param FLAGS Additional mounting flags. (see above) - * - * @return The number of entries in MOUNTS or -1 if an error occurred (see errno) - * @note The caller is responsible for freeing MOUNTS when finished with it - * @note All device caches are setup using default values (see above) - */ - extern int ntfsMountAll (ntfs_md **mounts, u32 flags); +/** + * Mount all NTFS partitions on all inserted block devices. + * + * @param MOUNTS (out) A pointer to receive the array of mount descriptors + * @param FLAGS Additional mounting flags. (see above) + * + * @return The number of entries in MOUNTS or -1 if an error occurred (see errno) + * @note The caller is responsible for freeing MOUNTS when finished with it + * @note All device caches are setup using default values (see above) + */ +extern int ntfsMountAll (ntfs_md **mounts, u32 flags); - /** - * Mount all NTFS partitions on a block devices. - * - * @param INTERFACE The block device to mount. - * @param MOUNTS (out) A pointer to receive the array of mount descriptors - * @param FLAGS Additional mounting flags. (see above) - * - * @return The number of entries in MOUNTS or -1 if an error occurred (see errno) - * @note The caller is responsible for freeing MOUNTS when finished with it - * @note The device cache is setup using default values (see above) - */ - extern int ntfsMountDevice (const DISC_INTERFACE* interface, ntfs_md **mounts, u32 flags); +/** + * Mount all NTFS partitions on a block devices. + * + * @param INTERFACE The block device to mount. + * @param MOUNTS (out) A pointer to receive the array of mount descriptors + * @param FLAGS Additional mounting flags. (see above) + * + * @return The number of entries in MOUNTS or -1 if an error occurred (see errno) + * @note The caller is responsible for freeing MOUNTS when finished with it + * @note The device cache is setup using default values (see above) + */ +extern int ntfsMountDevice (const DISC_INTERFACE* interface, ntfs_md **mounts, u32 flags); - /** - * Mount a NTFS partition from a specific sector on a block device. - * - * @param NAME The name to mount the device under (can then be accessed as "NAME:/") - * @param INTERFACE The block device to mount - * @param STARTSECTOR The sector the partition begins at (see @ntfsFindPartitions) - * @param CACHEPAGECOUNT The total number of pages in the device cache - * @param CACHEPAGESIZE The number of sectors per cache page - * @param FLAGS Additional mounting flags (see above) - * - * @return True if mount was successful, false if no partition was found or an error occurred (see errno) - * @note ntfsFindPartitions should be used first to locate the partitions start sector - */ - extern bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSector, u32 cachePageCount, u32 cachePageSize, u32 flags); +/** + * Mount a NTFS partition from a specific sector on a block device. + * + * @param NAME The name to mount the device under (can then be accessed as "NAME:/") + * @param INTERFACE The block device to mount + * @param STARTSECTOR The sector the partition begins at (see @ntfsFindPartitions) + * @param CACHEPAGECOUNT The total number of pages in the device cache + * @param CACHEPAGESIZE The number of sectors per cache page + * @param FLAGS Additional mounting flags (see above) + * + * @return True if mount was successful, false if no partition was found or an error occurred (see errno) + * @note ntfsFindPartitions should be used first to locate the partitions start sector + */ +extern bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSector, u32 cachePageCount, u32 cachePageSize, u32 flags); - /** - * Unmount a NTFS partition. - * - * @param NAME The name of mount used in ntfsMountSimple() and ntfsMount() - * @param FORCE If true unmount even if the device is busy (may lead to data lose) - */ - extern void ntfsUnmount (const char *name, bool force); +/** + * Unmount a NTFS partition. + * + * @param NAME The name of mount used in ntfsMountSimple() and ntfsMount() + * @param FORCE If true unmount even if the device is busy (may lead to data lose) + */ +extern void ntfsUnmount (const char *name, bool force); - /** - * Get the volume name of a mounted NTFS partition. - * - * @param NAME The name of mount (see @ntfsMountAll, @ntfsMountDevice, and @ntfsMount) - * - * @return The volumes name if successful or NULL if an error occurred (see errno) - */ - extern const char *ntfsGetVolumeName (const char *name); +/** + * Get the volume name of a mounted NTFS partition. + * + * @param NAME The name of mount (see @ntfsMountAll, @ntfsMountDevice, and @ntfsMount) + * + * @return The volumes name if successful or NULL if an error occurred (see errno) + */ +extern const char *ntfsGetVolumeName (const char *name); - /** - * Set the volume name of a mounted NTFS partition. - * - * @param NAME The name of mount (see @ntfsMountAll, @ntfsMountDevice, and @ntfsMount) - * @param VOLUMENAME The new volume name - * - * @return True if mount was successful, false if an error occurred (see errno) - * @note The mount must be write-enabled else this will fail - */ - extern bool ntfsSetVolumeName (const char *name, const char *volumeName); +/** + * Set the volume name of a mounted NTFS partition. + * + * @param NAME The name of mount (see @ntfsMountAll, @ntfsMountDevice, and @ntfsMount) + * @param VOLUMENAME The new volume name + * + * @return True if mount was successful, false if an error occurred (see errno) + * @note The mount must be write-enabled else this will fail + */ +extern bool ntfsSetVolumeName (const char *name, const char *volumeName); #ifdef __cplusplus } diff --git a/source/libntfs/ntfsdir.c b/source/libntfs/ntfsdir.c index 4ab646bf..0723e35a 100644 --- a/source/libntfs/ntfsdir.c +++ b/source/libntfs/ntfsdir.c @@ -47,7 +47,8 @@ #define STATE(x) ((ntfs_dir_state*)(x)->dirStruct) -void ntfsCloseDir (ntfs_dir_state *dir) { +void ntfsCloseDir (ntfs_dir_state *dir) +{ // Sanity check if (!dir || !dir->vd) return; @@ -72,7 +73,8 @@ void ntfsCloseDir (ntfs_dir_state *dir) { return; } -int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st) { +int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st) +{ // Short circuit cases were we don't actually have to do anything if (!st || !path) return 0; @@ -89,7 +91,8 @@ int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st) { return -1; } - if (strcmp(path, ".") == 0 || strcmp(path, "..") == 0) { + if(strcmp(path, ".") == 0 || strcmp(path, "..") == 0) + { memset(st, 0, sizeof(struct stat)); st->st_mode = S_IFDIR; return 0; @@ -119,7 +122,8 @@ int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st) { return 0; } -int ntfs_link_r (struct _reent *r, const char *existing, const char *newLink) { +int ntfs_link_r (struct _reent *r, const char *existing, const char *newLink) +{ ntfs_log_trace("existing %s, newLink %s\n", existing, newLink); ntfs_vd *vd = NULL; @@ -152,7 +156,8 @@ int ntfs_link_r (struct _reent *r, const char *existing, const char *newLink) { return 0; } -int ntfs_unlink_r (struct _reent *r, const char *name) { +int ntfs_unlink_r (struct _reent *r, const char *name) +{ ntfs_log_trace("name %s\n", name); // Unlink the entry @@ -163,7 +168,8 @@ int ntfs_unlink_r (struct _reent *r, const char *name) { return ret; } -int ntfs_chdir_r (struct _reent *r, const char *name) { +int ntfs_chdir_r (struct _reent *r, const char *name) +{ ntfs_log_trace("name %s\n", name); ntfs_vd *vd = NULL; @@ -208,7 +214,8 @@ int ntfs_chdir_r (struct _reent *r, const char *name) { return 0; } -int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) { +int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) +{ ntfs_log_trace("oldName %s, newName %s\n", oldName, newName); ntfs_vd *vd = NULL; @@ -225,7 +232,7 @@ int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) { ntfsLock(vd); // You cannot rename between devices - if (vd != ntfsGetVolume(newName)) { + if(vd != ntfsGetVolume(newName)) { ntfsUnlock(vd); r->_errno = EXDEV; return -1; @@ -262,7 +269,8 @@ int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) { return 0; } -int ntfs_mkdir_r (struct _reent *r, const char *path, int mode) { +int ntfs_mkdir_r (struct _reent *r, const char *path, int mode) +{ ntfs_log_trace("path %s, mode %i\n", path, mode); ntfs_vd *vd = NULL; @@ -295,7 +303,8 @@ int ntfs_mkdir_r (struct _reent *r, const char *path, int mode) { return 0; } -int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) { +int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) +{ ntfs_log_trace("path %s, buf %p\n", path, buf); ntfs_vd *vd = NULL; @@ -319,11 +328,12 @@ int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) { // Zero out the stat buffer memset(buf, 0, sizeof(struct statvfs)); - if (ntfs_volume_get_free_space(vd->vol) < 0) { - ntfsUnlock(vd); - return -1; - } - + if(ntfs_volume_get_free_space(vd->vol) < 0) + { + ntfsUnlock(vd); + return -1; + } + // File system block size buf->f_bsize = vd->vol->cluster_size; @@ -370,7 +380,8 @@ int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) { * PRIVATE: Callback for directory walking */ int ntfs_readdir_filler (DIR_ITER *dirState, const ntfschar *name, const int name_len, const int name_type, - const s64 pos, const MFT_REF mref, const unsigned dt_type) { + const s64 pos, const MFT_REF mref, const unsigned dt_type) +{ ntfs_dir_state *dir = STATE(dirState); ntfs_dir_entry *entry = NULL; char *entry_name = NULL; @@ -407,7 +418,7 @@ int ntfs_readdir_filler (DIR_ITER *dirState, const ntfschar *name, const int nam // Double check that this entry can be emuerated (as described by the volume descriptor) if (((ni->flags & FILE_ATTR_HIDDEN) && !dir->vd->showHiddenFiles) || - ((ni->flags & FILE_ATTR_SYSTEM) && !dir->vd->showSystemFiles)) { + ((ni->flags & FILE_ATTR_SYSTEM) && !dir->vd->showSystemFiles)) { ntfs_inode_close(ni); return 0; } @@ -440,7 +451,8 @@ int ntfs_readdir_filler (DIR_ITER *dirState, const ntfschar *name, const int nam return 0; } -DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path) { +DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path) +{ ntfs_log_trace("dirState %p, path %s\n", dirState, path); ntfs_dir_state* dir = STATE(dirState); @@ -505,7 +517,8 @@ DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path return dirState; } -int ntfs_dirreset_r (struct _reent *r, DIR_ITER *dirState) { +int ntfs_dirreset_r (struct _reent *r, DIR_ITER *dirState) +{ ntfs_log_trace("dirState %p\n", dirState); ntfs_dir_state* dir = STATE(dirState); @@ -531,7 +544,8 @@ int ntfs_dirreset_r (struct _reent *r, DIR_ITER *dirState) { return 0; } -int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat) { +int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat) +{ ntfs_log_trace("dirState %p, filename %p, filestat %p\n", dirState, filename, filestat); ntfs_dir_state* dir = STATE(dirState); @@ -555,11 +569,15 @@ int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct // Fetch the current entry strcpy(filename, dir->current->name); - if (filestat != NULL) { - if (strcmp(dir->current->name, ".") == 0 || strcmp(dir->current->name, "..") == 0) { + if(filestat != NULL) + { + if(strcmp(dir->current->name, ".") == 0 || strcmp(dir->current->name, "..") == 0) + { memset(filestat, 0, sizeof(struct stat)); filestat->st_mode = S_IFDIR; - } else { + } + else + { ni = ntfsOpenEntry(dir->vd, dir->current->name); if (ni) { ntfsStat(dir->vd, ni, filestat); @@ -580,7 +598,8 @@ int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct return 0; } -int ntfs_dirclose_r (struct _reent *r, DIR_ITER *dirState) { +int ntfs_dirclose_r (struct _reent *r, DIR_ITER *dirState) +{ ntfs_log_trace("dirState %p\n", dirState); ntfs_dir_state* dir = STATE(dirState); diff --git a/source/libntfs/ntfsfile.c b/source/libntfs/ntfsfile.c index 840873cc..beeb7cf4 100644 --- a/source/libntfs/ntfsfile.c +++ b/source/libntfs/ntfsfile.c @@ -6,7 +6,7 @@ * * This program/include file 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 2 of the License, or + * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program/include file is distributed in the hope that it will be @@ -44,30 +44,31 @@ #define STATE(x) ((ntfs_file_state*)x) -void ntfsCloseFile (ntfs_file_state *file) { +void ntfsCloseFile (ntfs_file_state *file) +{ // Sanity check if (!file || !file->vd) return; // Special case fix ups for compressed and/or encrypted files if (file->compressed) - ntfs_attr_pclose(file->data_na); -#ifdef HAVE_SETXATTR + ntfs_attr_pclose(file->data_na); +#ifdef HAVE_SETXATTR if (file->encrypted) ntfs_efs_fixup_attribute(NULL, file->data_na); -#endif +#endif // Close the file data attribute (if open) if (file->data_na) ntfs_attr_close(file->data_na); - + // Sync the file (and its attributes) to disc - if (file->write) + if(file->write) ntfsSync(file->vd, file->ni); - + // Close the file (if open) if (file->ni) ntfsCloseEntry(file->vd, file->ni); - + // Reset the file state file->ni = NULL; file->data_na = NULL; @@ -81,11 +82,12 @@ void ntfsCloseFile (ntfs_file_state *file) { return; } -int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) { +int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) +{ ntfs_log_trace("fileStruct %p, path %s, flags %i, mode %i\n", fileStruct, path, flags, mode); ntfs_file_state* file = STATE(fileStruct); - + // Get the volume descriptor for this path file->vd = ntfsGetVolume(path); if (!file->vd) { @@ -115,7 +117,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags ntfsUnlock(file->vd); return -1; } - + // Try and find the file and (if found) ensure that it is not a directory file->ni = ntfsOpenEntry(file->vd, path); if (file->ni && (file->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { @@ -124,10 +126,10 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EISDIR; return -1; } - + // Are we creating this file? if (flags & O_CREAT) { - + // The file SHOULD NOT already exist if (file->ni) { ntfsCloseEntry(file->vd, file->ni); @@ -135,7 +137,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EEXIST; return -1; } - + // Create the file file->ni = ntfsCreate(file->vd, path, S_IFREG, NULL); if (!file->ni) { @@ -144,17 +146,17 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags } } - + // Sanity check, the file should be open by now if (!file->ni) { ntfsUnlock(file->vd); r->_errno = ENOENT; return -1; } - + // Open the files data attribute file->data_na = ntfs_attr_open(file->ni, AT_DATA, AT_UNNAMED, 0); - if (!file->data_na) { + if(!file->data_na) { ntfsCloseEntry(file->vd, file->ni); ntfsUnlock(file->vd); return -1; @@ -163,7 +165,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags // Determine if this files data is compressed and/or encrypted file->compressed = NAttrCompressed(file->data_na) || (file->ni->flags & FILE_ATTR_COMPRESSED); file->encrypted = NAttrEncrypted(file->data_na) || (file->ni->flags & FILE_ATTR_ENCRYPTED); - + // We cannot read/write encrypted files if (file->encrypted) { ntfs_attr_close(file->data_na); @@ -172,7 +174,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EACCES; return -1; } - + // Make sure we aren't trying to write to a read-only file if ((file->ni->flags & FILE_ATTR_READONLY) && file->write) { ntfs_attr_close(file->data_na); @@ -181,7 +183,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EROFS; return -1; } - + // Truncate the file if requested if ((flags & O_TRUNC) && file->write) { if (ntfs_attr_truncate(file->data_na, 0)) { @@ -192,16 +194,16 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags return -1; } } - + // Set the files current position and length file->pos = 0; file->len = file->data_na->data_size; - + ntfs_log_trace("file->len %d\n", file->len); // Update file times ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); - + // Insert the file into the double-linked FILO list of open files if (file->vd->firstOpenFile) { file->nextOpenFile = file->vd->firstOpenFile; @@ -212,30 +214,31 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags file->prevOpenFile = NULL; file->vd->firstOpenFile = file; file->vd->openFileCount++; - + // Unlock ntfsUnlock(file->vd); - + return (int)fileStruct; } -int ntfs_close_r (struct _reent *r, int fd) { +int ntfs_close_r (struct _reent *r, int fd) +{ ntfs_log_trace("fd %p\n", fd); - + ntfs_file_state* file = STATE(fd); - + // Sanity check if (!file || !file->vd) { r->_errno = EBADF; return -1; } - + // Lock ntfsLock(file->vd); // Close the file ntfsCloseFile(file); - + // Remove the file from the double-linked FILO list of open files file->vd->openFileCount--; if (file->nextOpenFile) @@ -247,44 +250,45 @@ int ntfs_close_r (struct _reent *r, int fd) { // Unlock ntfsUnlock(file->vd); - + return 0; } -ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) { +ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) +{ ntfs_log_trace("fd %p, ptr %p, len %Li\n", fd, ptr, len); - + ntfs_file_state* file = STATE(fd); ssize_t written = 0; off_t old_pos = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Short circuit cases where we don't actually have to do anything if (!ptr || len <= 0) { return 0; } - + // Lock ntfsLock(file->vd); - + // Check that we are allowed to write to this file if (!file->write) { ntfsUnlock(file->vd); r->_errno = EACCES; return -1; } - + // If we are in append mode, backup the current position and move to the end of the file if (file->append) { old_pos = file->pos; file->pos = file->len; } - + // Write to the files data atrribute while (len) { ssize_t ret = ntfs_attr_pwrite(file->data_na, file->pos, len, ptr); @@ -297,56 +301,57 @@ ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) { file->pos += ret; written += ret; } - + // If we are in append mode, restore the current position to were it was prior to this write if (file->append) { file->pos = old_pos; } - + // Mark the file for archiving (if we actually wrote something) if (written) file->ni->flags |= FILE_ATTR_ARCHIVE; - + // Update file times (if we actually wrote something) if (written) ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_MCTIME); - + // Update the files data length file->len = file->data_na->data_size; - - // Unlock + + // Unlock ntfsUnlock(file->vd); - + return written; } -ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) { +ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) +{ ntfs_log_trace("fd %p, ptr %p, len %Li\n", fd, ptr, len); - + ntfs_file_state* file = STATE(fd); ssize_t read = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Short circuit cases where we don't actually have to do anything if (!ptr || len <= 0) { return 0; } - + // Lock ntfsLock(file->vd); - + // Check that we are allowed to read from this file if (!file->read) { ntfsUnlock(file->vd); r->_errno = EACCES; return -1; } - + // Don't read past the end of file if (file->pos + len > file->len) { r->_errno = EOVERFLOW; @@ -354,8 +359,8 @@ ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) { ntfs_log_trace("EOVERFLOW"); } - ntfs_log_trace("file->pos:%d, len:%d, file->len:%d \n", (u32)file->pos, (u32)len, (u32)file->len); - + ntfs_log_trace("file->pos:%d, len:%d, file->len:%d \n", (u32)file->pos, (u32)len, (u32)file->len); + // Read from the files data attribute while (len) { ssize_t ret = ntfs_attr_pread(file->data_na, file->pos, len, ptr); @@ -373,95 +378,92 @@ ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) { // Update file times (if we actually read something) if (read) ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); - - // Unlock + + // Unlock ntfsUnlock(file->vd); - + return read; } -off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) { +off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) +{ ntfs_log_trace("fd %p, pos %Li, dir %i\n", fd, pos, dir); - + ntfs_file_state* file = STATE(fd); off_t position = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Lock ntfsLock(file->vd); - + // Set the files current position - switch (dir) { - case SEEK_SET: - position = file->pos = MIN(MAX(pos, 0), file->len); - break; - case SEEK_CUR: - position = file->pos = MIN(MAX(file->pos + pos, 0), file->len); - break; - case SEEK_END: - position = file->pos = MIN(MAX(file->len + pos, 0), file->len); - break; + switch(dir) { + case SEEK_SET: position = file->pos = MIN(MAX(pos, 0), file->len); break; + case SEEK_CUR: position = file->pos = MIN(MAX(file->pos + pos, 0), file->len); break; + case SEEK_END: position = file->pos = MIN(MAX(file->len + pos, 0), file->len); break; } - - // Unlock + + // Unlock ntfsUnlock(file->vd); - + return position; } -int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st) { +int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st) +{ ntfs_log_trace("fd %p\n", fd); ntfs_file_state* file = STATE(fd); int ret = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Short circuit cases were we don't actually have to do anything if (!st) return 0; - + // Get the file stats ret = ntfsStat(file->vd, file->ni, st); if (ret) r->_errno = errno; - + return ret; } -int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) { +int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) +{ ntfs_log_trace("fd %p, len %Li\n", fd, len); - + ntfs_file_state* file = STATE(fd); - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Lock ntfsLock(file->vd); - + // Check that we are allowed to write to this file if (!file->write) { ntfsUnlock(file->vd); r->_errno = EACCES; return -1; } - + // For compressed files, only deleting and expanding contents are implemented if (file->compressed && - len > 0 && - len < file->data_na->initialized_size) { + len > 0 && + len < file->data_na->initialized_size) { ntfsUnlock(file->vd); r->_errno = EOPNOTSUPP; return -1; @@ -486,45 +488,46 @@ int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) { // Mark the file for archiving (if we actually changed something) if (file->len != file->data_na->data_size) file->ni->flags |= FILE_ATTR_ARCHIVE; - + // Update file times (if we actually changed something) if (file->len != file->data_na->data_size) ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_MCTIME); - + // Update the files data length file->len = file->data_na->data_size; - // Sync the file (and its attributes) to disc + // Sync the file (and its attributes) to disc ntfsSync(file->vd, file->ni); // Unlock ntfsUnlock(file->vd); - + return 0; } -int ntfs_fsync_r (struct _reent *r, int fd) { +int ntfs_fsync_r (struct _reent *r, int fd) +{ ntfs_log_trace("fd %p\n", fd); ntfs_file_state* file = STATE(fd); int ret = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Lock ntfsLock(file->vd); - + // Sync the file (and its attributes) to disc ret = ntfsSync(file->vd, file->ni); if (ret) r->_errno = errno; - + // Unlock ntfsUnlock(file->vd); - + return ret; } diff --git a/source/libntfs/ntfsfile.h b/source/libntfs/ntfsfile.h index d4675316..275c745a 100644 --- a/source/libntfs/ntfsfile.h +++ b/source/libntfs/ntfsfile.h @@ -6,7 +6,7 @@ * * This program/include file 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 2 of the License, or + * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program/include file is distributed in the hope that it will be diff --git a/source/libntfs/ntfsfile_frag.c b/source/libntfs/ntfsfile_frag.c index bdf59516..8fd75404 100644 --- a/source/libntfs/ntfsfile_frag.c +++ b/source/libntfs/ntfsfile_frag.c @@ -6,7 +6,7 @@ * * This program/include file 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 2 of the License, or + * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program/include file is distributed in the hope that it will be @@ -50,29 +50,30 @@ #if 0 -void ntfsCloseFile (ntfs_file_state *file) { +void ntfsCloseFile (ntfs_file_state *file) +{ // Sanity check if (!file || !file->vd) return; // Special case fix ups for compressed and/or encrypted files if (file->compressed) - ntfs_attr_pclose(file->data_na); + ntfs_attr_pclose(file->data_na); if (file->encrypted) ntfs_efs_fixup_attribute(NULL, file->data_na); - + // Close the file data attribute (if open) if (file->data_na) ntfs_attr_close(file->data_na); - + // Sync the file (and its attributes) to disc - if (file->write) + if(file->write) ntfsSync(file->vd, file->ni); - + // Close the file (if open) if (file->ni) ntfsCloseEntry(file->vd, file->ni); - + // Reset the file state file->ni = NULL; file->data_na = NULL; @@ -86,11 +87,12 @@ void ntfsCloseFile (ntfs_file_state *file) { return; } -int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) { +int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) +{ ntfs_log_trace("fileStruct %p, path %s, flags %i, mode %i\n", fileStruct, path, flags, mode); ntfs_file_state* file = STATE(fileStruct); - + // Get the volume descriptor for this path file->vd = ntfsGetVolume(path); if (!file->vd) { @@ -120,7 +122,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags ntfsUnlock(file->vd); return -1; } - + // Try and find the file and (if found) ensure that it is not a directory file->ni = ntfsOpenEntry(file->vd, path); if (file->ni && (file->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { @@ -129,10 +131,10 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EISDIR; return -1; } - + // Are we creating this file? if (flags & O_CREAT) { - + // The file SHOULD NOT already exist if (file->ni) { ntfsCloseEntry(file->vd, file->ni); @@ -140,7 +142,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EEXIST; return -1; } - + // Create the file file->ni = ntfsCreate(file->vd, path, S_IFREG, NULL); if (!file->ni) { @@ -149,17 +151,17 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags } } - + // Sanity check, the file should be open by now if (!file->ni) { ntfsUnlock(file->vd); r->_errno = ENOENT; return -1; } - + // Open the files data attribute file->data_na = ntfs_attr_open(file->ni, AT_DATA, AT_UNNAMED, 0); - if (!file->data_na) { + if(!file->data_na) { ntfsCloseEntry(file->vd, file->ni); ntfsUnlock(file->vd); return -1; @@ -168,7 +170,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags // Determine if this files data is compressed and/or encrypted file->compressed = NAttrCompressed(file->data_na) || (file->ni->flags & FILE_ATTR_COMPRESSED); file->encrypted = NAttrEncrypted(file->data_na) || (file->ni->flags & FILE_ATTR_ENCRYPTED); - + // We cannot read/write encrypted files if (file->encrypted) { ntfs_attr_close(file->data_na); @@ -177,7 +179,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EACCES; return -1; } - + // Make sure we aren't trying to write to a read-only file if ((file->ni->flags & FILE_ATTR_READONLY) && file->write) { ntfs_attr_close(file->data_na); @@ -186,7 +188,7 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags r->_errno = EROFS; return -1; } - + // Truncate the file if requested if ((flags & O_TRUNC) && file->write) { if (ntfs_attr_truncate(file->data_na, 0)) { @@ -197,14 +199,14 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags return -1; } } - + // Set the files current position and length file->pos = 0; file->len = file->data_na->data_size; // Update file times ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); - + // Insert the file into the double-linked FILO list of open files if (file->vd->firstOpenFile) { file->nextOpenFile = file->vd->firstOpenFile; @@ -215,30 +217,31 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags file->prevOpenFile = NULL; file->vd->firstOpenFile = file; file->vd->openFileCount++; - + // Unlock ntfsUnlock(file->vd); - + return (int)fileStruct; } -int ntfs_close_r (struct _reent *r, int fd) { +int ntfs_close_r (struct _reent *r, int fd) +{ ntfs_log_trace("fd %p\n", fd); - + ntfs_file_state* file = STATE(fd); - + // Sanity check if (!file || !file->vd) { r->_errno = EBADF; return -1; } - + // Lock ntfsLock(file->vd); // Close the file ntfsCloseFile(file); - + // Remove the file from the double-linked FILO list of open files file->vd->openFileCount--; if (file->nextOpenFile) @@ -250,44 +253,45 @@ int ntfs_close_r (struct _reent *r, int fd) { // Unlock ntfsUnlock(file->vd); - + return 0; } -ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) { +ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) +{ ntfs_log_trace("fd %p, ptr %p, len %Li\n", fd, ptr, len); - + ntfs_file_state* file = STATE(fd); ssize_t written = 0; off_t old_pos = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Short circuit cases where we don't actually have to do anything if (!ptr || len <= 0) { return 0; } - + // Lock ntfsLock(file->vd); - + // Check that we are allowed to write to this file if (!file->write) { ntfsUnlock(file->vd); r->_errno = EACCES; return -1; } - + // If we are in append mode, backup the current position and move to the end of the file if (file->append) { old_pos = file->pos; file->pos = file->len; } - + // Write to the files data atrribute while (len) { ssize_t ret = ntfs_attr_pwrite(file->data_na, file->pos, len, ptr); @@ -300,36 +304,37 @@ ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) { file->pos += ret; written += ret; } - + // If we are in append mode, restore the current position to were it was prior to this write if (file->append) { file->pos = old_pos; } - + // Mark the file for archiving (if we actually wrote something) if (written) file->ni->flags |= FILE_ATTR_ARCHIVE; - + // Update file times (if we actually wrote something) if (written) ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_MCTIME); - + // Update the files data length file->len = file->data_na->data_size; - - // Unlock + + // Unlock ntfsUnlock(file->vd); - + return written; } #endif s64 ntfs_attr_getfragments(ntfs_attr *na, const s64 pos, s64 count, u64 offset, - _ntfs_frag_append_t append_fragment, void *callback_data); + _ntfs_frag_append_t append_fragment, void *callback_data); int _NTFS_get_fragments (const char *path, - _ntfs_frag_append_t append_fragment, void *callback_data) { + _ntfs_frag_append_t append_fragment, void *callback_data) +{ struct _reent r; ntfs_file_state file_st, *file = &file_st; ssize_t read = 0; @@ -352,7 +357,7 @@ int _NTFS_get_fragments (const char *path, return 0; } */ - + // Lock ntfsLock(file->vd); @@ -363,7 +368,7 @@ int _NTFS_get_fragments (const char *path, r->_errno = EACCES; return -1; } - + // Don't read past the end of file if (file->pos + len > file->len) { r->_errno = EOVERFLOW; @@ -377,11 +382,11 @@ int _NTFS_get_fragments (const char *path, // Read from the files data attribute while (len) { s64 ret = ntfs_attr_getfragments(file->data_na, file->pos, - len, offset, append_fragment, callback_data); + len, offset, append_fragment, callback_data); if (ret <= 0 || ret > len) { //r->_errno = errno; ret_val = -14; - if (ret < 0) ret_val = ret; + if (ret < 0) ret_val = ret; goto out; } offset += ret; @@ -412,88 +417,85 @@ out: #if 0 -off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) { +off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) +{ ntfs_log_trace("fd %p, pos %Li, dir %i\n", fd, pos, dir); - + ntfs_file_state* file = STATE(fd); off_t position = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Lock ntfsLock(file->vd); - + // Set the files current position - switch (dir) { - case SEEK_SET: - position = file->pos = MIN(MAX(pos, 0), file->len); - break; - case SEEK_CUR: - position = file->pos = MIN(MAX(file->pos + pos, 0), file->len); - break; - case SEEK_END: - position = file->pos = MIN(MAX(file->len + pos, 0), file->len); - break; + switch(dir) { + case SEEK_SET: position = file->pos = MIN(MAX(pos, 0), file->len); break; + case SEEK_CUR: position = file->pos = MIN(MAX(file->pos + pos, 0), file->len); break; + case SEEK_END: position = file->pos = MIN(MAX(file->len + pos, 0), file->len); break; } - - // Unlock + + // Unlock ntfsUnlock(file->vd); - + return position; } -int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st) { +int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st) +{ ntfs_log_trace("fd %p\n", fd); ntfs_file_state* file = STATE(fd); int ret = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Short circuit cases were we don't actually have to do anything if (!st) return 0; - + // Get the file stats ret = ntfsStat(file->vd, file->ni, st); if (ret) r->_errno = errno; - + return ret; } -int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) { +int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) +{ ntfs_log_trace("fd %p, len %Li\n", fd, len); - + ntfs_file_state* file = STATE(fd); - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Lock ntfsLock(file->vd); - + // Check that we are allowed to write to this file if (!file->write) { ntfsUnlock(file->vd); r->_errno = EACCES; return -1; } - + // For compressed files, only deleting and expanding contents are implemented if (file->compressed && - len > 0 && - len < file->data_na->initialized_size) { + len > 0 && + len < file->data_na->initialized_size) { ntfsUnlock(file->vd); r->_errno = EOPNOTSUPP; return -1; @@ -518,46 +520,47 @@ int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) { // Mark the file for archiving (if we actually changed something) if (file->len != file->data_na->data_size) file->ni->flags |= FILE_ATTR_ARCHIVE; - + // Update file times (if we actually changed something) if (file->len != file->data_na->data_size) ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_MCTIME); - + // Update the files data length file->len = file->data_na->data_size; - // Sync the file (and its attributes) to disc + // Sync the file (and its attributes) to disc ntfsSync(file->vd, file->ni); // Unlock ntfsUnlock(file->vd); - + return 0; } -int ntfs_fsync_r (struct _reent *r, int fd) { +int ntfs_fsync_r (struct _reent *r, int fd) +{ ntfs_log_trace("fd %p\n", fd); ntfs_file_state* file = STATE(fd); int ret = 0; - + // Sanity check if (!file || !file->vd || !file->ni || !file->data_na) { r->_errno = EINVAL; return -1; } - + // Lock ntfsLock(file->vd); - + // Sync the file (and its attributes) to disc ret = ntfsSync(file->vd, file->ni); if (ret) r->_errno = errno; - + // Unlock ntfsUnlock(file->vd); - + return ret; } diff --git a/source/libntfs/ntfsinternal.c b/source/libntfs/ntfsinternal.c index 466f3fbd..2b11c724 100644 --- a/source/libntfs/ntfsinternal.c +++ b/source/libntfs/ntfsinternal.c @@ -62,7 +62,8 @@ const INTERFACE_ID ntfs_disc_interfaces[] = { #endif -int ntfsAddDevice (const char *name, void *deviceData) { +int ntfsAddDevice (const char *name, void *deviceData) +{ const devoptab_t *devoptab_ntfs = ntfsGetDevOpTab(); devoptab_t *dev = NULL; char *devname = NULL; @@ -103,7 +104,8 @@ int ntfsAddDevice (const char *name, void *deviceData) { return -1; } -void ntfsRemoveDevice (const char *path) { +void ntfsRemoveDevice (const char *path) +{ const devoptab_t *devoptab = NULL; char name[128] = {0}; int i; @@ -130,7 +132,8 @@ void ntfsRemoveDevice (const char *path) { return; } -const devoptab_t *ntfsGetDevice (const char *path, bool useDefaultDevice) { +const devoptab_t *ntfsGetDevice (const char *path, bool useDefaultDevice) +{ const devoptab_t *devoptab = NULL; char name[128] = {0}; int i; @@ -161,12 +164,14 @@ const devoptab_t *ntfsGetDevice (const char *path, bool useDefaultDevice) { return NULL; } -const INTERFACE_ID *ntfsGetDiscInterfaces (void) { +const INTERFACE_ID *ntfsGetDiscInterfaces (void) +{ // Get all know disc interfaces on the host system return ntfs_disc_interfaces; } -ntfs_vd *ntfsGetVolume (const char *path) { +ntfs_vd *ntfsGetVolume (const char *path) +{ // Get the volume descriptor from the paths associated devoptab (if found) const devoptab_t *devoptab_ntfs = ntfsGetDevOpTab(); const devoptab_t *devoptab = ntfsGetDevice(path, true); @@ -176,7 +181,8 @@ ntfs_vd *ntfsGetVolume (const char *path) { return NULL; } -int ntfsInitVolume (ntfs_vd *vd) { +int ntfsInitVolume (ntfs_vd *vd) +{ // Sanity check if (!vd) { errno = ENODEV; @@ -201,7 +207,8 @@ int ntfsInitVolume (ntfs_vd *vd) { return 0; } -void ntfsDeinitVolume (ntfs_vd *vd) { +void ntfsDeinitVolume (ntfs_vd *vd) +{ // Sanity check if (!vd) { errno = ENODEV; @@ -235,8 +242,8 @@ void ntfsDeinitVolume (ntfs_vd *vd) { // Close the volumes current directory (if any) //if (vd->cwd_ni) { - //ntfsCloseEntry(vd, vd->cwd_ni); - //vd->cwd_ni = NULL; + //ntfsCloseEntry(vd, vd->cwd_ni); + //vd->cwd_ni = NULL; //} // Force the underlying device to sync @@ -251,11 +258,13 @@ void ntfsDeinitVolume (ntfs_vd *vd) { return; } -ntfs_inode *ntfsOpenEntry (ntfs_vd *vd, const char *path) { +ntfs_inode *ntfsOpenEntry (ntfs_vd *vd, const char *path) +{ return ntfsParseEntry(vd, path, 1); } -ntfs_inode *ntfsParseEntry (ntfs_vd *vd, const char *path, int reparseLevel) { +ntfs_inode *ntfsParseEntry (ntfs_vd *vd, const char *path, int reparseLevel) +{ ntfs_inode *ni = NULL; char *target = NULL; int attr_size; @@ -315,7 +324,8 @@ ntfs_inode *ntfsParseEntry (ntfs_vd *vd, const char *path, int reparseLevel) { return ni; } -void ntfsCloseEntry (ntfs_vd *vd, ntfs_inode *ni) { +void ntfsCloseEntry (ntfs_vd *vd, ntfs_inode *ni) +{ // Sanity check if (!vd) { errno = ENODEV; @@ -339,7 +349,8 @@ void ntfsCloseEntry (ntfs_vd *vd, ntfs_inode *ni) { } -ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char *target) { +ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char *target) +{ ntfs_inode *dir_ni = NULL, *ni = NULL; char *dir = NULL; char *name = NULL; @@ -353,8 +364,8 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * } // You cannot link between devices - if (target) { - if (vd != ntfsGetVolume(target)) { + if(target) { + if(vd != ntfsGetVolume(target)) { errno = EXDEV; return NULL; } @@ -389,7 +400,8 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * goto cleanup; } name = strrchr(dir, '/'); - if (name) { + if(name) + { name++; name[0] = 0; } @@ -404,24 +416,24 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * switch (type) { // Symbolic link - case S_IFLNK: - if (!target) { - errno = EINVAL; - goto cleanup; - } - utarget_len = ntfsLocalToUnicode(target, &utarget); - if (utarget_len < 0) { - errno = EINVAL; - goto cleanup; - } - ni = ntfs_create_symlink(dir_ni, 0, uname, uname_len, utarget, utarget_len); - break; + case S_IFLNK: + if (!target) { + errno = EINVAL; + goto cleanup; + } + utarget_len = ntfsLocalToUnicode(target, &utarget); + if (utarget_len < 0) { + errno = EINVAL; + goto cleanup; + } + ni = ntfs_create_symlink(dir_ni, 0, uname, uname_len, utarget, utarget_len); + break; // Directory or file - case S_IFDIR: - case S_IFREG: - ni = ntfs_create(dir_ni, 0, uname, uname_len, type); - break; + case S_IFDIR: + case S_IFREG: + ni = ntfs_create(dir_ni, 0, uname, uname_len, type); + break; } @@ -444,16 +456,16 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * cleanup: - if (dir_ni) + if(dir_ni) ntfsCloseEntry(vd, dir_ni); - if (utarget) + if(utarget) ntfs_free(utarget); - if (uname) + if(uname) ntfs_free(uname); - if (dir) + if(dir) ntfs_free(dir); // Unlock @@ -462,7 +474,8 @@ cleanup: return ni; } -int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) { +int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) +{ ntfs_inode *dir_ni = NULL, *ni = NULL; char *dir = NULL; char *name = NULL; @@ -477,7 +490,7 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) { } // You cannot link between devices - if (vd != ntfsGetVolume(new_path)) { + if(vd != ntfsGetVolume(new_path)) { errno = EXDEV; return -1; } @@ -543,16 +556,16 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) { cleanup: - if (dir_ni) + if(dir_ni) ntfsCloseEntry(vd, dir_ni); - if (ni) + if(ni) ntfsCloseEntry(vd, ni); - if (uname) + if(uname) ntfs_free(uname); - if (dir) + if(dir) ntfs_free(dir); // Unlock @@ -561,7 +574,8 @@ cleanup: return res; } -int ntfsUnlink (ntfs_vd *vd, const char *path) { +int ntfsUnlink (ntfs_vd *vd, const char *path) +{ ntfs_inode *dir_ni = NULL, *ni = NULL; char *dir = NULL; char *name = NULL; @@ -603,7 +617,8 @@ int ntfsUnlink (ntfs_vd *vd, const char *path) { goto cleanup; } name = strrchr(dir, '/'); - if (name) { + if(name) + { name++; name[0] = 0; } @@ -637,16 +652,16 @@ int ntfsUnlink (ntfs_vd *vd, const char *path) { cleanup: - if (dir_ni) + if(dir_ni) ntfsCloseEntry(vd, dir_ni); - if (ni) + if(ni) ntfsCloseEntry(vd, ni); - if (uname) + if(uname) ntfs_free(uname); - if (dir) + if(dir) ntfs_free(dir); // Unlock @@ -655,7 +670,8 @@ cleanup: return 0; } -int ntfsSync (ntfs_vd *vd, ntfs_inode *ni) { +int ntfsSync (ntfs_vd *vd, ntfs_inode *ni) +{ int res = 0; // Sanity check @@ -686,7 +702,8 @@ int ntfsSync (ntfs_vd *vd, ntfs_inode *ni) { } -int ntfsStat (ntfs_vd *vd, ntfs_inode *ni, struct stat *st) { +int ntfsStat (ntfs_vd *vd, ntfs_inode *ni, struct stat *st) +{ ntfs_attr *na = NULL; int res = 0; @@ -725,7 +742,7 @@ int ntfsStat (ntfs_vd *vd, ntfs_inode *ni, struct stat *st) { ntfs_attr_close(na); } - // Else it must be a file + // Else it must be a file } else { st->st_mode = S_IFREG | (0777 & ~vd->fmask); st->st_size = ni->data_size; @@ -751,7 +768,8 @@ int ntfsStat (ntfs_vd *vd, ntfs_inode *ni, struct stat *st) { return res; } -void ntfsUpdateTimes (ntfs_vd *vd, ntfs_inode *ni, ntfs_time_update_flags mask) { +void ntfsUpdateTimes (ntfs_vd *vd, ntfs_inode *ni, ntfs_time_update_flags mask) +{ // Run the access time update strategy against the device driver settings first if (vd && vd->atime == ATIME_DISABLED) mask &= ~NTFS_UPDATE_ATIME; @@ -763,7 +781,8 @@ void ntfsUpdateTimes (ntfs_vd *vd, ntfs_inode *ni, ntfs_time_update_flags mask) return; } -const char *ntfsRealPath (const char *path) { +const char *ntfsRealPath (const char *path) +{ // Sanity check if (!path) return NULL; @@ -779,7 +798,8 @@ const char *ntfsRealPath (const char *path) { return path; } -int ntfsUnicodeToLocal (const ntfschar *ins, const int ins_len, char **outs, int outs_len) { +int ntfsUnicodeToLocal (const ntfschar *ins, const int ins_len, char **outs, int outs_len) +{ int len = 0; int i; @@ -816,7 +836,8 @@ int ntfsUnicodeToLocal (const ntfschar *ins, const int ins_len, char **outs, int return len; } -int ntfsLocalToUnicode (const char *ins, ntfschar **outs) { +int ntfsLocalToUnicode (const char *ins, ntfschar **outs) +{ // Sanity check if (!ins || !outs) return 0; diff --git a/source/libntfs/ntfsinternal.h b/source/libntfs/ntfsinternal.h index e6a4a28d..11dfb8fd 100644 --- a/source/libntfs/ntfsinternal.h +++ b/source/libntfs/ntfsinternal.h @@ -139,12 +139,14 @@ typedef struct _ntfs_vd { } ntfs_vd; /* Lock volume */ -static inline void ntfsLock (ntfs_vd *vd) { +static inline void ntfsLock (ntfs_vd *vd) +{ LWP_MutexLock(vd->lock); } /* Unlock volume */ -static inline void ntfsUnlock (ntfs_vd *vd) { +static inline void ntfsUnlock (ntfs_vd *vd) +{ LWP_MutexUnlock(vd->lock); } diff --git a/source/libntfs/ntfstime.h b/source/libntfs/ntfstime.h index 86dcf731..e933b53c 100644 --- a/source/libntfs/ntfstime.h +++ b/source/libntfs/ntfstime.h @@ -40,8 +40,9 @@ * * Return: n A Unix time (number of seconds since 1970) */ -static __inline__ time_t ntfs2utc(s64 ntfs_time) { - return (sle64_to_cpu(ntfs_time) - (NTFS_TIME_OFFSET)) / 10000000; +static __inline__ time_t ntfs2utc(s64 ntfs_time) +{ + return (sle64_to_cpu(ntfs_time) - (NTFS_TIME_OFFSET)) / 10000000; } /** @@ -59,9 +60,10 @@ static __inline__ time_t ntfs2utc(s64 ntfs_time) { * * Return: n An NTFS time (100ns units since Jan 1601) */ -static __inline__ s64 utc2ntfs(time_t utc_time) { - /* Convert to 100ns intervals and then add the NTFS time offset. */ - return cpu_to_sle64((s64)utc_time * 10000000 + NTFS_TIME_OFFSET); +static __inline__ s64 utc2ntfs(time_t utc_time) +{ + /* Convert to 100ns intervals and then add the NTFS time offset. */ + return cpu_to_sle64((s64)utc_time * 10000000 + NTFS_TIME_OFFSET); } #endif /* _NTFS_NTFSTIME_H */ diff --git a/source/libntfs/reparse.c b/source/libntfs/reparse.c index eedfac61..80a25acb 100644 --- a/source/libntfs/reparse.c +++ b/source/libntfs/reparse.c @@ -73,58 +73,57 @@ #define IO_REPARSE_TAG_SYMLINK const_cpu_to_le32(0xA000000C) struct MOUNT_POINT_REPARSE_DATA { /* reparse data for junctions */ - le16 subst_name_offset; - le16 subst_name_length; - le16 print_name_offset; - le16 print_name_length; - char path_buffer[0]; /* above data assume this is char array */ + le16 subst_name_offset; + le16 subst_name_length; + le16 print_name_offset; + le16 print_name_length; + char path_buffer[0]; /* above data assume this is char array */ } ; struct SYMLINK_REPARSE_DATA { /* reparse data for symlinks */ - le16 subst_name_offset; - le16 subst_name_length; - le16 print_name_offset; - le16 print_name_length; - le32 flags; /* 1 for full target, otherwise 0 */ - char path_buffer[0]; /* above data assume this is char array */ + le16 subst_name_offset; + le16 subst_name_length; + le16 print_name_offset; + le16 print_name_length; + le32 flags; /* 1 for full target, otherwise 0 */ + char path_buffer[0]; /* above data assume this is char array */ } ; struct INODE_STACK { - struct INODE_STACK *previous; - struct INODE_STACK *next; - ntfs_inode *ni; + struct INODE_STACK *previous; + struct INODE_STACK *next; + ntfs_inode *ni; } ; struct REPARSE_INDEX { /* index entry in $Extend/$Reparse */ - INDEX_ENTRY_HEADER header; - REPARSE_INDEX_KEY key; - le32 filling; + INDEX_ENTRY_HEADER header; + REPARSE_INDEX_KEY key; + le32 filling; } ; static const ntfschar dir_junction_head[] = { - const_cpu_to_le16('\\'), - const_cpu_to_le16('?'), - const_cpu_to_le16('?'), - const_cpu_to_le16('\\') + const_cpu_to_le16('\\'), + const_cpu_to_le16('?'), + const_cpu_to_le16('?'), + const_cpu_to_le16('\\') } ; static const ntfschar vol_junction_head[] = { - const_cpu_to_le16('\\'), - const_cpu_to_le16('?'), - const_cpu_to_le16('?'), - const_cpu_to_le16('\\'), - const_cpu_to_le16('V'), - const_cpu_to_le16('o'), - const_cpu_to_le16('l'), - const_cpu_to_le16('u'), - const_cpu_to_le16('m'), - const_cpu_to_le16('e'), - const_cpu_to_le16('{'), + const_cpu_to_le16('\\'), + const_cpu_to_le16('?'), + const_cpu_to_le16('?'), + const_cpu_to_le16('\\'), + const_cpu_to_le16('V'), + const_cpu_to_le16('o'), + const_cpu_to_le16('l'), + const_cpu_to_le16('u'), + const_cpu_to_le16('m'), + const_cpu_to_le16('e'), + const_cpu_to_le16('{'), } ; static ntfschar reparse_index_name[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('R') - }; + const_cpu_to_le16('R') }; static const char mappingdir[] = ".NTFS-3G/"; @@ -142,80 +141,81 @@ static const char mappingdir[] = ".NTFS-3G/"; */ static u64 ntfs_fix_file_name(ntfs_inode *dir_ni, ntfschar *uname, - int uname_len) { - ntfs_volume *vol = dir_ni->vol; - ntfs_index_context *icx; - u64 mref; - le64 lemref; - int lkup; - int olderrno; - int i; - u32 cpuchar; - INDEX_ENTRY *entry; - FILE_NAME_ATTR *found; - struct { - FILE_NAME_ATTR attr; - ntfschar file_name[NTFS_MAX_NAME_LEN + 1]; - } find; + int uname_len) +{ + ntfs_volume *vol = dir_ni->vol; + ntfs_index_context *icx; + u64 mref; + le64 lemref; + int lkup; + int olderrno; + int i; + u32 cpuchar; + INDEX_ENTRY *entry; + FILE_NAME_ATTR *found; + struct { + FILE_NAME_ATTR attr; + ntfschar file_name[NTFS_MAX_NAME_LEN + 1]; + } find; - mref = (u64)-1; /* default return (not found) */ - icx = ntfs_index_ctx_get(dir_ni, NTFS_INDEX_I30, 4); - if (icx) { - if (uname_len > NTFS_MAX_NAME_LEN) - uname_len = NTFS_MAX_NAME_LEN; - find.attr.file_name_length = uname_len; - for (i=0; iupcase_len) - && (le16_to_cpu(vol->upcase[cpuchar]) < cpuchar)) - find.attr.file_name[i] = vol->upcase[cpuchar]; - else - find.attr.file_name[i] = uname[i]; - } - olderrno = errno; - lkup = ntfs_index_lookup((char*)&find, uname_len, icx); - if (errno == ENOENT) - errno = olderrno; - /* - * We generally only get the first matching candidate, - * so we still have to check whether this is a real match - */ - if (icx->entry && (icx->entry->ie_flags & INDEX_ENTRY_END)) - /* get next entry if reaching end of block */ - entry = ntfs_index_next(icx->entry, icx); - else - entry = icx->entry; - if (entry) { - found = &entry->key.file_name; - if (lkup - && !ntfs_names_collate(find.attr.file_name, - find.attr.file_name_length, - found->file_name, found->file_name_length, - 1, IGNORE_CASE, - vol->upcase, vol->upcase_len)) - lkup = 0; - if (!lkup) { - /* - * name found : - * fix original name and return inode - */ - lemref = *(le64*)((char*)found->file_name - - sizeof(INDEX_ENTRY_HEADER) - - sizeof(FILE_NAME_ATTR)); - mref = le64_to_cpu(lemref); - for (i=0; ifile_name_length; i++) - uname[i] = found->file_name[i]; - } - } - ntfs_index_ctx_put(icx); - } - return (mref); + mref = (u64)-1; /* default return (not found) */ + icx = ntfs_index_ctx_get(dir_ni, NTFS_INDEX_I30, 4); + if (icx) { + if (uname_len > NTFS_MAX_NAME_LEN) + uname_len = NTFS_MAX_NAME_LEN; + find.attr.file_name_length = uname_len; + for (i=0; iupcase_len) + && (le16_to_cpu(vol->upcase[cpuchar]) < cpuchar)) + find.attr.file_name[i] = vol->upcase[cpuchar]; + else + find.attr.file_name[i] = uname[i]; + } + olderrno = errno; + lkup = ntfs_index_lookup((char*)&find, uname_len, icx); + if (errno == ENOENT) + errno = olderrno; + /* + * We generally only get the first matching candidate, + * so we still have to check whether this is a real match + */ + if (icx->entry && (icx->entry->ie_flags & INDEX_ENTRY_END)) + /* get next entry if reaching end of block */ + entry = ntfs_index_next(icx->entry, icx); + else + entry = icx->entry; + if (entry) { + found = &entry->key.file_name; + if (lkup + && !ntfs_names_collate(find.attr.file_name, + find.attr.file_name_length, + found->file_name, found->file_name_length, + 1, IGNORE_CASE, + vol->upcase, vol->upcase_len)) + lkup = 0; + if (!lkup) { + /* + * name found : + * fix original name and return inode + */ + lemref = *(le64*)((char*)found->file_name + - sizeof(INDEX_ENTRY_HEADER) + - sizeof(FILE_NAME_ATTR)); + mref = le64_to_cpu(lemref); + for (i=0; ifile_name_length; i++) + uname[i] = found->file_name[i]; + } + } + ntfs_index_ctx_put(icx); + } + return (mref); } /* @@ -227,47 +227,48 @@ static u64 ntfs_fix_file_name(ntfs_inode *dir_ni, ntfschar *uname, */ static char *search_absolute(ntfs_volume *vol, ntfschar *path, - int count, BOOL isdir) { - ntfs_inode *ni; - u64 inum; - char *target; - int start; - int len; + int count, BOOL isdir) +{ + ntfs_inode *ni; + u64 inum; + char *target; + int start; + int len; - target = (char*)NULL; /* default return */ - ni = ntfs_inode_open(vol, (MFT_REF)FILE_root); - if (ni) { - start = 0; - do { - len = 0; - while (((start + len) < count) - && (path[start + len] != const_cpu_to_le16('\\'))) - len++; - inum = ntfs_fix_file_name(ni, &path[start], len); - ntfs_inode_close(ni); - ni = (ntfs_inode*)NULL; - if (inum != (u64)-1) { - inum = MREF(inum); - ni = ntfs_inode_open(vol, inum); - start += len; - if (start < count) - path[start++] = const_cpu_to_le16('/'); - } - } while (ni - && (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - && (start < count)); - if (ni - && (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY ? isdir : !isdir)) - if (ntfs_ucstombs(path, count, &target, 0) < 0) { - if (target) { - free(target); - target = (char*)NULL; - } - } - if (ni) - ntfs_inode_close(ni); - } - return (target); + target = (char*)NULL; /* default return */ + ni = ntfs_inode_open(vol, (MFT_REF)FILE_root); + if (ni) { + start = 0; + do { + len = 0; + while (((start + len) < count) + && (path[start + len] != const_cpu_to_le16('\\'))) + len++; + inum = ntfs_fix_file_name(ni, &path[start], len); + ntfs_inode_close(ni); + ni = (ntfs_inode*)NULL; + if (inum != (u64)-1) { + inum = MREF(inum); + ni = ntfs_inode_open(vol, inum); + start += len; + if (start < count) + path[start++] = const_cpu_to_le16('/'); + } + } while (ni + && (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + && (start < count)); + if (ni + && (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY ? isdir : !isdir)) + if (ntfs_ucstombs(path, count, &target, 0) < 0) { + if (target) { + free(target); + target = (char*)NULL; + } + } + if (ni) + ntfs_inode_close(ni); + } + return (target); } /* @@ -278,26 +279,27 @@ static char *search_absolute(ntfs_volume *vol, ntfschar *path, */ static struct INODE_STACK *stack_inode(struct INODE_STACK *topni, - ntfschar *name, int len, BOOL fix) { - struct INODE_STACK *curni; - u64 inum; + ntfschar *name, int len, BOOL fix) +{ + struct INODE_STACK *curni; + u64 inum; - if (fix) - inum = ntfs_fix_file_name(topni->ni, name, len); - else - inum = ntfs_inode_lookup_by_name(topni->ni, name, len); - if (inum != (u64)-1) { - inum = MREF(inum); - curni = (struct INODE_STACK*)malloc(sizeof(struct INODE_STACK)); - if (curni) { - curni->ni = ntfs_inode_open(topni->ni->vol, inum); - topni->next = curni; - curni->previous = topni; - curni->next = (struct INODE_STACK*)NULL; - } - } else - curni = (struct INODE_STACK*)NULL; - return (curni); + if (fix) + inum = ntfs_fix_file_name(topni->ni, name, len); + else + inum = ntfs_inode_lookup_by_name(topni->ni, name, len); + if (inum != (u64)-1) { + inum = MREF(inum); + curni = (struct INODE_STACK*)malloc(sizeof(struct INODE_STACK)); + if (curni) { + curni->ni = ntfs_inode_open(topni->ni->vol, inum); + topni->next = curni; + curni->previous = topni; + curni->next = (struct INODE_STACK*)NULL; + } + } else + curni = (struct INODE_STACK*)NULL; + return (curni); } /* @@ -307,21 +309,22 @@ static struct INODE_STACK *stack_inode(struct INODE_STACK *topni, * or NULL (with stack unchanged) if there is a problem */ -static struct INODE_STACK *pop_inode(struct INODE_STACK *topni) { - struct INODE_STACK *curni; +static struct INODE_STACK *pop_inode(struct INODE_STACK *topni) +{ + struct INODE_STACK *curni; - curni = (struct INODE_STACK*)NULL; - if (topni->previous) { - if (!ntfs_inode_close(topni->ni)) { - curni = topni->previous; - free(topni); - curni->next = (struct INODE_STACK*)NULL; - } - } else { - /* ".." reached the root of fs */ - errno = ENOENT; - } - return (curni); + curni = (struct INODE_STACK*)NULL; + if (topni->previous) { + if (!ntfs_inode_close(topni->ni)) { + curni = topni->previous; + free(topni); + curni->next = (struct INODE_STACK*)NULL; + } + } else { + /* ".." reached the root of fs */ + errno = ENOENT; + } + return (curni); } /* @@ -333,117 +336,118 @@ static struct INODE_STACK *pop_inode(struct INODE_STACK *topni) { */ static char *search_relative(ntfs_volume *vol, ntfschar *path, int count, - const char *base, BOOL isdir) { - struct INODE_STACK *topni; - struct INODE_STACK *curni; - char *target; - ntfschar *unicode; - int unisz; - int start; - int len; + const char *base, BOOL isdir) +{ + struct INODE_STACK *topni; + struct INODE_STACK *curni; + char *target; + ntfschar *unicode; + int unisz; + int start; + int len; - target = (char*)NULL; /* default return */ - topni = (struct INODE_STACK*)malloc(sizeof(struct INODE_STACK)); - if (topni) { - topni->ni = ntfs_inode_open(vol, FILE_root); - topni->previous = (struct INODE_STACK*)NULL; - topni->next = (struct INODE_STACK*)NULL; - } - if (topni && topni->ni) { - /* - * Process the base path - */ - unicode = (ntfschar*)NULL; - unisz = ntfs_mbstoucs(base, &unicode); - if ((unisz > 0) && unicode) { - start = 1; - do { - len = 0; - while (((start + len) < unisz) - && (unicode[start + len] - != const_cpu_to_le16('/'))) - len++; - curni = (struct INODE_STACK*)NULL; - if ((start + len) < unisz) { - curni = stack_inode(topni, - &unicode[start], len, FALSE); - if (curni) - topni = curni; - } else - curni = topni; - start += len + 1; - } while (curni - && topni->ni - && (topni->ni->mrec->flags - & MFT_RECORD_IS_DIRECTORY) - && (start < unisz)); - free(unicode); - if (curni - && topni->ni - && (topni->ni->mrec->flags - & MFT_RECORD_IS_DIRECTORY)) { - start = 0; - do { - len = 0; - while (((start + len) < count) - && (path[start + len] - != const_cpu_to_le16('\\'))) - len++; - curni = (struct INODE_STACK*)NULL; - if ((path[start] - == const_cpu_to_le16('.')) - && ((len == 1) - || ((len == 2) - && (path[start+1] - == const_cpu_to_le16('.'))))) { - /* leave the .. or . in the path */ - curni = topni; - if (len == 2) { - curni = pop_inode(topni); - if (curni) - topni = curni; - } - } else { - curni = stack_inode(topni, - &path[start], len, TRUE); - if (curni) - topni = curni; - } - if (topni->ni) { - start += len; - if (start < count) - path[start++] - = const_cpu_to_le16('/'); - } - } while (curni - && topni->ni - && (topni->ni->mrec->flags - & MFT_RECORD_IS_DIRECTORY) - && (start < count)); - if (curni - && topni->ni - && (topni->ni->mrec->flags - & MFT_RECORD_IS_DIRECTORY - ? isdir : !isdir)) { - if (ntfs_ucstombs(path, count, - &target, 0) < 0) { - if (target) { - free(target); - target = (char*)NULL; - } - } - } - } - } - do { - if (topni->ni) - ntfs_inode_close(topni->ni); - curni = topni; - topni = topni->previous; - free(curni); - } while (topni); - } - return (target); + target = (char*)NULL; /* default return */ + topni = (struct INODE_STACK*)malloc(sizeof(struct INODE_STACK)); + if (topni) { + topni->ni = ntfs_inode_open(vol, FILE_root); + topni->previous = (struct INODE_STACK*)NULL; + topni->next = (struct INODE_STACK*)NULL; + } + if (topni && topni->ni) { + /* + * Process the base path + */ + unicode = (ntfschar*)NULL; + unisz = ntfs_mbstoucs(base, &unicode); + if ((unisz > 0) && unicode) { + start = 1; + do { + len = 0; + while (((start + len) < unisz) + && (unicode[start + len] + != const_cpu_to_le16('/'))) + len++; + curni = (struct INODE_STACK*)NULL; + if ((start + len) < unisz) { + curni = stack_inode(topni, + &unicode[start], len, FALSE); + if (curni) + topni = curni; + } else + curni = topni; + start += len + 1; + } while (curni + && topni->ni + && (topni->ni->mrec->flags + & MFT_RECORD_IS_DIRECTORY) + && (start < unisz)); + free(unicode); + if (curni + && topni->ni + && (topni->ni->mrec->flags + & MFT_RECORD_IS_DIRECTORY)) { + start = 0; + do { + len = 0; + while (((start + len) < count) + && (path[start + len] + != const_cpu_to_le16('\\'))) + len++; + curni = (struct INODE_STACK*)NULL; + if ((path[start] + == const_cpu_to_le16('.')) + && ((len == 1) + || ((len == 2) + && (path[start+1] + == const_cpu_to_le16('.'))))) { + /* leave the .. or . in the path */ + curni = topni; + if (len == 2) { + curni = pop_inode(topni); + if (curni) + topni = curni; + } + } else { + curni = stack_inode(topni, + &path[start], len, TRUE); + if (curni) + topni = curni; + } + if (topni->ni) { + start += len; + if (start < count) + path[start++] + = const_cpu_to_le16('/'); + } + } while (curni + && topni->ni + && (topni->ni->mrec->flags + & MFT_RECORD_IS_DIRECTORY) + && (start < count)); + if (curni + && topni->ni + && (topni->ni->mrec->flags + & MFT_RECORD_IS_DIRECTORY + ? isdir : !isdir)) { + if (ntfs_ucstombs(path, count, + &target, 0) < 0) { + if (target) { + free(target); + target = (char*)NULL; + } + } + } + } + } + do { + if (topni->ni) + ntfs_inode_close(topni->ni); + curni = topni; + topni = topni->previous; + free(curni); + } while (topni); + } + return (target); } /* @@ -454,37 +458,38 @@ static char *search_relative(ntfs_volume *vol, ntfschar *path, int count, * -1 if there was an error (described by errno) */ -static int ntfs_drive_letter(ntfs_volume *vol, ntfschar letter) { - char defines[NTFS_MAX_NAME_LEN + 5]; - char *drive; - int ret; - int sz; - int olderrno; - ntfs_inode *ni; +static int ntfs_drive_letter(ntfs_volume *vol, ntfschar letter) +{ + char defines[NTFS_MAX_NAME_LEN + 5]; + char *drive; + int ret; + int sz; + int olderrno; + ntfs_inode *ni; - ret = -1; - drive = (char*)NULL; - sz = ntfs_ucstombs(&letter, 1, &drive, 0); - if (sz > 0) { - strcpy(defines,mappingdir); - if ((*drive >= 'a') && (*drive <= 'z')) - *drive += 'A' - 'a'; - strcat(defines,drive); - strcat(defines,":"); - olderrno = errno; - ni = ntfs_pathname_to_inode(vol, NULL, defines); - if (ni && !ntfs_inode_close(ni)) - ret = 1; - else - if (errno == ENOENT) { - ret = 0; - /* avoid errno pollution */ - errno = olderrno; - } - } - if (drive) - free(drive); - return (ret); + ret = -1; + drive = (char*)NULL; + sz = ntfs_ucstombs(&letter, 1, &drive, 0); + if (sz > 0) { + strcpy(defines,mappingdir); + if ((*drive >= 'a') && (*drive <= 'z')) + *drive += 'A' - 'a'; + strcat(defines,drive); + strcat(defines,":"); + olderrno = errno; + ni = ntfs_pathname_to_inode(vol, NULL, defines); + if (ni && !ntfs_inode_close(ni)) + ret = 1; + else + if (errno == ENOENT) { + ret = 0; + /* avoid errno pollution */ + errno = olderrno; + } + } + if (drive) + free(drive); + return (ret); } /* @@ -504,110 +509,111 @@ static int ntfs_drive_letter(ntfs_volume *vol, ntfschar letter) { static char *ntfs_get_fulllink(ntfs_volume *vol, ntfschar *junction, - int count, const char *path, BOOL isdir) { - char *target; - char *fulltarget; - int i; - int sz; - int level; - const char *p; - char *q; - enum { DIR_JUNCTION, VOL_JUNCTION, NO_JUNCTION } kind; + int count, const char *path, BOOL isdir) +{ + char *target; + char *fulltarget; + int i; + int sz; + int level; + const char *p; + char *q; + enum { DIR_JUNCTION, VOL_JUNCTION, NO_JUNCTION } kind; - target = (char*)NULL; - fulltarget = (char*)NULL; - /* - * For a valid directory junction we want \??\x:\ - * where \ is an individual char and x a non-null char - */ - if ((count >= 7) - && !memcmp(junction,dir_junction_head,8) - && junction[4] - && (junction[5] == const_cpu_to_le16(':')) - && (junction[6] == const_cpu_to_le16('\\'))) - kind = DIR_JUNCTION; - else - /* - * For a valid volume junction we want \\?\Volume{ - * and a final \ (where \ is an individual char) - */ - if ((count >= 12) - && !memcmp(junction,vol_junction_head,22) - && (junction[count-1] == const_cpu_to_le16('\\'))) - kind = VOL_JUNCTION; - else - kind = NO_JUNCTION; - /* - * Directory junction with an explicit path and - * no specific definition for the drive letter : - * try to interpret as a target on the same volume - */ - if ((kind == DIR_JUNCTION) - && (count >= 7) - && junction[7] - && !ntfs_drive_letter(vol, junction[4])) { - target = search_absolute(vol,&junction[7],count - 7, isdir); - if (target) { - level = 0; - for (p=path; *p; p++) - if (*p == '/') - level++; - fulltarget = (char*)ntfs_malloc(3*level - + strlen(target) + 1); - if (fulltarget) { - fulltarget[0] = 0; - if (level > 1) { - for (i=1; i 0) && target) { - /* reverse slashes */ - for (q=target; *q; q++) - if (*q == '\\') - *q = '/'; - /* force uppercase drive letter */ - if ((target[1] == ':') - && (target[0] >= 'a') - && (target[0] <= 'z')) - target[0] += 'A' - 'a'; - level = 0; - for (p=path; *p; p++) - if (*p == '/') - level++; - fulltarget = (char*)ntfs_malloc(3*level - + sizeof(mappingdir) + strlen(target) - 3); - if (fulltarget) { - fulltarget[0] = 0; - if (level > 1) { - for (i=1; i= 7) + && !memcmp(junction,dir_junction_head,8) + && junction[4] + && (junction[5] == const_cpu_to_le16(':')) + && (junction[6] == const_cpu_to_le16('\\'))) + kind = DIR_JUNCTION; + else + /* + * For a valid volume junction we want \\?\Volume{ + * and a final \ (where \ is an individual char) + */ + if ((count >= 12) + && !memcmp(junction,vol_junction_head,22) + && (junction[count-1] == const_cpu_to_le16('\\'))) + kind = VOL_JUNCTION; + else + kind = NO_JUNCTION; + /* + * Directory junction with an explicit path and + * no specific definition for the drive letter : + * try to interpret as a target on the same volume + */ + if ((kind == DIR_JUNCTION) + && (count >= 7) + && junction[7] + && !ntfs_drive_letter(vol, junction[4])) { + target = search_absolute(vol,&junction[7],count - 7, isdir); + if (target) { + level = 0; + for (p=path; *p; p++) + if (*p == '/') + level++; + fulltarget = (char*)ntfs_malloc(3*level + + strlen(target) + 1); + if (fulltarget) { + fulltarget[0] = 0; + if (level > 1) { + for (i=1; i 0) && target) { + /* reverse slashes */ + for (q=target; *q; q++) + if (*q == '\\') + *q = '/'; + /* force uppercase drive letter */ + if ((target[1] == ':') + && (target[0] >= 'a') + && (target[0] <= 'z')) + target[0] += 'A' - 'a'; + level = 0; + for (p=path; *p; p++) + if (*p == '/') + level++; + fulltarget = (char*)ntfs_malloc(3*level + + sizeof(mappingdir) + strlen(target) - 3); + if (fulltarget) { + fulltarget[0] = 0; + if (level > 1) { + for (i=1; i= 3) - && junction[0] - && (junction[1] == const_cpu_to_le16(':')) - && (junction[2] == const_cpu_to_le16('\\'))) - kind = FULL_PATH; - else - /* - * For an absolute path we want an initial \ - */ - if ((count >= 0) - && (junction[0] == const_cpu_to_le16('\\'))) - kind = ABS_PATH; - else - kind = REJECTED_PATH; - /* - * Full path, with a drive letter and - * no specific definition for the drive letter : - * try to interpret as a target on the same volume. - * Do the same for an abs path with no drive letter. - */ - if (((kind == FULL_PATH) - && (count >= 3) - && junction[3] - && !ntfs_drive_letter(vol, junction[0])) - || (kind == ABS_PATH)) { - if (kind == ABS_PATH) - target = search_absolute(vol, &junction[1], - count - 1, isdir); - else - target = search_absolute(vol, &junction[3], - count - 3, isdir); - if (target) { - level = 0; - for (p=path; *p; p++) - if (*p == '/') - level++; - fulltarget = (char*)ntfs_malloc(3*level - + strlen(target) + 1); - if (fulltarget) { - fulltarget[0] = 0; - if (level > 1) { - for (i=1; i 0) && target) { - /* reverse slashes */ - for (q=target; *q; q++) - if (*q == '\\') - *q = '/'; - /* force uppercase drive letter */ - if ((target[1] == ':') - && (target[0] >= 'a') - && (target[0] <= 'z')) - target[0] += 'A' - 'a'; - level = 0; - for (p=path; *p; p++) - if (*p == '/') - level++; - fulltarget = (char*)ntfs_malloc(3*level - + sizeof(mappingdir) + strlen(target) - 3); - if (fulltarget) { - fulltarget[0] = 0; - if (level > 1) { - for (i=1; i= 3) + && junction[0] + && (junction[1] == const_cpu_to_le16(':')) + && (junction[2] == const_cpu_to_le16('\\'))) + kind = FULL_PATH; + else + /* + * For an absolute path we want an initial \ + */ + if ((count >= 0) + && (junction[0] == const_cpu_to_le16('\\'))) + kind = ABS_PATH; + else + kind = REJECTED_PATH; + /* + * Full path, with a drive letter and + * no specific definition for the drive letter : + * try to interpret as a target on the same volume. + * Do the same for an abs path with no drive letter. + */ + if (((kind == FULL_PATH) + && (count >= 3) + && junction[3] + && !ntfs_drive_letter(vol, junction[0])) + || (kind == ABS_PATH)) { + if (kind == ABS_PATH) + target = search_absolute(vol, &junction[1], + count - 1, isdir); + else + target = search_absolute(vol, &junction[3], + count - 3, isdir); + if (target) { + level = 0; + for (p=path; *p; p++) + if (*p == '/') + level++; + fulltarget = (char*)ntfs_malloc(3*level + + strlen(target) + 1); + if (fulltarget) { + fulltarget[0] = 0; + if (level > 1) { + for (i=1; i 0) && target) { + /* reverse slashes */ + for (q=target; *q; q++) + if (*q == '\\') + *q = '/'; + /* force uppercase drive letter */ + if ((target[1] == ':') + && (target[0] >= 'a') + && (target[0] <= 'z')) + target[0] += 'A' - 'a'; + level = 0; + for (p=path; *p; p++) + if (*p == '/') + level++; + fulltarget = (char*)ntfs_malloc(3*level + + sizeof(mappingdir) + strlen(target) - 3); + if (fulltarget) { + fulltarget[0] = 0; + if (level > 1) { + for (i=1; imrec->flags & MFT_RECORD_IS_DIRECTORY) - != const_cpu_to_le16(0); - vol = ni->vol; - reparse_attr = (REPARSE_POINT*)ntfs_attr_readall(ni, - AT_REPARSE_POINT,(ntfschar*)NULL, 0, &attr_size); - if (reparse_attr && attr_size) { - switch (reparse_attr->reparse_tag) { - case IO_REPARSE_TAG_MOUNT_POINT : - mount_point_data = (struct MOUNT_POINT_REPARSE_DATA*) - reparse_attr->reparse_data; - offs = le16_to_cpu(mount_point_data->subst_name_offset); - lth = le16_to_cpu(mount_point_data->subst_name_length); - /* consistency checks */ - if (isdir - && ((le16_to_cpu(reparse_attr->reparse_data_length) - + 8) == attr_size) - && ((int)((sizeof(REPARSE_POINT) - + sizeof(struct MOUNT_POINT_REPARSE_DATA) - + offs + lth)) <= attr_size)) { - target = ntfs_get_fulllink(vol, - (ntfschar*)&mount_point_data->path_buffer[offs], - lth/2, org_path, isdir); - if (target) - bad = FALSE; - } - break; - case IO_REPARSE_TAG_SYMLINK : - symlink_data = (struct SYMLINK_REPARSE_DATA*) - reparse_attr->reparse_data; - offs = le16_to_cpu(symlink_data->subst_name_offset); - lth = le16_to_cpu(symlink_data->subst_name_length); - p = (ntfschar*)&symlink_data->path_buffer[offs]; - /* - * Predetermine the kind of target, - * the called function has to make a full check - */ - if (*p++ == const_cpu_to_le16('\\')) { - if ((*p == const_cpu_to_le16('?')) - || (*p == const_cpu_to_le16('\\'))) - kind = FULL_TARGET; - else - kind = ABS_TARGET; - } else - if (*p == const_cpu_to_le16(':')) - kind = ABS_TARGET; - else - kind = REL_TARGET; - p--; - /* consistency checks */ - if (((le16_to_cpu(reparse_attr->reparse_data_length) - + 8) == attr_size) - && ((int)((sizeof(REPARSE_POINT) - + sizeof(struct SYMLINK_REPARSE_DATA) - + offs + lth)) <= attr_size)) { - switch (kind) { - case FULL_TARGET : - if (!(symlink_data->flags - & const_cpu_to_le32(1))) { - target = ntfs_get_fulllink(vol, - p, lth/2, - org_path, isdir); - if (target) - bad = FALSE; - } - break; - case ABS_TARGET : - if (symlink_data->flags - & const_cpu_to_le32(1)) { - target = ntfs_get_abslink(vol, - p, lth/2, - org_path, isdir); - if (target) - bad = FALSE; - } - break; - case REL_TARGET : - if (symlink_data->flags - & const_cpu_to_le32(1)) { - target = ntfs_get_rellink(vol, - p, lth/2, - org_path, isdir); - if (target) - bad = FALSE; - } - break; - } - } - break; - } - free(reparse_attr); - } - *pattr_size = attr_size; - if (bad) - errno = EOPNOTSUPP; - return (target); + target = (char*)NULL; + bad = TRUE; + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + != const_cpu_to_le16(0); + vol = ni->vol; + reparse_attr = (REPARSE_POINT*)ntfs_attr_readall(ni, + AT_REPARSE_POINT,(ntfschar*)NULL, 0, &attr_size); + if (reparse_attr && attr_size) { + switch (reparse_attr->reparse_tag) { + case IO_REPARSE_TAG_MOUNT_POINT : + mount_point_data = (struct MOUNT_POINT_REPARSE_DATA*) + reparse_attr->reparse_data; + offs = le16_to_cpu(mount_point_data->subst_name_offset); + lth = le16_to_cpu(mount_point_data->subst_name_length); + /* consistency checks */ + if (isdir + && ((le16_to_cpu(reparse_attr->reparse_data_length) + + 8) == attr_size) + && ((int)((sizeof(REPARSE_POINT) + + sizeof(struct MOUNT_POINT_REPARSE_DATA) + + offs + lth)) <= attr_size)) { + target = ntfs_get_fulllink(vol, + (ntfschar*)&mount_point_data->path_buffer[offs], + lth/2, org_path, isdir); + if (target) + bad = FALSE; + } + break; + case IO_REPARSE_TAG_SYMLINK : + symlink_data = (struct SYMLINK_REPARSE_DATA*) + reparse_attr->reparse_data; + offs = le16_to_cpu(symlink_data->subst_name_offset); + lth = le16_to_cpu(symlink_data->subst_name_length); + p = (ntfschar*)&symlink_data->path_buffer[offs]; + /* + * Predetermine the kind of target, + * the called function has to make a full check + */ + if (*p++ == const_cpu_to_le16('\\')) { + if ((*p == const_cpu_to_le16('?')) + || (*p == const_cpu_to_le16('\\'))) + kind = FULL_TARGET; + else + kind = ABS_TARGET; + } else + if (*p == const_cpu_to_le16(':')) + kind = ABS_TARGET; + else + kind = REL_TARGET; + p--; + /* consistency checks */ + if (((le16_to_cpu(reparse_attr->reparse_data_length) + + 8) == attr_size) + && ((int)((sizeof(REPARSE_POINT) + + sizeof(struct SYMLINK_REPARSE_DATA) + + offs + lth)) <= attr_size)) { + switch (kind) { + case FULL_TARGET : + if (!(symlink_data->flags + & const_cpu_to_le32(1))) { + target = ntfs_get_fulllink(vol, + p, lth/2, + org_path, isdir); + if (target) + bad = FALSE; + } + break; + case ABS_TARGET : + if (symlink_data->flags + & const_cpu_to_le32(1)) { + target = ntfs_get_abslink(vol, + p, lth/2, + org_path, isdir); + if (target) + bad = FALSE; + } + break; + case REL_TARGET : + if (symlink_data->flags + & const_cpu_to_le32(1)) { + target = ntfs_get_rellink(vol, + p, lth/2, + org_path, isdir); + if (target) + bad = FALSE; + } + break; + } + } + break; + } + free(reparse_attr); + } + *pattr_size = attr_size; + if (bad) + errno = EOPNOTSUPP; + return (target); } /* @@ -884,25 +893,25 @@ char *ntfs_make_symlink(const char *org_path, * The validity of the target is not checked. */ -BOOL ntfs_possible_symlink(ntfs_inode *ni) { - s64 attr_size = 0; - REPARSE_POINT *reparse_attr; - BOOL possible; +BOOL ntfs_possible_symlink(ntfs_inode *ni) +{ + s64 attr_size = 0; + REPARSE_POINT *reparse_attr; + BOOL possible; - possible = FALSE; - reparse_attr = (REPARSE_POINT*)ntfs_attr_readall(ni, - AT_REPARSE_POINT,(ntfschar*)NULL, 0, &attr_size); - if (reparse_attr && attr_size) { - switch (reparse_attr->reparse_tag) { - case IO_REPARSE_TAG_MOUNT_POINT : - case IO_REPARSE_TAG_SYMLINK : - possible = TRUE; - default : - ; - } - free(reparse_attr); - } - return (possible); + possible = FALSE; + reparse_attr = (REPARSE_POINT*)ntfs_attr_readall(ni, + AT_REPARSE_POINT,(ntfschar*)NULL, 0, &attr_size); + if (reparse_attr && attr_size) { + switch (reparse_attr->reparse_tag) { + case IO_REPARSE_TAG_MOUNT_POINT : + case IO_REPARSE_TAG_SYMLINK : + possible = TRUE; + default : ; + } + free(reparse_attr); + } + return (possible); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -915,32 +924,33 @@ BOOL ntfs_possible_symlink(ntfs_inode *ni) { */ static int set_reparse_index(ntfs_inode *ni, ntfs_index_context *xr, - le32 reparse_tag) { - struct REPARSE_INDEX indx; - u64 file_id_cpu; - le64 file_id; - le16 seqn; + le32 reparse_tag) +{ + struct REPARSE_INDEX indx; + u64 file_id_cpu; + le64 file_id; + le16 seqn; - seqn = ni->mrec->sequence_number; - file_id_cpu = MK_MREF(ni->mft_no,le16_to_cpu(seqn)); - file_id = cpu_to_le64(file_id_cpu); - indx.header.data_offset = const_cpu_to_le16( - sizeof(INDEX_ENTRY_HEADER) - + sizeof(REPARSE_INDEX_KEY)); - indx.header.data_length = const_cpu_to_le16(0); - indx.header.reservedV = const_cpu_to_le32(0); - indx.header.length = const_cpu_to_le16( - sizeof(struct REPARSE_INDEX)); - indx.header.key_length = const_cpu_to_le16( - sizeof(REPARSE_INDEX_KEY)); - indx.header.flags = const_cpu_to_le16(0); - indx.header.reserved = const_cpu_to_le16(0); - indx.key.reparse_tag = reparse_tag; - /* danger on processors which require proper alignment ! */ - memcpy(&indx.key.file_id, &file_id, 8); - indx.filling = const_cpu_to_le32(0); - ntfs_index_ctx_reinit(xr); - return (ntfs_ie_add(xr,(INDEX_ENTRY*)&indx)); + seqn = ni->mrec->sequence_number; + file_id_cpu = MK_MREF(ni->mft_no,le16_to_cpu(seqn)); + file_id = cpu_to_le64(file_id_cpu); + indx.header.data_offset = const_cpu_to_le16( + sizeof(INDEX_ENTRY_HEADER) + + sizeof(REPARSE_INDEX_KEY)); + indx.header.data_length = const_cpu_to_le16(0); + indx.header.reservedV = const_cpu_to_le32(0); + indx.header.length = const_cpu_to_le16( + sizeof(struct REPARSE_INDEX)); + indx.header.key_length = const_cpu_to_le16( + sizeof(REPARSE_INDEX_KEY)); + indx.header.flags = const_cpu_to_le16(0); + indx.header.reserved = const_cpu_to_le16(0); + indx.key.reparse_tag = reparse_tag; + /* danger on processors which require proper alignment ! */ + memcpy(&indx.key.file_id, &file_id, 8); + indx.filling = const_cpu_to_le32(0); + ntfs_index_ctx_reinit(xr); + return (ntfs_ie_add(xr,(INDEX_ENTRY*)&indx)); } #endif /* HAVE_SETXATTR */ @@ -954,33 +964,34 @@ static int set_reparse_index(ntfs_inode *ni, ntfs_index_context *xr, */ static int remove_reparse_index(ntfs_attr *na, ntfs_index_context *xr, - le32 *preparse_tag) { - REPARSE_INDEX_KEY key; - u64 file_id_cpu; - le64 file_id; - s64 size; - le16 seqn; - int ret; + le32 *preparse_tag) +{ + REPARSE_INDEX_KEY key; + u64 file_id_cpu; + le64 file_id; + s64 size; + le16 seqn; + int ret; - ret = na->data_size; - if (ret) { - /* read the existing reparse_tag */ - size = ntfs_attr_pread(na, 0, 4, preparse_tag); - if (size == 4) { - seqn = na->ni->mrec->sequence_number; - file_id_cpu = MK_MREF(na->ni->mft_no,le16_to_cpu(seqn)); - file_id = cpu_to_le64(file_id_cpu); - key.reparse_tag = *preparse_tag; - /* danger on processors which require proper alignment ! */ - memcpy(&key.file_id, &file_id, 8); - if (!ntfs_index_lookup(&key, sizeof(REPARSE_INDEX_KEY), xr)) - ret = ntfs_index_rm(xr); - } else { - ret = -1; - errno = ENODATA; - } - } - return (ret); + ret = na->data_size; + if (ret) { + /* read the existing reparse_tag */ + size = ntfs_attr_pread(na, 0, 4, preparse_tag); + if (size == 4) { + seqn = na->ni->mrec->sequence_number; + file_id_cpu = MK_MREF(na->ni->mft_no,le16_to_cpu(seqn)); + file_id = cpu_to_le64(file_id_cpu); + key.reparse_tag = *preparse_tag; + /* danger on processors which require proper alignment ! */ + memcpy(&key.file_id, &file_id, 8); + if (!ntfs_index_lookup(&key, sizeof(REPARSE_INDEX_KEY), xr)) + ret = ntfs_index_rm(xr); + } else { + ret = -1; + errno = ENODATA; + } + } + return (ret); } /* @@ -992,19 +1003,20 @@ static int remove_reparse_index(ntfs_attr *na, ntfs_index_context *xr, * The index has to be freed and inode closed when not needed any more. */ -static ntfs_index_context *open_reparse_index(ntfs_volume *vol) { - ntfs_inode *ni; - ntfs_index_context *xr; +static ntfs_index_context *open_reparse_index(ntfs_volume *vol) +{ + ntfs_inode *ni; + ntfs_index_context *xr; - ni = ntfs_pathname_to_inode(vol, NULL, "$Extend/$Reparse"); - if (ni) { - xr = ntfs_index_ctx_get(ni, reparse_index_name, 2); - if (!xr) { - ntfs_inode_close(ni); - } - } else - xr = (ntfs_index_context*)NULL; - return (xr); + ni = ntfs_pathname_to_inode(vol, NULL, "$Extend/$Reparse"); + if (ni) { + xr = ntfs_index_ctx_get(ni, reparse_index_name, 2); + if (!xr) { + ntfs_inode_close(ni); + } + } else + xr = (ntfs_index_context*)NULL; + return (xr); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -1023,53 +1035,54 @@ static ntfs_index_context *open_reparse_index(ntfs_volume *vol) { */ static int update_reparse_data(ntfs_inode *ni, ntfs_index_context *xr, - const char *value, size_t size) { - int res; - int written; - int oldsize; - ntfs_attr *na; - le32 reparse_tag; + const char *value, size_t size) +{ + int res; + int written; + int oldsize; + ntfs_attr *na; + le32 reparse_tag; - res = 0; - na = ntfs_attr_open(ni, AT_REPARSE_POINT, AT_UNNAMED, 0); - if (na) { - /* remove the existing reparse data */ - oldsize = remove_reparse_index(na,xr,&reparse_tag); - if (oldsize < 0) - res = -1; - else { - /* resize attribute */ - res = ntfs_attr_truncate(na, (s64)size); - /* overwrite value if any */ - if (!res && value) { - written = (int)ntfs_attr_pwrite(na, - (s64)0, (s64)size, value); - if (written != (s64)size) { - ntfs_log_error("Failed to update " - "reparse data\n"); - errno = EIO; - res = -1; - } - } - if (!res - && set_reparse_index(ni,xr, - ((const REPARSE_POINT*)value)->reparse_tag) - && (oldsize > 0)) { - /* - * If cannot index, try to remove the reparse - * data and log the error. There will be an - * inconsistency if removal fails. - */ - ntfs_attr_rm(na); - ntfs_log_error("Failed to index reparse data." - " Possible corruption.\n"); - } - } - ntfs_attr_close(na); - NInoSetDirty(ni); - } else - res = -1; - return (res); + res = 0; + na = ntfs_attr_open(ni, AT_REPARSE_POINT, AT_UNNAMED, 0); + if (na) { + /* remove the existing reparse data */ + oldsize = remove_reparse_index(na,xr,&reparse_tag); + if (oldsize < 0) + res = -1; + else { + /* resize attribute */ + res = ntfs_attr_truncate(na, (s64)size); + /* overwrite value if any */ + if (!res && value) { + written = (int)ntfs_attr_pwrite(na, + (s64)0, (s64)size, value); + if (written != (s64)size) { + ntfs_log_error("Failed to update " + "reparse data\n"); + errno = EIO; + res = -1; + } + } + if (!res + && set_reparse_index(ni,xr, + ((const REPARSE_POINT*)value)->reparse_tag) + && (oldsize > 0)) { + /* + * If cannot index, try to remove the reparse + * data and log the error. There will be an + * inconsistency if removal fails. + */ + ntfs_attr_rm(na); + ntfs_log_error("Failed to index reparse data." + " Possible corruption.\n"); + } + } + ntfs_attr_close(na); + NInoSetDirty(ni); + } else + res = -1; + return (res); } #endif /* HAVE_SETXATTR */ @@ -1081,33 +1094,34 @@ static int update_reparse_data(ntfs_inode *ni, ntfs_index_context *xr, * -1 if failure, explained by errno */ -int ntfs_delete_reparse_index(ntfs_inode *ni) { - ntfs_index_context *xr; - ntfs_inode *xrni; - ntfs_attr *na; - le32 reparse_tag; - int res; +int ntfs_delete_reparse_index(ntfs_inode *ni) +{ + ntfs_index_context *xr; + ntfs_inode *xrni; + ntfs_attr *na; + le32 reparse_tag; + int res; - res = 0; - na = ntfs_attr_open(ni, AT_REPARSE_POINT, AT_UNNAMED, 0); - if (na) { - /* - * read the existing reparse data (the tag is enough) - * and un-index it - */ - xr = open_reparse_index(ni->vol); - if (xr) { - if (remove_reparse_index(na,xr,&reparse_tag) < 0) - res = -1; - xrni = xr->ni; - ntfs_index_entry_mark_dirty(xr); - NInoSetDirty(xrni); - ntfs_index_ctx_put(xr); - ntfs_inode_close(xrni); - } - ntfs_attr_close(na); - } - return (res); + res = 0; + na = ntfs_attr_open(ni, AT_REPARSE_POINT, AT_UNNAMED, 0); + if (na) { + /* + * read the existing reparse data (the tag is enough) + * and un-index it + */ + xr = open_reparse_index(ni->vol); + if (xr) { + if (remove_reparse_index(na,xr,&reparse_tag) < 0) + res = -1; + xrni = xr->ni; + ntfs_index_entry_mark_dirty(xr); + NInoSetDirty(xrni); + ntfs_index_ctx_put(xr); + ntfs_inode_close(xrni); + } + ntfs_attr_close(na); + } + return (res); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -1120,29 +1134,30 @@ int ntfs_delete_reparse_index(ntfs_inode *ni) { */ int ntfs_get_ntfs_reparse_data(const char *path __attribute__((unused)), - char *value, size_t size, ntfs_inode *ni) { - REPARSE_POINT *reparse_attr; - s64 attr_size; + char *value, size_t size, ntfs_inode *ni) +{ + REPARSE_POINT *reparse_attr; + s64 attr_size; - attr_size = 0; /* default to no data and no error */ - if (ni) { - if (ni->flags & FILE_ATTR_REPARSE_POINT) { - reparse_attr = (REPARSE_POINT*)ntfs_attr_readall(ni, - AT_REPARSE_POINT,(ntfschar*)NULL, 0, &attr_size); - if (reparse_attr) { - if (attr_size <= (s64)size) { - if (value) - memcpy(value,reparse_attr, - attr_size); - else - errno = EINVAL; - } - free(reparse_attr); - } - } else - errno = ENODATA; - } - return (attr_size ? (int)attr_size : -errno); + attr_size = 0; /* default to no data and no error */ + if (ni) { + if (ni->flags & FILE_ATTR_REPARSE_POINT) { + reparse_attr = (REPARSE_POINT*)ntfs_attr_readall(ni, + AT_REPARSE_POINT,(ntfschar*)NULL, 0, &attr_size); + if (reparse_attr) { + if (attr_size <= (s64)size) { + if (value) + memcpy(value,reparse_attr, + attr_size); + else + errno = EINVAL; + } + free(reparse_attr); + } + } else + errno = ENODATA; + } + return (attr_size ? (int)attr_size : -errno); } /* @@ -1154,65 +1169,66 @@ int ntfs_get_ntfs_reparse_data(const char *path __attribute__((unused)), */ int ntfs_set_ntfs_reparse_data(const char *path __attribute__((unused)), - const char *value, size_t size, int flags, - ntfs_inode *ni) { - int res; - u8 dummy; - ntfs_inode *xrni; - ntfs_index_context *xr; + const char *value, size_t size, int flags, + ntfs_inode *ni) +{ + int res; + u8 dummy; + ntfs_inode *xrni; + ntfs_index_context *xr; - res = 0; - if (ni && value && (size >= 4)) { - xr = open_reparse_index(ni->vol); - if (xr) { - if (!ntfs_attr_exist(ni,AT_REPARSE_POINT, - AT_UNNAMED,0)) { - if (!(flags & XATTR_REPLACE)) { - /* - * no reparse data attribute : add one, - * apparently, this does not feed the new value in - * Note : NTFS version must be >= 3 - */ - if (ni->vol->major_ver >= 3) { - res = ntfs_attr_add(ni, - AT_REPARSE_POINT, - AT_UNNAMED,0,&dummy, - (s64)0); - if (!res) - ni->flags |= - FILE_ATTR_REPARSE_POINT; - NInoSetDirty(ni); - } else { - errno = EOPNOTSUPP; - res = -1; - } - } else { - errno = ENODATA; - res = -1; - } - } else { - if (flags & XATTR_CREATE) { - errno = EEXIST; - res = -1; - } - } - if (!res) { - /* update value and index */ - res = update_reparse_data(ni,xr,value,size); - } - xrni = xr->ni; - ntfs_index_entry_mark_dirty(xr); - NInoSetDirty(xrni); - ntfs_index_ctx_put(xr); - ntfs_inode_close(xrni); - } else { - res = -1; - } - } else { - errno = EINVAL; - res = -1; - } - return (res ? -1 : 0); + res = 0; + if (ni && value && (size >= 4)) { + xr = open_reparse_index(ni->vol); + if (xr) { + if (!ntfs_attr_exist(ni,AT_REPARSE_POINT, + AT_UNNAMED,0)) { + if (!(flags & XATTR_REPLACE)) { + /* + * no reparse data attribute : add one, + * apparently, this does not feed the new value in + * Note : NTFS version must be >= 3 + */ + if (ni->vol->major_ver >= 3) { + res = ntfs_attr_add(ni, + AT_REPARSE_POINT, + AT_UNNAMED,0,&dummy, + (s64)0); + if (!res) + ni->flags |= + FILE_ATTR_REPARSE_POINT; + NInoSetDirty(ni); + } else { + errno = EOPNOTSUPP; + res = -1; + } + } else { + errno = ENODATA; + res = -1; + } + } else { + if (flags & XATTR_CREATE) { + errno = EEXIST; + res = -1; + } + } + if (!res) { + /* update value and index */ + res = update_reparse_data(ni,xr,value,size); + } + xrni = xr->ni; + ntfs_index_entry_mark_dirty(xr); + NInoSetDirty(xrni); + ntfs_index_ctx_put(xr); + ntfs_inode_close(xrni); + } else { + res = -1; + } + } else { + errno = EINVAL; + res = -1; + } + return (res ? -1 : 0); } /* @@ -1222,70 +1238,71 @@ int ntfs_set_ntfs_reparse_data(const char *path __attribute__((unused)), */ int ntfs_remove_ntfs_reparse_data(const char *path __attribute__((unused)), - ntfs_inode *ni) { - int res; - int olderrno; - ntfs_attr *na; - ntfs_inode *xrni; - ntfs_index_context *xr; - le32 reparse_tag; + ntfs_inode *ni) +{ + int res; + int olderrno; + ntfs_attr *na; + ntfs_inode *xrni; + ntfs_index_context *xr; + le32 reparse_tag; - res = 0; - if (ni) { - /* - * open and delete the reparse data - */ - na = ntfs_attr_open(ni, AT_REPARSE_POINT, - AT_UNNAMED,0); - if (na) { - /* first remove index (reparse data needed) */ - xr = open_reparse_index(ni->vol); - if (xr) { - if (remove_reparse_index(na,xr, - &reparse_tag) < 0) { - res = -1; - } else { - /* now remove attribute */ - res = ntfs_attr_rm(na); - if (!res) { - ni->flags &= - ~FILE_ATTR_REPARSE_POINT; - } else { - /* - * If we could not remove the - * attribute, try to restore the - * index and log the error. There - * will be an inconsistency if - * the reindexing fails. - */ - set_reparse_index(ni, xr, - reparse_tag); - ntfs_log_error( - "Failed to remove reparse data." - " Possible corruption.\n"); - } - } - xrni = xr->ni; - ntfs_index_entry_mark_dirty(xr); - NInoSetDirty(xrni); - ntfs_index_ctx_put(xr); - ntfs_inode_close(xrni); - } - olderrno = errno; - ntfs_attr_close(na); - /* avoid errno pollution */ - if (errno == ENOENT) - errno = olderrno; - } else { - errno = ENODATA; - res = -1; - } - NInoSetDirty(ni); - } else { - errno = EINVAL; - res = -1; - } - return (res ? -1 : 0); + res = 0; + if (ni) { + /* + * open and delete the reparse data + */ + na = ntfs_attr_open(ni, AT_REPARSE_POINT, + AT_UNNAMED,0); + if (na) { + /* first remove index (reparse data needed) */ + xr = open_reparse_index(ni->vol); + if (xr) { + if (remove_reparse_index(na,xr, + &reparse_tag) < 0) { + res = -1; + } else { + /* now remove attribute */ + res = ntfs_attr_rm(na); + if (!res) { + ni->flags &= + ~FILE_ATTR_REPARSE_POINT; + } else { + /* + * If we could not remove the + * attribute, try to restore the + * index and log the error. There + * will be an inconsistency if + * the reindexing fails. + */ + set_reparse_index(ni, xr, + reparse_tag); + ntfs_log_error( + "Failed to remove reparse data." + " Possible corruption.\n"); + } + } + xrni = xr->ni; + ntfs_index_entry_mark_dirty(xr); + NInoSetDirty(xrni); + ntfs_index_ctx_put(xr); + ntfs_inode_close(xrni); + } + olderrno = errno; + ntfs_attr_close(na); + /* avoid errno pollution */ + if (errno == ENOENT) + errno = olderrno; + } else { + errno = ENODATA; + res = -1; + } + NInoSetDirty(ni); + } else { + errno = EINVAL; + res = -1; + } + return (res ? -1 : 0); } #endif /* HAVE_SETXATTR */ diff --git a/source/libntfs/reparse.h b/source/libntfs/reparse.h index 088ec7af..91ede03e 100644 --- a/source/libntfs/reparse.h +++ b/source/libntfs/reparse.h @@ -25,13 +25,13 @@ #define REPARSE_H char *ntfs_make_symlink(const char *org_path, - ntfs_inode *ni, int *pattr_size); + ntfs_inode *ni, int *pattr_size); BOOL ntfs_possible_symlink(ntfs_inode *ni); int ntfs_get_ntfs_reparse_data(const char *path, - char *value, size_t size, ntfs_inode *ni); + char *value, size_t size, ntfs_inode *ni); int ntfs_set_ntfs_reparse_data(const char *path, const char *value, - size_t size, int flags, ntfs_inode *ni); + size_t size, int flags, ntfs_inode *ni); int ntfs_remove_ntfs_reparse_data(const char *path, ntfs_inode *ni); int ntfs_delete_reparse_index(ntfs_inode *ni); diff --git a/source/libntfs/runlist.c b/source/libntfs/runlist.c index df68bef2..f81996bd 100644 --- a/source/libntfs/runlist.c +++ b/source/libntfs/runlist.c @@ -60,9 +60,10 @@ * * Returns: */ -static void ntfs_rl_mm(runlist_element *base, int dst, int src, int size) { - if ((dst != src) && (size > 0)) - memmove(base + dst, base + src, size * sizeof(*base)); +static void ntfs_rl_mm(runlist_element *base, int dst, int src, int size) +{ + if ((dst != src) && (size > 0)) + memmove(base + dst, base + src, size * sizeof(*base)); } /** @@ -78,9 +79,10 @@ static void ntfs_rl_mm(runlist_element *base, int dst, int src, int size) { * Returns: */ static void ntfs_rl_mc(runlist_element *dstbase, int dst, - runlist_element *srcbase, int src, int size) { - if (size > 0) - memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase)); + runlist_element *srcbase, int src, int size) +{ + if (size > 0) + memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase)); } /** @@ -99,13 +101,14 @@ static void ntfs_rl_mc(runlist_element *dstbase, int dst, * On success, return a pointer to the newly allocated, or recycled, memory. * On error, return NULL with errno set to the error code. */ -static runlist_element *ntfs_rl_realloc(runlist_element *rl, int old_size, - int new_size) { - old_size = (old_size * sizeof(runlist_element) + 0xfff) & ~0xfff; - new_size = (new_size * sizeof(runlist_element) + 0xfff) & ~0xfff; - if (old_size == new_size) - return rl; - return realloc(rl, new_size); +static runlist_element *ntfs_rl_realloc(runlist_element *rl, int old_size, + int new_size) +{ + old_size = (old_size * sizeof(runlist_element) + 0xfff) & ~0xfff; + new_size = (new_size * sizeof(runlist_element) + 0xfff) & ~0xfff; + if (old_size == new_size) + return rl; + return realloc(rl, new_size); } /* @@ -116,16 +119,17 @@ static runlist_element *ntfs_rl_realloc(runlist_element *rl, int old_size, * or NULL if reallocation was not possible (with errno set) */ -runlist_element *ntfs_rl_extend(runlist_element *rl, int more_entries) { - int last; +runlist_element *ntfs_rl_extend(runlist_element *rl, int more_entries) +{ + int last; - last = 0; - while (rl[last].length) - last++; - rl = ntfs_rl_realloc(rl,last+1,last+more_entries+1); - if (!rl) - errno = ENOMEM; - return (rl); + last = 0; + while (rl[last].length) + last++; + rl = ntfs_rl_realloc(rl,last+1,last+more_entries+1); + if (!rl) + errno = ENOMEM; + return (rl); } /** @@ -139,28 +143,29 @@ runlist_element *ntfs_rl_extend(runlist_element *rl, int more_entries) { * Return: TRUE Success, the runlists can be merged. * FALSE Failure, the runlists cannot be merged. */ -static BOOL ntfs_rl_are_mergeable(runlist_element *dst, runlist_element *src) { - if (!dst || !src) { - ntfs_log_debug("Eeek. ntfs_rl_are_mergeable() invoked with NULL " - "pointer!\n"); - return FALSE; - } +static BOOL ntfs_rl_are_mergeable(runlist_element *dst, runlist_element *src) +{ + if (!dst || !src) { + ntfs_log_debug("Eeek. ntfs_rl_are_mergeable() invoked with NULL " + "pointer!\n"); + return FALSE; + } - /* We can merge unmapped regions even if they are misaligned. */ - if ((dst->lcn == LCN_RL_NOT_MAPPED) && (src->lcn == LCN_RL_NOT_MAPPED)) - return TRUE; - /* If the runs are misaligned, we cannot merge them. */ - if ((dst->vcn + dst->length) != src->vcn) - return FALSE; - /* If both runs are non-sparse and contiguous, we can merge them. */ - if ((dst->lcn >= 0) && (src->lcn >= 0) && - ((dst->lcn + dst->length) == src->lcn)) - return TRUE; - /* If we are merging two holes, we can merge them. */ - if ((dst->lcn == LCN_HOLE) && (src->lcn == LCN_HOLE)) - return TRUE; - /* Cannot merge. */ - return FALSE; + /* We can merge unmapped regions even if they are misaligned. */ + if ((dst->lcn == LCN_RL_NOT_MAPPED) && (src->lcn == LCN_RL_NOT_MAPPED)) + return TRUE; + /* If the runs are misaligned, we cannot merge them. */ + if ((dst->vcn + dst->length) != src->vcn) + return FALSE; + /* If both runs are non-sparse and contiguous, we can merge them. */ + if ((dst->lcn >= 0) && (src->lcn >= 0) && + ((dst->lcn + dst->length) == src->lcn)) + return TRUE; + /* If we are merging two holes, we can merge them. */ + if ((dst->lcn == LCN_HOLE) && (src->lcn == LCN_HOLE)) + return TRUE; + /* Cannot merge. */ + return FALSE; } /** @@ -172,8 +177,9 @@ static BOOL ntfs_rl_are_mergeable(runlist_element *dst, runlist_element *src) { * caller must make sure the runlists can be merged or this will corrupt the * destination runlist. */ -static void __ntfs_rl_merge(runlist_element *dst, runlist_element *src) { - dst->length += src->length; +static void __ntfs_rl_merge(runlist_element *dst, runlist_element *src) +{ + dst->length += src->length; } /** @@ -197,49 +203,50 @@ static void __ntfs_rl_merge(runlist_element *dst, runlist_element *src) { * left unmodified. */ static runlist_element *ntfs_rl_append(runlist_element *dst, int dsize, - runlist_element *src, int ssize, int loc) { - BOOL right = FALSE; /* Right end of @src needs merging */ - int marker; /* End of the inserted runs */ + runlist_element *src, int ssize, int loc) +{ + BOOL right = FALSE; /* Right end of @src needs merging */ + int marker; /* End of the inserted runs */ - if (!dst || !src) { - ntfs_log_debug("Eeek. ntfs_rl_append() invoked with NULL " - "pointer!\n"); - errno = EINVAL; - return NULL; - } + if (!dst || !src) { + ntfs_log_debug("Eeek. ntfs_rl_append() invoked with NULL " + "pointer!\n"); + errno = EINVAL; + return NULL; + } - /* First, check if the right hand end needs merging. */ - if ((loc + 1) < dsize) - right = ntfs_rl_are_mergeable(src + ssize - 1, dst + loc + 1); + /* First, check if the right hand end needs merging. */ + if ((loc + 1) < dsize) + right = ntfs_rl_are_mergeable(src + ssize - 1, dst + loc + 1); - /* Space required: @dst size + @src size, less one if we merged. */ - dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right); - if (!dst) - return NULL; - /* - * We are guaranteed to succeed from here so can start modifying the - * original runlists. - */ + /* Space required: @dst size + @src size, less one if we merged. */ + dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right); + if (!dst) + return NULL; + /* + * We are guaranteed to succeed from here so can start modifying the + * original runlists. + */ - /* First, merge the right hand end, if necessary. */ - if (right) - __ntfs_rl_merge(src + ssize - 1, dst + loc + 1); + /* First, merge the right hand end, if necessary. */ + if (right) + __ntfs_rl_merge(src + ssize - 1, dst + loc + 1); - /* marker - First run after the @src runs that have been inserted */ - marker = loc + ssize + 1; + /* marker - First run after the @src runs that have been inserted */ + marker = loc + ssize + 1; - /* Move the tail of @dst out of the way, then copy in @src. */ - ntfs_rl_mm(dst, marker, loc + 1 + right, dsize - loc - 1 - right); - ntfs_rl_mc(dst, loc + 1, src, 0, ssize); + /* Move the tail of @dst out of the way, then copy in @src. */ + ntfs_rl_mm(dst, marker, loc + 1 + right, dsize - loc - 1 - right); + ntfs_rl_mc(dst, loc + 1, src, 0, ssize); - /* Adjust the size of the preceding hole. */ - dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn; + /* Adjust the size of the preceding hole. */ + dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn; - /* We may have changed the length of the file, so fix the end marker */ - if (dst[marker].lcn == LCN_ENOENT) - dst[marker].vcn = dst[marker-1].vcn + dst[marker-1].length; + /* We may have changed the length of the file, so fix the end marker */ + if (dst[marker].lcn == LCN_ENOENT) + dst[marker].vcn = dst[marker-1].vcn + dst[marker-1].length; - return dst; + return dst; } /** @@ -263,79 +270,80 @@ static runlist_element *ntfs_rl_append(runlist_element *dst, int dsize, * left unmodified. */ static runlist_element *ntfs_rl_insert(runlist_element *dst, int dsize, - runlist_element *src, int ssize, int loc) { - BOOL left = FALSE; /* Left end of @src needs merging */ - BOOL disc = FALSE; /* Discontinuity between @dst and @src */ - int marker; /* End of the inserted runs */ + runlist_element *src, int ssize, int loc) +{ + BOOL left = FALSE; /* Left end of @src needs merging */ + BOOL disc = FALSE; /* Discontinuity between @dst and @src */ + int marker; /* End of the inserted runs */ - if (!dst || !src) { - ntfs_log_debug("Eeek. ntfs_rl_insert() invoked with NULL " - "pointer!\n"); - errno = EINVAL; - return NULL; - } + if (!dst || !src) { + ntfs_log_debug("Eeek. ntfs_rl_insert() invoked with NULL " + "pointer!\n"); + errno = EINVAL; + return NULL; + } - /* disc => Discontinuity between the end of @dst and the start of @src. - * This means we might need to insert a "notmapped" run. - */ - if (loc == 0) - disc = (src[0].vcn > 0); - else { - s64 merged_length; + /* disc => Discontinuity between the end of @dst and the start of @src. + * This means we might need to insert a "notmapped" run. + */ + if (loc == 0) + disc = (src[0].vcn > 0); + else { + s64 merged_length; - left = ntfs_rl_are_mergeable(dst + loc - 1, src); + left = ntfs_rl_are_mergeable(dst + loc - 1, src); - merged_length = dst[loc - 1].length; - if (left) - merged_length += src->length; + merged_length = dst[loc - 1].length; + if (left) + merged_length += src->length; - disc = (src[0].vcn > dst[loc - 1].vcn + merged_length); - } + disc = (src[0].vcn > dst[loc - 1].vcn + merged_length); + } - /* Space required: @dst size + @src size, less one if we merged, plus - * one if there was a discontinuity. - */ - dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc); - if (!dst) - return NULL; - /* - * We are guaranteed to succeed from here so can start modifying the - * original runlist. - */ + /* Space required: @dst size + @src size, less one if we merged, plus + * one if there was a discontinuity. + */ + dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc); + if (!dst) + return NULL; + /* + * We are guaranteed to succeed from here so can start modifying the + * original runlist. + */ - if (left) - __ntfs_rl_merge(dst + loc - 1, src); + if (left) + __ntfs_rl_merge(dst + loc - 1, src); - /* - * marker - First run after the @src runs that have been inserted - * Nominally: marker = @loc + @ssize (location + number of runs in @src) - * If "left", then the first run in @src has been merged with one in @dst. - * If "disc", then @dst and @src don't meet and we need an extra run to fill the gap. - */ - marker = loc + ssize - left + disc; + /* + * marker - First run after the @src runs that have been inserted + * Nominally: marker = @loc + @ssize (location + number of runs in @src) + * If "left", then the first run in @src has been merged with one in @dst. + * If "disc", then @dst and @src don't meet and we need an extra run to fill the gap. + */ + marker = loc + ssize - left + disc; - /* Move the tail of @dst out of the way, then copy in @src. */ - ntfs_rl_mm(dst, marker, loc, dsize - loc); - ntfs_rl_mc(dst, loc + disc, src, left, ssize - left); + /* Move the tail of @dst out of the way, then copy in @src. */ + ntfs_rl_mm(dst, marker, loc, dsize - loc); + ntfs_rl_mc(dst, loc + disc, src, left, ssize - left); - /* Adjust the VCN of the first run after the insertion ... */ - dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length; - /* ... and the length. */ - if (dst[marker].lcn == LCN_HOLE || dst[marker].lcn == LCN_RL_NOT_MAPPED) - dst[marker].length = dst[marker + 1].vcn - dst[marker].vcn; + /* Adjust the VCN of the first run after the insertion ... */ + dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length; + /* ... and the length. */ + if (dst[marker].lcn == LCN_HOLE || dst[marker].lcn == LCN_RL_NOT_MAPPED) + dst[marker].length = dst[marker + 1].vcn - dst[marker].vcn; - /* Writing beyond the end of the file and there's a discontinuity. */ - if (disc) { - if (loc > 0) { - dst[loc].vcn = dst[loc - 1].vcn + dst[loc - 1].length; - dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn; - } else { - dst[loc].vcn = 0; - dst[loc].length = dst[loc + 1].vcn; - } - dst[loc].lcn = LCN_RL_NOT_MAPPED; - } - return dst; + /* Writing beyond the end of the file and there's a discontinuity. */ + if (disc) { + if (loc > 0) { + dst[loc].vcn = dst[loc - 1].vcn + dst[loc - 1].length; + dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn; + } else { + dst[loc].vcn = 0; + dst[loc].length = dst[loc + 1].vcn; + } + dst[loc].lcn = LCN_RL_NOT_MAPPED; + } + return dst; } /** @@ -358,70 +366,71 @@ static runlist_element *ntfs_rl_insert(runlist_element *dst, int dsize, * left unmodified. */ static runlist_element *ntfs_rl_replace(runlist_element *dst, int dsize, - runlist_element *src, int ssize, - int loc) { - signed delta; - BOOL left = FALSE; /* Left end of @src needs merging */ - BOOL right = FALSE; /* Right end of @src needs merging */ - int tail; /* Start of tail of @dst */ - int marker; /* End of the inserted runs */ + runlist_element *src, int ssize, + int loc) +{ + signed delta; + BOOL left = FALSE; /* Left end of @src needs merging */ + BOOL right = FALSE; /* Right end of @src needs merging */ + int tail; /* Start of tail of @dst */ + int marker; /* End of the inserted runs */ - if (!dst || !src) { - ntfs_log_debug("Eeek. ntfs_rl_replace() invoked with NULL " - "pointer!\n"); - errno = EINVAL; - return NULL; - } + if (!dst || !src) { + ntfs_log_debug("Eeek. ntfs_rl_replace() invoked with NULL " + "pointer!\n"); + errno = EINVAL; + return NULL; + } - /* First, see if the left and right ends need merging. */ - if ((loc + 1) < dsize) - right = ntfs_rl_are_mergeable(src + ssize - 1, dst + loc + 1); - if (loc > 0) - left = ntfs_rl_are_mergeable(dst + loc - 1, src); + /* First, see if the left and right ends need merging. */ + if ((loc + 1) < dsize) + right = ntfs_rl_are_mergeable(src + ssize - 1, dst + loc + 1); + if (loc > 0) + left = ntfs_rl_are_mergeable(dst + loc - 1, src); - /* Allocate some space. We'll need less if the left, right, or both - * ends get merged. The -1 accounts for the run being replaced. - */ - delta = ssize - 1 - left - right; - if (delta > 0) { - dst = ntfs_rl_realloc(dst, dsize, dsize + delta); - if (!dst) - return NULL; - } - /* - * We are guaranteed to succeed from here so can start modifying the - * original runlists. - */ + /* Allocate some space. We'll need less if the left, right, or both + * ends get merged. The -1 accounts for the run being replaced. + */ + delta = ssize - 1 - left - right; + if (delta > 0) { + dst = ntfs_rl_realloc(dst, dsize, dsize + delta); + if (!dst) + return NULL; + } + /* + * We are guaranteed to succeed from here so can start modifying the + * original runlists. + */ - /* First, merge the left and right ends, if necessary. */ - if (right) - __ntfs_rl_merge(src + ssize - 1, dst + loc + 1); - if (left) - __ntfs_rl_merge(dst + loc - 1, src); + /* First, merge the left and right ends, if necessary. */ + if (right) + __ntfs_rl_merge(src + ssize - 1, dst + loc + 1); + if (left) + __ntfs_rl_merge(dst + loc - 1, src); - /* - * tail - Offset of the tail of @dst - * Nominally: @tail = @loc + 1 (location, skipping the replaced run) - * If "right", then one of @dst's runs is already merged into @src. - */ - tail = loc + right + 1; + /* + * tail - Offset of the tail of @dst + * Nominally: @tail = @loc + 1 (location, skipping the replaced run) + * If "right", then one of @dst's runs is already merged into @src. + */ + tail = loc + right + 1; - /* - * marker - First run after the @src runs that have been inserted - * Nominally: @marker = @loc + @ssize (location + number of runs in @src) - * If "left", then the first run in @src has been merged with one in @dst. - */ - marker = loc + ssize - left; + /* + * marker - First run after the @src runs that have been inserted + * Nominally: @marker = @loc + @ssize (location + number of runs in @src) + * If "left", then the first run in @src has been merged with one in @dst. + */ + marker = loc + ssize - left; - /* Move the tail of @dst out of the way, then copy in @src. */ - ntfs_rl_mm(dst, marker, tail, dsize - tail); - ntfs_rl_mc(dst, loc, src, left, ssize - left); + /* Move the tail of @dst out of the way, then copy in @src. */ + ntfs_rl_mm(dst, marker, tail, dsize - tail); + ntfs_rl_mc(dst, loc, src, left, ssize - left); - /* We may have changed the length of the file, so fix the end marker */ - if (((dsize - tail) > 0) && (dst[marker].lcn == LCN_ENOENT)) - dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length; + /* We may have changed the length of the file, so fix the end marker */ + if (((dsize - tail) > 0) && (dst[marker].lcn == LCN_ENOENT)) + dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length; - return dst; + return dst; } /** @@ -445,242 +454,244 @@ static runlist_element *ntfs_rl_replace(runlist_element *dst, int dsize, * left unmodified. */ static runlist_element *ntfs_rl_split(runlist_element *dst, int dsize, - runlist_element *src, int ssize, int loc) { - if (!dst || !src) { - ntfs_log_debug("Eeek. ntfs_rl_split() invoked with NULL pointer!\n"); - errno = EINVAL; - return NULL; - } + runlist_element *src, int ssize, int loc) +{ + if (!dst || !src) { + ntfs_log_debug("Eeek. ntfs_rl_split() invoked with NULL pointer!\n"); + errno = EINVAL; + return NULL; + } - /* Space required: @dst size + @src size + one new hole. */ - dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1); - if (!dst) - return dst; - /* - * We are guaranteed to succeed from here so can start modifying the - * original runlists. - */ + /* Space required: @dst size + @src size + one new hole. */ + dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1); + if (!dst) + return dst; + /* + * We are guaranteed to succeed from here so can start modifying the + * original runlists. + */ - /* Move the tail of @dst out of the way, then copy in @src. */ - ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc); - ntfs_rl_mc(dst, loc + 1, src, 0, ssize); + /* Move the tail of @dst out of the way, then copy in @src. */ + ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc); + ntfs_rl_mc(dst, loc + 1, src, 0, ssize); - /* Adjust the size of the holes either size of @src. */ - dst[loc].length = dst[loc+1].vcn - dst[loc].vcn; - dst[loc+ssize+1].vcn = dst[loc+ssize].vcn + dst[loc+ssize].length; - dst[loc+ssize+1].length = dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn; + /* Adjust the size of the holes either size of @src. */ + dst[loc].length = dst[loc+1].vcn - dst[loc].vcn; + dst[loc+ssize+1].vcn = dst[loc+ssize].vcn + dst[loc+ssize].length; + dst[loc+ssize+1].length = dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn; - return dst; + return dst; } /** * ntfs_runlists_merge_i - see ntfs_runlists_merge */ -static runlist_element *ntfs_runlists_merge_i(runlist_element *drl, - runlist_element *srl) { - int di, si; /* Current index into @[ds]rl. */ - int sstart; /* First index with lcn > LCN_RL_NOT_MAPPED. */ - int dins; /* Index into @drl at which to insert @srl. */ - int dend, send; /* Last index into @[ds]rl. */ - int dfinal, sfinal; /* The last index into @[ds]rl with +static runlist_element *ntfs_runlists_merge_i(runlist_element *drl, + runlist_element *srl) +{ + int di, si; /* Current index into @[ds]rl. */ + int sstart; /* First index with lcn > LCN_RL_NOT_MAPPED. */ + int dins; /* Index into @drl at which to insert @srl. */ + int dend, send; /* Last index into @[ds]rl. */ + int dfinal, sfinal; /* The last index into @[ds]rl with lcn >= LCN_HOLE. */ - int marker = 0; - VCN marker_vcn = 0; + int marker = 0; + VCN marker_vcn = 0; - ntfs_log_debug("dst:\n"); - ntfs_debug_runlist_dump(drl); - ntfs_log_debug("src:\n"); - ntfs_debug_runlist_dump(srl); + ntfs_log_debug("dst:\n"); + ntfs_debug_runlist_dump(drl); + ntfs_log_debug("src:\n"); + ntfs_debug_runlist_dump(srl); - /* Check for silly calling... */ - if (!srl) - return drl; + /* Check for silly calling... */ + if (!srl) + return drl; - /* Check for the case where the first mapping is being done now. */ - if (!drl) { - drl = srl; - /* Complete the source runlist if necessary. */ - if (drl[0].vcn) { - /* Scan to the end of the source runlist. */ - for (dend = 0; drl[dend].length; dend++) - ; - dend++; - drl = ntfs_rl_realloc(drl, dend, dend + 1); - if (!drl) - return drl; - /* Insert start element at the front of the runlist. */ - ntfs_rl_mm(drl, 1, 0, dend); - drl[0].vcn = 0; - drl[0].lcn = LCN_RL_NOT_MAPPED; - drl[0].length = drl[1].vcn; - } - goto finished; - } + /* Check for the case where the first mapping is being done now. */ + if (!drl) { + drl = srl; + /* Complete the source runlist if necessary. */ + if (drl[0].vcn) { + /* Scan to the end of the source runlist. */ + for (dend = 0; drl[dend].length; dend++) + ; + dend++; + drl = ntfs_rl_realloc(drl, dend, dend + 1); + if (!drl) + return drl; + /* Insert start element at the front of the runlist. */ + ntfs_rl_mm(drl, 1, 0, dend); + drl[0].vcn = 0; + drl[0].lcn = LCN_RL_NOT_MAPPED; + drl[0].length = drl[1].vcn; + } + goto finished; + } - si = di = 0; + si = di = 0; - /* Skip any unmapped start element(s) in the source runlist. */ - while (srl[si].length && srl[si].lcn < (LCN)LCN_HOLE) - si++; + /* Skip any unmapped start element(s) in the source runlist. */ + while (srl[si].length && srl[si].lcn < (LCN)LCN_HOLE) + si++; - /* Can't have an entirely unmapped source runlist. */ - if (!srl[si].length) { - errno = EINVAL; - ntfs_log_perror("%s: unmapped source runlist", __FUNCTION__); - return NULL; - } + /* Can't have an entirely unmapped source runlist. */ + if (!srl[si].length) { + errno = EINVAL; + ntfs_log_perror("%s: unmapped source runlist", __FUNCTION__); + return NULL; + } - /* Record the starting points. */ - sstart = si; + /* Record the starting points. */ + sstart = si; - /* - * Skip forward in @drl until we reach the position where @srl needs to - * be inserted. If we reach the end of @drl, @srl just needs to be - * appended to @drl. - */ - for (; drl[di].length; di++) { - if (drl[di].vcn + drl[di].length > srl[sstart].vcn) - break; - } - dins = di; + /* + * Skip forward in @drl until we reach the position where @srl needs to + * be inserted. If we reach the end of @drl, @srl just needs to be + * appended to @drl. + */ + for (; drl[di].length; di++) { + if (drl[di].vcn + drl[di].length > srl[sstart].vcn) + break; + } + dins = di; - /* Sanity check for illegal overlaps. */ - if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) && - (srl[si].lcn >= 0)) { - errno = ERANGE; - ntfs_log_perror("Run lists overlap. Cannot merge"); - return NULL; - } + /* Sanity check for illegal overlaps. */ + if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) && + (srl[si].lcn >= 0)) { + errno = ERANGE; + ntfs_log_perror("Run lists overlap. Cannot merge"); + return NULL; + } - /* Scan to the end of both runlists in order to know their sizes. */ - for (send = si; srl[send].length; send++) - ; - for (dend = di; drl[dend].length; dend++) - ; + /* Scan to the end of both runlists in order to know their sizes. */ + for (send = si; srl[send].length; send++) + ; + for (dend = di; drl[dend].length; dend++) + ; - if (srl[send].lcn == (LCN)LCN_ENOENT) - marker_vcn = srl[marker = send].vcn; + if (srl[send].lcn == (LCN)LCN_ENOENT) + marker_vcn = srl[marker = send].vcn; - /* Scan to the last element with lcn >= LCN_HOLE. */ - for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--) - ; - for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--) - ; + /* Scan to the last element with lcn >= LCN_HOLE. */ + for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--) + ; + for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--) + ; - { - BOOL start; - BOOL finish; - int ds = dend + 1; /* Number of elements in drl & srl */ - int ss = sfinal - sstart + 1; + { + BOOL start; + BOOL finish; + int ds = dend + 1; /* Number of elements in drl & srl */ + int ss = sfinal - sstart + 1; - start = ((drl[dins].lcn < LCN_RL_NOT_MAPPED) || /* End of file */ - (drl[dins].vcn == srl[sstart].vcn)); /* Start of hole */ - finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) && /* End of file */ - ((drl[dins].vcn + drl[dins].length) <= /* End of hole */ - (srl[send - 1].vcn + srl[send - 1].length))); + start = ((drl[dins].lcn < LCN_RL_NOT_MAPPED) || /* End of file */ + (drl[dins].vcn == srl[sstart].vcn)); /* Start of hole */ + finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) && /* End of file */ + ((drl[dins].vcn + drl[dins].length) <= /* End of hole */ + (srl[send - 1].vcn + srl[send - 1].length))); - /* Or we'll lose an end marker */ - if (finish && !drl[dins].length) - ss++; - if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn)) - finish = FALSE; + /* Or we'll lose an end marker */ + if (finish && !drl[dins].length) + ss++; + if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn)) + finish = FALSE; - ntfs_log_debug("dfinal = %i, dend = %i\n", dfinal, dend); - ntfs_log_debug("sstart = %i, sfinal = %i, send = %i\n", sstart, sfinal, send); - ntfs_log_debug("start = %i, finish = %i\n", start, finish); - ntfs_log_debug("ds = %i, ss = %i, dins = %i\n", ds, ss, dins); + ntfs_log_debug("dfinal = %i, dend = %i\n", dfinal, dend); + ntfs_log_debug("sstart = %i, sfinal = %i, send = %i\n", sstart, sfinal, send); + ntfs_log_debug("start = %i, finish = %i\n", start, finish); + ntfs_log_debug("ds = %i, ss = %i, dins = %i\n", ds, ss, dins); - if (start) { - if (finish) - drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins); - else - drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins); - } else { - if (finish) - drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins); - else - drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins); - } - if (!drl) { - ntfs_log_perror("Merge failed"); - return drl; - } - free(srl); - if (marker) { - ntfs_log_debug("Triggering marker code.\n"); - for (ds = dend; drl[ds].length; ds++) - ; - /* We only need to care if @srl ended after @drl. */ - if (drl[ds].vcn <= marker_vcn) { - int slots = 0; + if (start) { + if (finish) + drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins); + else + drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins); + } else { + if (finish) + drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins); + else + drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins); + } + if (!drl) { + ntfs_log_perror("Merge failed"); + return drl; + } + free(srl); + if (marker) { + ntfs_log_debug("Triggering marker code.\n"); + for (ds = dend; drl[ds].length; ds++) + ; + /* We only need to care if @srl ended after @drl. */ + if (drl[ds].vcn <= marker_vcn) { + int slots = 0; - if (drl[ds].vcn == marker_vcn) { - ntfs_log_debug("Old marker = %lli, replacing with " - "LCN_ENOENT.\n", - (long long)drl[ds].lcn); - drl[ds].lcn = (LCN)LCN_ENOENT; - goto finished; - } - /* - * We need to create an unmapped runlist element in - * @drl or extend an existing one before adding the - * ENOENT terminator. - */ - if (drl[ds].lcn == (LCN)LCN_ENOENT) { - ds--; - slots = 1; - } - if (drl[ds].lcn != (LCN)LCN_RL_NOT_MAPPED) { - /* Add an unmapped runlist element. */ - if (!slots) { - /* FIXME/TODO: We need to have the - * extra memory already! (AIA) - */ - drl = ntfs_rl_realloc(drl, ds, ds + 2); - if (!drl) - goto critical_error; - slots = 2; - } - ds++; - /* Need to set vcn if it isn't set already. */ - if (slots != 1) - drl[ds].vcn = drl[ds - 1].vcn + - drl[ds - 1].length; - drl[ds].lcn = (LCN)LCN_RL_NOT_MAPPED; - /* We now used up a slot. */ - slots--; - } - drl[ds].length = marker_vcn - drl[ds].vcn; - /* Finally add the ENOENT terminator. */ - ds++; - if (!slots) { - /* FIXME/TODO: We need to have the extra - * memory already! (AIA) - */ - drl = ntfs_rl_realloc(drl, ds, ds + 1); - if (!drl) - goto critical_error; - } - drl[ds].vcn = marker_vcn; - drl[ds].lcn = (LCN)LCN_ENOENT; - drl[ds].length = (s64)0; - } - } - } + if (drl[ds].vcn == marker_vcn) { + ntfs_log_debug("Old marker = %lli, replacing with " + "LCN_ENOENT.\n", + (long long)drl[ds].lcn); + drl[ds].lcn = (LCN)LCN_ENOENT; + goto finished; + } + /* + * We need to create an unmapped runlist element in + * @drl or extend an existing one before adding the + * ENOENT terminator. + */ + if (drl[ds].lcn == (LCN)LCN_ENOENT) { + ds--; + slots = 1; + } + if (drl[ds].lcn != (LCN)LCN_RL_NOT_MAPPED) { + /* Add an unmapped runlist element. */ + if (!slots) { + /* FIXME/TODO: We need to have the + * extra memory already! (AIA) + */ + drl = ntfs_rl_realloc(drl, ds, ds + 2); + if (!drl) + goto critical_error; + slots = 2; + } + ds++; + /* Need to set vcn if it isn't set already. */ + if (slots != 1) + drl[ds].vcn = drl[ds - 1].vcn + + drl[ds - 1].length; + drl[ds].lcn = (LCN)LCN_RL_NOT_MAPPED; + /* We now used up a slot. */ + slots--; + } + drl[ds].length = marker_vcn - drl[ds].vcn; + /* Finally add the ENOENT terminator. */ + ds++; + if (!slots) { + /* FIXME/TODO: We need to have the extra + * memory already! (AIA) + */ + drl = ntfs_rl_realloc(drl, ds, ds + 1); + if (!drl) + goto critical_error; + } + drl[ds].vcn = marker_vcn; + drl[ds].lcn = (LCN)LCN_ENOENT; + drl[ds].length = (s64)0; + } + } + } finished: - /* The merge was completed successfully. */ - ntfs_log_debug("Merged runlist:\n"); - ntfs_debug_runlist_dump(drl); - return drl; + /* The merge was completed successfully. */ + ntfs_log_debug("Merged runlist:\n"); + ntfs_debug_runlist_dump(drl); + return drl; critical_error: - /* Critical error! We cannot afford to fail here. */ - ntfs_log_perror("libntfs: Critical error"); - ntfs_log_debug("Forcing segmentation fault!\n"); - marker_vcn = ((runlist*)NULL)->lcn; - return drl; + /* Critical error! We cannot afford to fail here. */ + ntfs_log_perror("libntfs: Critical error"); + ntfs_log_debug("Forcing segmentation fault!\n"); + marker_vcn = ((runlist*)NULL)->lcn; + return drl; } /** @@ -716,13 +727,14 @@ critical_error: * ERANGE The runlists overlap and cannot be merged. */ runlist_element *ntfs_runlists_merge(runlist_element *drl, - runlist_element *srl) { - runlist_element *rl; - - ntfs_log_enter("Entering\n"); - rl = ntfs_runlists_merge_i(drl, srl); - ntfs_log_leave("\n"); - return rl; + runlist_element *srl) +{ + runlist_element *rl; + + ntfs_log_enter("Entering\n"); + rl = ntfs_runlists_merge_i(drl, srl); + ntfs_log_leave("\n"); + return rl; } /** @@ -753,236 +765,238 @@ runlist_element *ntfs_runlists_merge(runlist_element *drl, * runlist if overlap present before returning NULL, with errno = ERANGE). */ runlist_element *ntfs_mapping_pairs_decompress_i(const ntfs_volume *vol, - const ATTR_RECORD *attr, runlist_element *old_rl) { - VCN vcn; /* Current vcn. */ - LCN lcn; /* Current lcn. */ - s64 deltaxcn; /* Change in [vl]cn. */ - runlist_element *rl; /* The output runlist. */ - const u8 *buf; /* Current position in mapping pairs array. */ - const u8 *attr_end; /* End of attribute. */ - int err, rlsize; /* Size of runlist buffer. */ - u16 rlpos; /* Current runlist position in units of + const ATTR_RECORD *attr, runlist_element *old_rl) +{ + VCN vcn; /* Current vcn. */ + LCN lcn; /* Current lcn. */ + s64 deltaxcn; /* Change in [vl]cn. */ + runlist_element *rl; /* The output runlist. */ + const u8 *buf; /* Current position in mapping pairs array. */ + const u8 *attr_end; /* End of attribute. */ + int err, rlsize; /* Size of runlist buffer. */ + u16 rlpos; /* Current runlist position in units of runlist_elements. */ - u8 b; /* Current byte offset in buf. */ + u8 b; /* Current byte offset in buf. */ - ntfs_log_trace("Entering for attr 0x%x.\n", - (unsigned)le32_to_cpu(attr->type)); - /* Make sure attr exists and is non-resident. */ - if (!attr || !attr->non_resident || - sle64_to_cpu(attr->lowest_vcn) < (VCN)0) { - errno = EINVAL; - return NULL; - } - /* Start at vcn = lowest_vcn and lcn 0. */ - vcn = sle64_to_cpu(attr->lowest_vcn); - lcn = 0; - /* Get start of the mapping pairs array. */ - buf = (const u8*)attr + le16_to_cpu(attr->mapping_pairs_offset); - attr_end = (const u8*)attr + le32_to_cpu(attr->length); - if (buf < (const u8*)attr || buf > attr_end) { - ntfs_log_debug("Corrupt attribute.\n"); - errno = EIO; - return NULL; - } - /* Current position in runlist array. */ - rlpos = 0; - /* Allocate first 4kiB block and set current runlist size to 4kiB. */ - rlsize = 0x1000; - rl = ntfs_malloc(rlsize); - if (!rl) - return NULL; - /* Insert unmapped starting element if necessary. */ - if (vcn) { - rl->vcn = (VCN)0; - rl->lcn = (LCN)LCN_RL_NOT_MAPPED; - rl->length = vcn; - rlpos++; - } - while (buf < attr_end && *buf) { - /* - * Allocate more memory if needed, including space for the - * not-mapped and terminator elements. - */ - if ((int)((rlpos + 3) * sizeof(*old_rl)) > rlsize) { - runlist_element *rl2; + ntfs_log_trace("Entering for attr 0x%x.\n", + (unsigned)le32_to_cpu(attr->type)); + /* Make sure attr exists and is non-resident. */ + if (!attr || !attr->non_resident || + sle64_to_cpu(attr->lowest_vcn) < (VCN)0) { + errno = EINVAL; + return NULL; + } + /* Start at vcn = lowest_vcn and lcn 0. */ + vcn = sle64_to_cpu(attr->lowest_vcn); + lcn = 0; + /* Get start of the mapping pairs array. */ + buf = (const u8*)attr + le16_to_cpu(attr->mapping_pairs_offset); + attr_end = (const u8*)attr + le32_to_cpu(attr->length); + if (buf < (const u8*)attr || buf > attr_end) { + ntfs_log_debug("Corrupt attribute.\n"); + errno = EIO; + return NULL; + } + /* Current position in runlist array. */ + rlpos = 0; + /* Allocate first 4kiB block and set current runlist size to 4kiB. */ + rlsize = 0x1000; + rl = ntfs_malloc(rlsize); + if (!rl) + return NULL; + /* Insert unmapped starting element if necessary. */ + if (vcn) { + rl->vcn = (VCN)0; + rl->lcn = (LCN)LCN_RL_NOT_MAPPED; + rl->length = vcn; + rlpos++; + } + while (buf < attr_end && *buf) { + /* + * Allocate more memory if needed, including space for the + * not-mapped and terminator elements. + */ + if ((int)((rlpos + 3) * sizeof(*old_rl)) > rlsize) { + runlist_element *rl2; - rlsize += 0x1000; - rl2 = realloc(rl, rlsize); - if (!rl2) { - int eo = errno; - free(rl); - errno = eo; - return NULL; - } - rl = rl2; - } - /* Enter the current vcn into the current runlist element. */ - rl[rlpos].vcn = vcn; - /* - * Get the change in vcn, i.e. the run length in clusters. - * Doing it this way ensures that we signextend negative values. - * A negative run length doesn't make any sense, but hey, I - * didn't make up the NTFS specs and Windows NT4 treats the run - * length as a signed value so that's how it is... - */ - b = *buf & 0xf; - if (b) { - if (buf + b > attr_end) - goto io_error; - for (deltaxcn = (s8)buf[b--]; b; b--) - deltaxcn = (deltaxcn << 8) + buf[b]; - } else { /* The length entry is compulsory. */ - ntfs_log_debug("Missing length entry in mapping pairs " - "array.\n"); - deltaxcn = (s64)-1; - } - /* - * Assume a negative length to indicate data corruption and - * hence clean-up and return NULL. - */ - if (deltaxcn < 0) { - ntfs_log_debug("Invalid length in mapping pairs array.\n"); - goto err_out; - } - /* - * Enter the current run length into the current runlist - * element. - */ - rl[rlpos].length = deltaxcn; - /* Increment the current vcn by the current run length. */ - vcn += deltaxcn; - /* - * There might be no lcn change at all, as is the case for - * sparse clusters on NTFS 3.0+, in which case we set the lcn - * to LCN_HOLE. - */ - if (!(*buf & 0xf0)) - rl[rlpos].lcn = (LCN)LCN_HOLE; - else { - /* Get the lcn change which really can be negative. */ - u8 b2 = *buf & 0xf; - b = b2 + ((*buf >> 4) & 0xf); - if (buf + b > attr_end) - goto io_error; - for (deltaxcn = (s8)buf[b--]; b > b2; b--) - deltaxcn = (deltaxcn << 8) + buf[b]; - /* Change the current lcn to it's new value. */ - lcn += deltaxcn; + rlsize += 0x1000; + rl2 = realloc(rl, rlsize); + if (!rl2) { + int eo = errno; + free(rl); + errno = eo; + return NULL; + } + rl = rl2; + } + /* Enter the current vcn into the current runlist element. */ + rl[rlpos].vcn = vcn; + /* + * Get the change in vcn, i.e. the run length in clusters. + * Doing it this way ensures that we signextend negative values. + * A negative run length doesn't make any sense, but hey, I + * didn't make up the NTFS specs and Windows NT4 treats the run + * length as a signed value so that's how it is... + */ + b = *buf & 0xf; + if (b) { + if (buf + b > attr_end) + goto io_error; + for (deltaxcn = (s8)buf[b--]; b; b--) + deltaxcn = (deltaxcn << 8) + buf[b]; + } else { /* The length entry is compulsory. */ + ntfs_log_debug("Missing length entry in mapping pairs " + "array.\n"); + deltaxcn = (s64)-1; + } + /* + * Assume a negative length to indicate data corruption and + * hence clean-up and return NULL. + */ + if (deltaxcn < 0) { + ntfs_log_debug("Invalid length in mapping pairs array.\n"); + goto err_out; + } + /* + * Enter the current run length into the current runlist + * element. + */ + rl[rlpos].length = deltaxcn; + /* Increment the current vcn by the current run length. */ + vcn += deltaxcn; + /* + * There might be no lcn change at all, as is the case for + * sparse clusters on NTFS 3.0+, in which case we set the lcn + * to LCN_HOLE. + */ + if (!(*buf & 0xf0)) + rl[rlpos].lcn = (LCN)LCN_HOLE; + else { + /* Get the lcn change which really can be negative. */ + u8 b2 = *buf & 0xf; + b = b2 + ((*buf >> 4) & 0xf); + if (buf + b > attr_end) + goto io_error; + for (deltaxcn = (s8)buf[b--]; b > b2; b--) + deltaxcn = (deltaxcn << 8) + buf[b]; + /* Change the current lcn to it's new value. */ + lcn += deltaxcn; #ifdef DEBUG - /* - * On NTFS 1.2-, apparently can have lcn == -1 to - * indicate a hole. But we haven't verified ourselves - * whether it is really the lcn or the deltaxcn that is - * -1. So if either is found give us a message so we - * can investigate it further! - */ - if (vol->major_ver < 3) { - if (deltaxcn == (LCN)-1) - ntfs_log_debug("lcn delta == -1\n"); - if (lcn == (LCN)-1) - ntfs_log_debug("lcn == -1\n"); - } + /* + * On NTFS 1.2-, apparently can have lcn == -1 to + * indicate a hole. But we haven't verified ourselves + * whether it is really the lcn or the deltaxcn that is + * -1. So if either is found give us a message so we + * can investigate it further! + */ + if (vol->major_ver < 3) { + if (deltaxcn == (LCN)-1) + ntfs_log_debug("lcn delta == -1\n"); + if (lcn == (LCN)-1) + ntfs_log_debug("lcn == -1\n"); + } #endif - /* Check lcn is not below -1. */ - if (lcn < (LCN)-1) { - ntfs_log_debug("Invalid LCN < -1 in mapping pairs " - "array.\n"); - goto err_out; - } - /* Enter the current lcn into the runlist element. */ - rl[rlpos].lcn = lcn; - } - /* Get to the next runlist element. */ - rlpos++; - /* Increment the buffer position to the next mapping pair. */ - buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1; - } - if (buf >= attr_end) - goto io_error; - /* - * If there is a highest_vcn specified, it must be equal to the final - * vcn in the runlist - 1, or something has gone badly wrong. - */ - deltaxcn = sle64_to_cpu(attr->highest_vcn); - if (deltaxcn && vcn - 1 != deltaxcn) { + /* Check lcn is not below -1. */ + if (lcn < (LCN)-1) { + ntfs_log_debug("Invalid LCN < -1 in mapping pairs " + "array.\n"); + goto err_out; + } + /* Enter the current lcn into the runlist element. */ + rl[rlpos].lcn = lcn; + } + /* Get to the next runlist element. */ + rlpos++; + /* Increment the buffer position to the next mapping pair. */ + buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1; + } + if (buf >= attr_end) + goto io_error; + /* + * If there is a highest_vcn specified, it must be equal to the final + * vcn in the runlist - 1, or something has gone badly wrong. + */ + deltaxcn = sle64_to_cpu(attr->highest_vcn); + if (deltaxcn && vcn - 1 != deltaxcn) { mpa_err: - ntfs_log_debug("Corrupt mapping pairs array in non-resident " - "attribute.\n"); - goto err_out; - } - /* Setup not mapped runlist element if this is the base extent. */ - if (!attr->lowest_vcn) { - VCN max_cluster; + ntfs_log_debug("Corrupt mapping pairs array in non-resident " + "attribute.\n"); + goto err_out; + } + /* Setup not mapped runlist element if this is the base extent. */ + if (!attr->lowest_vcn) { + VCN max_cluster; - max_cluster = ((sle64_to_cpu(attr->allocated_size) + - vol->cluster_size - 1) >> - vol->cluster_size_bits) - 1; - /* - * A highest_vcn of zero means this is a single extent - * attribute so simply terminate the runlist with LCN_ENOENT). - */ - if (deltaxcn) { - /* - * If there is a difference between the highest_vcn and - * the highest cluster, the runlist is either corrupt - * or, more likely, there are more extents following - * this one. - */ - if (deltaxcn < max_cluster) { - ntfs_log_debug("More extents to follow; deltaxcn = " - "0x%llx, max_cluster = 0x%llx\n", - (long long)deltaxcn, - (long long)max_cluster); - rl[rlpos].vcn = vcn; - vcn += rl[rlpos].length = max_cluster - deltaxcn; - rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED; - rlpos++; - } else if (deltaxcn > max_cluster) { - ntfs_log_debug("Corrupt attribute. deltaxcn = " - "0x%llx, max_cluster = 0x%llx\n", - (long long)deltaxcn, - (long long)max_cluster); - goto mpa_err; - } - } - rl[rlpos].lcn = (LCN)LCN_ENOENT; - } else /* Not the base extent. There may be more extents to follow. */ - rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED; + max_cluster = ((sle64_to_cpu(attr->allocated_size) + + vol->cluster_size - 1) >> + vol->cluster_size_bits) - 1; + /* + * A highest_vcn of zero means this is a single extent + * attribute so simply terminate the runlist with LCN_ENOENT). + */ + if (deltaxcn) { + /* + * If there is a difference between the highest_vcn and + * the highest cluster, the runlist is either corrupt + * or, more likely, there are more extents following + * this one. + */ + if (deltaxcn < max_cluster) { + ntfs_log_debug("More extents to follow; deltaxcn = " + "0x%llx, max_cluster = 0x%llx\n", + (long long)deltaxcn, + (long long)max_cluster); + rl[rlpos].vcn = vcn; + vcn += rl[rlpos].length = max_cluster - deltaxcn; + rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED; + rlpos++; + } else if (deltaxcn > max_cluster) { + ntfs_log_debug("Corrupt attribute. deltaxcn = " + "0x%llx, max_cluster = 0x%llx\n", + (long long)deltaxcn, + (long long)max_cluster); + goto mpa_err; + } + } + rl[rlpos].lcn = (LCN)LCN_ENOENT; + } else /* Not the base extent. There may be more extents to follow. */ + rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED; - /* Setup terminating runlist element. */ - rl[rlpos].vcn = vcn; - rl[rlpos].length = (s64)0; - /* If no existing runlist was specified, we are done. */ - if (!old_rl) { - ntfs_log_debug("Mapping pairs array successfully decompressed:\n"); - ntfs_debug_runlist_dump(rl); - return rl; - } - /* Now combine the new and old runlists checking for overlaps. */ - old_rl = ntfs_runlists_merge(old_rl, rl); - if (old_rl) - return old_rl; - err = errno; - free(rl); - ntfs_log_debug("Failed to merge runlists.\n"); - errno = err; - return NULL; + /* Setup terminating runlist element. */ + rl[rlpos].vcn = vcn; + rl[rlpos].length = (s64)0; + /* If no existing runlist was specified, we are done. */ + if (!old_rl) { + ntfs_log_debug("Mapping pairs array successfully decompressed:\n"); + ntfs_debug_runlist_dump(rl); + return rl; + } + /* Now combine the new and old runlists checking for overlaps. */ + old_rl = ntfs_runlists_merge(old_rl, rl); + if (old_rl) + return old_rl; + err = errno; + free(rl); + ntfs_log_debug("Failed to merge runlists.\n"); + errno = err; + return NULL; io_error: - ntfs_log_debug("Corrupt attribute.\n"); + ntfs_log_debug("Corrupt attribute.\n"); err_out: - free(rl); - errno = EIO; - return NULL; + free(rl); + errno = EIO; + return NULL; } runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, - const ATTR_RECORD *attr, runlist_element *old_rl) { - runlist_element *rle; - - ntfs_log_enter("Entering\n"); - rle = ntfs_mapping_pairs_decompress_i(vol, attr, old_rl); - ntfs_log_leave("\n"); - return rle; + const ATTR_RECORD *attr, runlist_element *old_rl) +{ + runlist_element *rle; + + ntfs_log_enter("Entering\n"); + rle = ntfs_mapping_pairs_decompress_i(vol, attr, old_rl); + ntfs_log_leave("\n"); + return rle; } /** @@ -1004,38 +1018,39 @@ runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, * -3 = LCN_ENOENT There is no such vcn in the attribute. * -4 = LCN_EINVAL Input parameter error. */ -LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn) { - int i; +LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn) +{ + int i; - if (vcn < (VCN)0) - return (LCN)LCN_EINVAL; - /* - * If rl is NULL, assume that we have found an unmapped runlist. The - * caller can then attempt to map it and fail appropriately if - * necessary. - */ - if (!rl) - return (LCN)LCN_RL_NOT_MAPPED; + if (vcn < (VCN)0) + return (LCN)LCN_EINVAL; + /* + * If rl is NULL, assume that we have found an unmapped runlist. The + * caller can then attempt to map it and fail appropriately if + * necessary. + */ + if (!rl) + return (LCN)LCN_RL_NOT_MAPPED; - /* Catch out of lower bounds vcn. */ - if (vcn < rl[0].vcn) - return (LCN)LCN_ENOENT; + /* Catch out of lower bounds vcn. */ + if (vcn < rl[0].vcn) + return (LCN)LCN_ENOENT; - for (i = 0; rl[i].length; i++) { - if (vcn < rl[i+1].vcn) { - if (rl[i].lcn >= (LCN)0) - return rl[i].lcn + (vcn - rl[i].vcn); - return rl[i].lcn; - } - } - /* - * The terminator element is setup to the correct value, i.e. one of - * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT. - */ - if (rl[i].lcn < (LCN)0) - return rl[i].lcn; - /* Just in case... We could replace this with BUG() some day. */ - return (LCN)LCN_ENOENT; + for (i = 0; rl[i].length; i++) { + if (vcn < rl[i+1].vcn) { + if (rl[i].lcn >= (LCN)0) + return rl[i].lcn + (vcn - rl[i].vcn); + return rl[i].lcn; + } + } + /* + * The terminator element is setup to the correct value, i.e. one of + * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT. + */ + if (rl[i].lcn < (LCN)0) + return rl[i].lcn; + /* Just in case... We could replace this with BUG() some day. */ + return (LCN)LCN_ENOENT; } /** @@ -1063,68 +1078,69 @@ LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn) { * the run list must point to valid locations within the ntfs volume. */ s64 ntfs_rl_pread(const ntfs_volume *vol, const runlist_element *rl, - const s64 pos, s64 count, void *b) { - s64 bytes_read, to_read, ofs, total; - int err = EIO; + const s64 pos, s64 count, void *b) +{ + s64 bytes_read, to_read, ofs, total; + int err = EIO; - if (!vol || !rl || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("Failed to read runlist [vol: %p rl: %p " - "pos: %lld count: %lld]", vol, rl, - (long long)pos, (long long)count); - return -1; - } - if (!count) - return count; - /* Seek in @rl to the run containing @pos. */ - for (ofs = 0; rl->length && (ofs + (rl->length << - vol->cluster_size_bits) <= pos); rl++) - ofs += (rl->length << vol->cluster_size_bits); - /* Offset in the run at which to begin reading. */ - ofs = pos - ofs; - for (total = 0LL; count; rl++, ofs = 0) { - if (!rl->length) - goto rl_err_out; - if (rl->lcn < (LCN)0) { - if (rl->lcn != (LCN)LCN_HOLE) - goto rl_err_out; - /* It is a hole. Just fill buffer @b with zeroes. */ - to_read = min(count, (rl->length << - vol->cluster_size_bits) - ofs); - memset(b, 0, to_read); - /* Update counters and proceed with next run. */ - total += to_read; - count -= to_read; - b = (u8*)b + to_read; - continue; - } - /* It is a real lcn, read it from the volume. */ - to_read = min(count, (rl->length << vol->cluster_size_bits) - - ofs); + if (!vol || !rl || pos < 0 || count < 0) { + errno = EINVAL; + ntfs_log_perror("Failed to read runlist [vol: %p rl: %p " + "pos: %lld count: %lld]", vol, rl, + (long long)pos, (long long)count); + return -1; + } + if (!count) + return count; + /* Seek in @rl to the run containing @pos. */ + for (ofs = 0; rl->length && (ofs + (rl->length << + vol->cluster_size_bits) <= pos); rl++) + ofs += (rl->length << vol->cluster_size_bits); + /* Offset in the run at which to begin reading. */ + ofs = pos - ofs; + for (total = 0LL; count; rl++, ofs = 0) { + if (!rl->length) + goto rl_err_out; + if (rl->lcn < (LCN)0) { + if (rl->lcn != (LCN)LCN_HOLE) + goto rl_err_out; + /* It is a hole. Just fill buffer @b with zeroes. */ + to_read = min(count, (rl->length << + vol->cluster_size_bits) - ofs); + memset(b, 0, to_read); + /* Update counters and proceed with next run. */ + total += to_read; + count -= to_read; + b = (u8*)b + to_read; + continue; + } + /* It is a real lcn, read it from the volume. */ + to_read = min(count, (rl->length << vol->cluster_size_bits) - + ofs); retry: - bytes_read = ntfs_pread(vol->dev, (rl->lcn << - vol->cluster_size_bits) + ofs, to_read, b); - /* If everything ok, update progress counters and continue. */ - if (bytes_read > 0) { - total += bytes_read; - count -= bytes_read; - b = (u8*)b + bytes_read; - continue; - } - /* If the syscall was interrupted, try again. */ - if (bytes_read == (s64)-1 && errno == EINTR) - goto retry; - if (bytes_read == (s64)-1) - err = errno; - goto rl_err_out; - } - /* Finally, return the number of bytes read. */ - return total; + bytes_read = ntfs_pread(vol->dev, (rl->lcn << + vol->cluster_size_bits) + ofs, to_read, b); + /* If everything ok, update progress counters and continue. */ + if (bytes_read > 0) { + total += bytes_read; + count -= bytes_read; + b = (u8*)b + bytes_read; + continue; + } + /* If the syscall was interrupted, try again. */ + if (bytes_read == (s64)-1 && errno == EINTR) + goto retry; + if (bytes_read == (s64)-1) + err = errno; + goto rl_err_out; + } + /* Finally, return the number of bytes read. */ + return total; rl_err_out: - if (total) - return total; - errno = err; - return -1; + if (total) + return total; + errno = err; + return -1; } /** @@ -1151,76 +1167,77 @@ rl_err_out: * of invalid arguments. */ s64 ntfs_rl_pwrite(const ntfs_volume *vol, const runlist_element *rl, - s64 ofs, const s64 pos, s64 count, void *b) { - s64 written, to_write, total = 0; - int err = EIO; + s64 ofs, const s64 pos, s64 count, void *b) +{ + s64 written, to_write, total = 0; + int err = EIO; - if (!vol || !rl || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("Failed to write runlist [vol: %p rl: %p " - "pos: %lld count: %lld]", vol, rl, - (long long)pos, (long long)count); - goto errno_set; - } - if (!count) - goto out; - /* Seek in @rl to the run containing @pos. */ - while (rl->length && (ofs + (rl->length << - vol->cluster_size_bits) <= pos)) { - ofs += (rl->length << vol->cluster_size_bits); - rl++; - } - /* Offset in the run at which to begin writing. */ - ofs = pos - ofs; - for (total = 0LL; count; rl++, ofs = 0) { - if (!rl->length) - goto rl_err_out; - if (rl->lcn < (LCN)0) { + if (!vol || !rl || pos < 0 || count < 0) { + errno = EINVAL; + ntfs_log_perror("Failed to write runlist [vol: %p rl: %p " + "pos: %lld count: %lld]", vol, rl, + (long long)pos, (long long)count); + goto errno_set; + } + if (!count) + goto out; + /* Seek in @rl to the run containing @pos. */ + while (rl->length && (ofs + (rl->length << + vol->cluster_size_bits) <= pos)) { + ofs += (rl->length << vol->cluster_size_bits); + rl++; + } + /* Offset in the run at which to begin writing. */ + ofs = pos - ofs; + for (total = 0LL; count; rl++, ofs = 0) { + if (!rl->length) + goto rl_err_out; + if (rl->lcn < (LCN)0) { - if (rl->lcn != (LCN)LCN_HOLE) - goto rl_err_out; - - to_write = min(count, (rl->length << - vol->cluster_size_bits) - ofs); - - total += to_write; - count -= to_write; - b = (u8*)b + to_write; - continue; - } - /* It is a real lcn, write it to the volume. */ - to_write = min(count, (rl->length << vol->cluster_size_bits) - - ofs); + if (rl->lcn != (LCN)LCN_HOLE) + goto rl_err_out; + + to_write = min(count, (rl->length << + vol->cluster_size_bits) - ofs); + + total += to_write; + count -= to_write; + b = (u8*)b + to_write; + continue; + } + /* It is a real lcn, write it to the volume. */ + to_write = min(count, (rl->length << vol->cluster_size_bits) - + ofs); retry: - if (!NVolReadOnly(vol)) - written = ntfs_pwrite(vol->dev, (rl->lcn << - vol->cluster_size_bits) + ofs, - to_write, b); - else - written = to_write; - /* If everything ok, update progress counters and continue. */ - if (written > 0) { - total += written; - count -= written; - b = (u8*)b + written; - continue; - } - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (written == (s64)-1) - err = errno; - goto rl_err_out; - } + if (!NVolReadOnly(vol)) + written = ntfs_pwrite(vol->dev, (rl->lcn << + vol->cluster_size_bits) + ofs, + to_write, b); + else + written = to_write; + /* If everything ok, update progress counters and continue. */ + if (written > 0) { + total += written; + count -= written; + b = (u8*)b + written; + continue; + } + /* If the syscall was interrupted, try again. */ + if (written == (s64)-1 && errno == EINTR) + goto retry; + if (written == (s64)-1) + err = errno; + goto rl_err_out; + } out: - return total; + return total; rl_err_out: - if (total) - goto out; - errno = err; + if (total) + goto out; + errno = err; errno_set: - total = -1; - goto out; + total = -1; + goto out; } /** @@ -1236,20 +1253,21 @@ errno_set: * * Return the number of bytes written. This function cannot fail. */ -int ntfs_get_nr_significant_bytes(const s64 n) { - u64 l; - int i; +int ntfs_get_nr_significant_bytes(const s64 n) +{ + u64 l; + int i; - l = (n < 0 ? ~n : n); - i = 1; - if (l >= 128) { - l >>= 7; - do { - i++; - l >>= 8; - } while (l); - } - return i; + l = (n < 0 ? ~n : n); + i = 1; + if (l >= 128) { + l >>= 7; + do { + i++; + l >>= 8; + } while (l); + } + return i; } /** @@ -1273,93 +1291,94 @@ int ntfs_get_nr_significant_bytes(const s64 n) { * EIO - The runlist is corrupt. */ int ntfs_get_size_for_mapping_pairs(const ntfs_volume *vol, - const runlist_element *rl, const VCN start_vcn, int max_size) { - LCN prev_lcn; - int rls; + const runlist_element *rl, const VCN start_vcn, int max_size) +{ + LCN prev_lcn; + int rls; - if (start_vcn < 0) { - ntfs_log_trace("start_vcn %lld (should be >= 0)\n", - (long long) start_vcn); - errno = EINVAL; - goto errno_set; - } - if (!rl) { - if (start_vcn) { - ntfs_log_trace("rl NULL, start_vcn %lld (should be > 0)\n", - (long long) start_vcn); - errno = EINVAL; - goto errno_set; - } - rls = 1; - goto out; - } - /* Skip to runlist element containing @start_vcn. */ - while (rl->length && start_vcn >= rl[1].vcn) - rl++; - if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn) { - errno = EINVAL; - goto errno_set; - } - prev_lcn = 0; - /* Always need the terminating zero byte. */ - rls = 1; - /* Do the first partial run if present. */ - if (start_vcn > rl->vcn) { - s64 delta; + if (start_vcn < 0) { + ntfs_log_trace("start_vcn %lld (should be >= 0)\n", + (long long) start_vcn); + errno = EINVAL; + goto errno_set; + } + if (!rl) { + if (start_vcn) { + ntfs_log_trace("rl NULL, start_vcn %lld (should be > 0)\n", + (long long) start_vcn); + errno = EINVAL; + goto errno_set; + } + rls = 1; + goto out; + } + /* Skip to runlist element containing @start_vcn. */ + while (rl->length && start_vcn >= rl[1].vcn) + rl++; + if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn) { + errno = EINVAL; + goto errno_set; + } + prev_lcn = 0; + /* Always need the terminating zero byte. */ + rls = 1; + /* Do the first partial run if present. */ + if (start_vcn > rl->vcn) { + s64 delta; - /* We know rl->length != 0 already. */ - if (rl->length < 0 || rl->lcn < LCN_HOLE) - goto err_out; - delta = start_vcn - rl->vcn; - /* Header byte + length. */ - rls += 1 + ntfs_get_nr_significant_bytes(rl->length - delta); - /* - * If the logical cluster number (lcn) denotes a hole and we - * are on NTFS 3.0+, we don't store it at all, i.e. we need - * zero space. On earlier NTFS versions we just store the lcn. - * Note: this assumes that on NTFS 1.2-, holes are stored with - * an lcn of -1 and not a delta_lcn of -1 (unless both are -1). - */ - if (rl->lcn >= 0 || vol->major_ver < 3) { - prev_lcn = rl->lcn; - if (rl->lcn >= 0) - prev_lcn += delta; - /* Change in lcn. */ - rls += ntfs_get_nr_significant_bytes(prev_lcn); - } - /* Go to next runlist element. */ - rl++; - } - /* Do the full runs. */ - for (; rl->length && (rls <= max_size); rl++) { - if (rl->length < 0 || rl->lcn < LCN_HOLE) - goto err_out; - /* Header byte + length. */ - rls += 1 + ntfs_get_nr_significant_bytes(rl->length); - /* - * If the logical cluster number (lcn) denotes a hole and we - * are on NTFS 3.0+, we don't store it at all, i.e. we need - * zero space. On earlier NTFS versions we just store the lcn. - * Note: this assumes that on NTFS 1.2-, holes are stored with - * an lcn of -1 and not a delta_lcn of -1 (unless both are -1). - */ - if (rl->lcn >= 0 || vol->major_ver < 3) { - /* Change in lcn. */ - rls += ntfs_get_nr_significant_bytes(rl->lcn - - prev_lcn); - prev_lcn = rl->lcn; - } - } -out: - return rls; + /* We know rl->length != 0 already. */ + if (rl->length < 0 || rl->lcn < LCN_HOLE) + goto err_out; + delta = start_vcn - rl->vcn; + /* Header byte + length. */ + rls += 1 + ntfs_get_nr_significant_bytes(rl->length - delta); + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just store the lcn. + * Note: this assumes that on NTFS 1.2-, holes are stored with + * an lcn of -1 and not a delta_lcn of -1 (unless both are -1). + */ + if (rl->lcn >= 0 || vol->major_ver < 3) { + prev_lcn = rl->lcn; + if (rl->lcn >= 0) + prev_lcn += delta; + /* Change in lcn. */ + rls += ntfs_get_nr_significant_bytes(prev_lcn); + } + /* Go to next runlist element. */ + rl++; + } + /* Do the full runs. */ + for (; rl->length && (rls <= max_size); rl++) { + if (rl->length < 0 || rl->lcn < LCN_HOLE) + goto err_out; + /* Header byte + length. */ + rls += 1 + ntfs_get_nr_significant_bytes(rl->length); + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just store the lcn. + * Note: this assumes that on NTFS 1.2-, holes are stored with + * an lcn of -1 and not a delta_lcn of -1 (unless both are -1). + */ + if (rl->lcn >= 0 || vol->major_ver < 3) { + /* Change in lcn. */ + rls += ntfs_get_nr_significant_bytes(rl->lcn - + prev_lcn); + prev_lcn = rl->lcn; + } + } +out: + return rls; err_out: - if (rl->lcn == LCN_RL_NOT_MAPPED) - errno = EINVAL; - else - errno = EIO; -errno_set: - rls = -1; - goto out; + if (rl->lcn == LCN_RL_NOT_MAPPED) + errno = EINVAL; + else + errno = EIO; +errno_set: + rls = -1; + goto out; } /** @@ -1380,36 +1399,37 @@ errno_set: * Return the number of bytes written on success. On error, i.e. the * destination buffer @dst is too small, return -1 with errno set ENOSPC. */ -int ntfs_write_significant_bytes(u8 *dst, const u8 *dst_max, const s64 n) { - s64 l = n; - int i; - s8 j; +int ntfs_write_significant_bytes(u8 *dst, const u8 *dst_max, const s64 n) +{ + s64 l = n; + int i; + s8 j; - i = 0; - do { - if (dst > dst_max) - goto err_out; - *dst++ = l & 0xffLL; - l >>= 8; - i++; - } while (l != 0LL && l != -1LL); - j = (n >> 8 * (i - 1)) & 0xff; - /* If the sign bit is wrong, we need an extra byte. */ - if (n < 0LL && j >= 0) { - if (dst > dst_max) - goto err_out; - i++; - *dst = (u8)-1; - } else if (n > 0LL && j < 0) { - if (dst > dst_max) - goto err_out; - i++; - *dst = 0; - } - return i; + i = 0; + do { + if (dst > dst_max) + goto err_out; + *dst++ = l & 0xffLL; + l >>= 8; + i++; + } while (l != 0LL && l != -1LL); + j = (n >> 8 * (i - 1)) & 0xff; + /* If the sign bit is wrong, we need an extra byte. */ + if (n < 0LL && j >= 0) { + if (dst > dst_max) + goto err_out; + i++; + *dst = (u8)-1; + } else if (n > 0LL && j < 0) { + if (dst > dst_max) + goto err_out; + i++; + *dst = 0; + } + return i; err_out: - errno = ENOSPC; - return -1; + errno = ENOSPC; + return -1; } /** @@ -1444,141 +1464,142 @@ err_out: * ENOSPC - The destination buffer is too small. */ int ntfs_mapping_pairs_build(const ntfs_volume *vol, u8 *dst, - const int dst_len, const runlist_element *rl, - const VCN start_vcn, runlist_element const **stop_rl) { - LCN prev_lcn; - u8 *dst_max, *dst_next; - s8 len_len, lcn_len; - int ret = 0; + const int dst_len, const runlist_element *rl, + const VCN start_vcn, runlist_element const **stop_rl) +{ + LCN prev_lcn; + u8 *dst_max, *dst_next; + s8 len_len, lcn_len; + int ret = 0; - if (start_vcn < 0) - goto val_err; - if (!rl) { - if (start_vcn) - goto val_err; - if (stop_rl) - *stop_rl = rl; - if (dst_len < 1) - goto nospc_err; - goto ok; - } - /* Skip to runlist element containing @start_vcn. */ - while (rl->length && start_vcn >= rl[1].vcn) - rl++; - if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn) - goto val_err; - /* - * @dst_max is used for bounds checking in - * ntfs_write_significant_bytes(). - */ - dst_max = dst + dst_len - 1; - prev_lcn = 0; - /* Do the first partial run if present. */ - if (start_vcn > rl->vcn) { - s64 delta; + if (start_vcn < 0) + goto val_err; + if (!rl) { + if (start_vcn) + goto val_err; + if (stop_rl) + *stop_rl = rl; + if (dst_len < 1) + goto nospc_err; + goto ok; + } + /* Skip to runlist element containing @start_vcn. */ + while (rl->length && start_vcn >= rl[1].vcn) + rl++; + if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn) + goto val_err; + /* + * @dst_max is used for bounds checking in + * ntfs_write_significant_bytes(). + */ + dst_max = dst + dst_len - 1; + prev_lcn = 0; + /* Do the first partial run if present. */ + if (start_vcn > rl->vcn) { + s64 delta; - /* We know rl->length != 0 already. */ - if (rl->length < 0 || rl->lcn < LCN_HOLE) - goto err_out; - delta = start_vcn - rl->vcn; - /* Write length. */ - len_len = ntfs_write_significant_bytes(dst + 1, dst_max, - rl->length - delta); - if (len_len < 0) - goto size_err; - /* - * If the logical cluster number (lcn) denotes a hole and we - * are on NTFS 3.0+, we don't store it at all, i.e. we need - * zero space. On earlier NTFS versions we just write the lcn - * change. FIXME: Do we need to write the lcn change or just - * the lcn in that case? Not sure as I have never seen this - * case on NT4. - We assume that we just need to write the lcn - * change until someone tells us otherwise... (AIA) - */ - if (rl->lcn >= 0 || vol->major_ver < 3) { - prev_lcn = rl->lcn; - if (rl->lcn >= 0) - prev_lcn += delta; - /* Write change in lcn. */ - lcn_len = ntfs_write_significant_bytes(dst + 1 + - len_len, dst_max, prev_lcn); - if (lcn_len < 0) - goto size_err; - } else - lcn_len = 0; - dst_next = dst + len_len + lcn_len + 1; - if (dst_next > dst_max) - goto size_err; - /* Update header byte. */ - *dst = lcn_len << 4 | len_len; - /* Position at next mapping pairs array element. */ - dst = dst_next; - /* Go to next runlist element. */ - rl++; - } - /* Do the full runs. */ - for (; rl->length; rl++) { - if (rl->length < 0 || rl->lcn < LCN_HOLE) - goto err_out; - /* Write length. */ - len_len = ntfs_write_significant_bytes(dst + 1, dst_max, - rl->length); - if (len_len < 0) - goto size_err; - /* - * If the logical cluster number (lcn) denotes a hole and we - * are on NTFS 3.0+, we don't store it at all, i.e. we need - * zero space. On earlier NTFS versions we just write the lcn - * change. FIXME: Do we need to write the lcn change or just - * the lcn in that case? Not sure as I have never seen this - * case on NT4. - We assume that we just need to write the lcn - * change until someone tells us otherwise... (AIA) - */ - if (rl->lcn >= 0 || vol->major_ver < 3) { - /* Write change in lcn. */ - lcn_len = ntfs_write_significant_bytes(dst + 1 + - len_len, dst_max, rl->lcn - prev_lcn); - if (lcn_len < 0) - goto size_err; - prev_lcn = rl->lcn; - } else - lcn_len = 0; - dst_next = dst + len_len + lcn_len + 1; - if (dst_next > dst_max) - goto size_err; - /* Update header byte. */ - *dst = lcn_len << 4 | len_len; - /* Position at next mapping pairs array element. */ - dst += 1 + len_len + lcn_len; - } - /* Set stop vcn. */ - if (stop_rl) - *stop_rl = rl; -ok: - /* Add terminator byte. */ - *dst = 0; + /* We know rl->length != 0 already. */ + if (rl->length < 0 || rl->lcn < LCN_HOLE) + goto err_out; + delta = start_vcn - rl->vcn; + /* Write length. */ + len_len = ntfs_write_significant_bytes(dst + 1, dst_max, + rl->length - delta); + if (len_len < 0) + goto size_err; + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just write the lcn + * change. FIXME: Do we need to write the lcn change or just + * the lcn in that case? Not sure as I have never seen this + * case on NT4. - We assume that we just need to write the lcn + * change until someone tells us otherwise... (AIA) + */ + if (rl->lcn >= 0 || vol->major_ver < 3) { + prev_lcn = rl->lcn; + if (rl->lcn >= 0) + prev_lcn += delta; + /* Write change in lcn. */ + lcn_len = ntfs_write_significant_bytes(dst + 1 + + len_len, dst_max, prev_lcn); + if (lcn_len < 0) + goto size_err; + } else + lcn_len = 0; + dst_next = dst + len_len + lcn_len + 1; + if (dst_next > dst_max) + goto size_err; + /* Update header byte. */ + *dst = lcn_len << 4 | len_len; + /* Position at next mapping pairs array element. */ + dst = dst_next; + /* Go to next runlist element. */ + rl++; + } + /* Do the full runs. */ + for (; rl->length; rl++) { + if (rl->length < 0 || rl->lcn < LCN_HOLE) + goto err_out; + /* Write length. */ + len_len = ntfs_write_significant_bytes(dst + 1, dst_max, + rl->length); + if (len_len < 0) + goto size_err; + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just write the lcn + * change. FIXME: Do we need to write the lcn change or just + * the lcn in that case? Not sure as I have never seen this + * case on NT4. - We assume that we just need to write the lcn + * change until someone tells us otherwise... (AIA) + */ + if (rl->lcn >= 0 || vol->major_ver < 3) { + /* Write change in lcn. */ + lcn_len = ntfs_write_significant_bytes(dst + 1 + + len_len, dst_max, rl->lcn - prev_lcn); + if (lcn_len < 0) + goto size_err; + prev_lcn = rl->lcn; + } else + lcn_len = 0; + dst_next = dst + len_len + lcn_len + 1; + if (dst_next > dst_max) + goto size_err; + /* Update header byte. */ + *dst = lcn_len << 4 | len_len; + /* Position at next mapping pairs array element. */ + dst += 1 + len_len + lcn_len; + } + /* Set stop vcn. */ + if (stop_rl) + *stop_rl = rl; +ok: + /* Add terminator byte. */ + *dst = 0; out: - return ret; + return ret; size_err: - /* Set stop vcn. */ - if (stop_rl) - *stop_rl = rl; - /* Add terminator byte. */ - *dst = 0; + /* Set stop vcn. */ + if (stop_rl) + *stop_rl = rl; + /* Add terminator byte. */ + *dst = 0; nospc_err: - errno = ENOSPC; - goto errno_set; + errno = ENOSPC; + goto errno_set; val_err: - errno = EINVAL; - goto errno_set; + errno = EINVAL; + goto errno_set; err_out: - if (rl->lcn == LCN_RL_NOT_MAPPED) - errno = EINVAL; - else - errno = EIO; + if (rl->lcn == LCN_RL_NOT_MAPPED) + errno = EINVAL; + else + errno = EIO; errno_set: - ret = -1; - goto out; + ret = -1; + goto out; } /** @@ -1594,67 +1615,68 @@ errno_set: * NOTE: @arl is the address of the runlist. We need the address so we can * modify the pointer to the runlist with the new, reallocated memory buffer. */ -int ntfs_rl_truncate(runlist **arl, const VCN start_vcn) { - runlist *rl; - BOOL is_end = FALSE; +int ntfs_rl_truncate(runlist **arl, const VCN start_vcn) +{ + runlist *rl; + BOOL is_end = FALSE; - if (!arl || !*arl) { - errno = EINVAL; - ntfs_log_perror("rl_truncate error: arl: %p *arl: %p", arl, *arl); - return -1; - } - - rl = *arl; - - if (start_vcn < rl->vcn) { - errno = EINVAL; - ntfs_log_perror("Start_vcn lies outside front of runlist"); - return -1; - } - - /* Find the starting vcn in the run list. */ - while (rl->length) { - if (start_vcn < rl[1].vcn) - break; - rl++; - } - - if (!rl->length) { - errno = EIO; - ntfs_log_trace("Truncating already truncated runlist?\n"); - return -1; - } - - /* Truncate the run. */ - rl->length = start_vcn - rl->vcn; - - /* - * If a run was partially truncated, make the following runlist - * element a terminator instead of the truncated runlist - * element itself. - */ - if (rl->length) { - ++rl; - if (!rl->length) - is_end = TRUE; - rl->vcn = start_vcn; - rl->length = 0; - } - rl->lcn = (LCN)LCN_ENOENT; - /** - * Reallocate memory if necessary. - * FIXME: Below code is broken, because runlist allocations must be - * a multiply of 4096. The code caused crashes and corruptions. - */ - /* - if (!is_end) { - size_t new_size = (rl - *arl + 1) * sizeof(runlist_element); - rl = realloc(*arl, new_size); - if (rl) - *arl = rl; - } - */ - return 0; + if (!arl || !*arl) { + errno = EINVAL; + ntfs_log_perror("rl_truncate error: arl: %p *arl: %p", arl, *arl); + return -1; + } + + rl = *arl; + + if (start_vcn < rl->vcn) { + errno = EINVAL; + ntfs_log_perror("Start_vcn lies outside front of runlist"); + return -1; + } + + /* Find the starting vcn in the run list. */ + while (rl->length) { + if (start_vcn < rl[1].vcn) + break; + rl++; + } + + if (!rl->length) { + errno = EIO; + ntfs_log_trace("Truncating already truncated runlist?\n"); + return -1; + } + + /* Truncate the run. */ + rl->length = start_vcn - rl->vcn; + + /* + * If a run was partially truncated, make the following runlist + * element a terminator instead of the truncated runlist + * element itself. + */ + if (rl->length) { + ++rl; + if (!rl->length) + is_end = TRUE; + rl->vcn = start_vcn; + rl->length = 0; + } + rl->lcn = (LCN)LCN_ENOENT; + /** + * Reallocate memory if necessary. + * FIXME: Below code is broken, because runlist allocations must be + * a multiply of 4096. The code caused crashes and corruptions. + */ +/* + if (!is_end) { + size_t new_size = (rl - *arl + 1) * sizeof(runlist_element); + rl = realloc(*arl, new_size); + if (rl) + *arl = rl; + } +*/ + return 0; } /** @@ -1663,25 +1685,26 @@ int ntfs_rl_truncate(runlist **arl, const VCN start_vcn) { * * Return 1 if have, 0 if not, -1 on error with errno set to the error code. */ -int ntfs_rl_sparse(runlist *rl) { - runlist *rlc; +int ntfs_rl_sparse(runlist *rl) +{ + runlist *rlc; - if (!rl) { - errno = EINVAL; - ntfs_log_perror("%s: ", __FUNCTION__); - return -1; - } + if (!rl) { + errno = EINVAL; + ntfs_log_perror("%s: ", __FUNCTION__); + return -1; + } - for (rlc = rl; rlc->length; rlc++) - if (rlc->lcn < 0) { - if (rlc->lcn != LCN_HOLE) { - errno = EINVAL; - ntfs_log_perror("%s: bad runlist", __FUNCTION__); - return -1; - } - return 1; - } - return 0; + for (rlc = rl; rlc->length; rlc++) + if (rlc->lcn < 0) { + if (rlc->lcn != LCN_HOLE) { + errno = EINVAL; + ntfs_log_perror("%s: bad runlist", __FUNCTION__); + return -1; + } + return 1; + } + return 0; } /** @@ -1691,27 +1714,28 @@ int ntfs_rl_sparse(runlist *rl) { * * Return compressed size or -1 on error with errno set to the error code. */ -s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) { - runlist *rlc; - s64 ret = 0; +s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) +{ + runlist *rlc; + s64 ret = 0; - if (!rl) { - errno = EINVAL; - ntfs_log_perror("%s: ", __FUNCTION__); - return -1; - } + if (!rl) { + errno = EINVAL; + ntfs_log_perror("%s: ", __FUNCTION__); + return -1; + } - for (rlc = rl; rlc->length; rlc++) { - if (rlc->lcn < 0) { - if (rlc->lcn != LCN_HOLE) { - errno = EINVAL; - ntfs_log_perror("%s: bad runlist", __FUNCTION__); - return -1; - } - } else - ret += rlc->length; - } - return ret << vol->cluster_size_bits; + for (rlc = rl; rlc->length; rlc++) { + if (rlc->lcn < 0) { + if (rlc->lcn != LCN_HOLE) { + errno = EINVAL; + ntfs_log_perror("%s: bad runlist", __FUNCTION__); + return -1; + } + } else + ret += rlc->length; + } + return ret << vol->cluster_size_bits; } @@ -1734,47 +1758,48 @@ s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) { * * Returns: */ -static void test_rl_dump_runlist(const runlist_element *rl) { - int abbr = 0; /* abbreviate long lists */ - int len = 0; - int i; - const char *lcn_str[5] = { "HOLE", "NOTMAP", "ENOENT", "XXXX" }; +static void test_rl_dump_runlist(const runlist_element *rl) +{ + int abbr = 0; /* abbreviate long lists */ + int len = 0; + int i; + const char *lcn_str[5] = { "HOLE", "NOTMAP", "ENOENT", "XXXX" }; - if (!rl) { - printf(" Run list not present.\n"); - return; - } + if (!rl) { + printf(" Run list not present.\n"); + return; + } - if (abbr) - for (len = 0; rl[len].length; len++) ; + if (abbr) + for (len = 0; rl[len].length; len++) ; - printf(" VCN LCN len\n"); - for (i = 0; ; i++, rl++) { - LCN lcn = rl->lcn; + printf(" VCN LCN len\n"); + for (i = 0; ; i++, rl++) { + LCN lcn = rl->lcn; - if ((abbr) && (len > 20)) { - if (i == 4) - printf(" ...\n"); - if ((i > 3) && (i < (len - 3))) - continue; - } + if ((abbr) && (len > 20)) { + if (i == 4) + printf(" ...\n"); + if ((i > 3) && (i < (len - 3))) + continue; + } - if (lcn < (LCN)0) { - int ind = -lcn - 1; + if (lcn < (LCN)0) { + int ind = -lcn - 1; - if (ind > -LCN_ENOENT - 1) - ind = 3; - printf("%8lld %8s %8lld\n", - rl->vcn, lcn_str[ind], rl->length); - } else - printf("%8lld %8lld %8lld\n", - rl->vcn, rl->lcn, rl->length); - if (!rl->length) - break; - } - if ((abbr) && (len > 20)) - printf(" (%d entries)\n", len+1); - printf("\n"); + if (ind > -LCN_ENOENT - 1) + ind = 3; + printf("%8lld %8s %8lld\n", + rl->vcn, lcn_str[ind], rl->length); + } else + printf("%8lld %8lld %8lld\n", + rl->vcn, rl->lcn, rl->length); + if (!rl->length) + break; + } + if ((abbr) && (len > 20)) + printf(" (%d entries)\n", len+1); + printf("\n"); } /** @@ -1786,20 +1811,21 @@ static void test_rl_dump_runlist(const runlist_element *rl) { * * Returns: */ -static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_element *srl) { - runlist_element *res = NULL; +static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_element *srl) +{ + runlist_element *res = NULL; - printf("dst:\n"); - test_rl_dump_runlist(drl); - printf("src:\n"); - test_rl_dump_runlist(srl); + printf("dst:\n"); + test_rl_dump_runlist(drl); + printf("src:\n"); + test_rl_dump_runlist(srl); - res = ntfs_runlists_merge(drl, srl); + res = ntfs_runlists_merge(drl, srl); - printf("res:\n"); - test_rl_dump_runlist(res); + printf("res:\n"); + test_rl_dump_runlist(res); - return res; + return res; } /** @@ -1812,22 +1838,23 @@ static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_el * * Returns: */ -static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize) { - FILE *fptr; +static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize) +{ + FILE *fptr; - fptr = fopen(file, "r"); - if (!fptr) { - printf("open %s\n", file); - return 0; - } + fptr = fopen(file, "r"); + if (!fptr) { + printf("open %s\n", file); + return 0; + } - if (fread(buf, bufsize, 1, fptr) == 99) { - printf("read %s\n", file); - return 0; - } + if (fread(buf, bufsize, 1, fptr) == 99) { + printf("read %s\n", file); + return 0; + } - fclose(fptr); - return 1; + fclose(fptr); + return 1; } /** @@ -1841,30 +1868,31 @@ static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize) { * * Returns: */ -static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int len) { - runlist_element *result; - int fudge; +static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int len) +{ + runlist_element *result; + int fudge; - if (contig) - fudge = 0; - else - fudge = 999; + if (contig) + fudge = 0; + else + fudge = 999; - result = ntfs_malloc(4096); - if (!result) - return NULL; - - if (multi) { - MKRL(result+0, vcn + (0*len/4), fudge + vcn + 1000 + (0*len/4), len / 4) - MKRL(result+1, vcn + (1*len/4), fudge + vcn + 1000 + (1*len/4), len / 4) - MKRL(result+2, vcn + (2*len/4), fudge + vcn + 1000 + (2*len/4), len / 4) - MKRL(result+3, vcn + (3*len/4), fudge + vcn + 1000 + (3*len/4), len / 4) - MKRL(result+4, vcn + (4*len/4), LCN_RL_NOT_MAPPED, 0) - } else { - MKRL(result+0, vcn, fudge + vcn + 1000, len) - MKRL(result+1, vcn + len, LCN_RL_NOT_MAPPED, 0) - } - return result; + result = ntfs_malloc(4096); + if (!result) + return NULL; + + if (multi) { + MKRL(result+0, vcn + (0*len/4), fudge + vcn + 1000 + (0*len/4), len / 4) + MKRL(result+1, vcn + (1*len/4), fudge + vcn + 1000 + (1*len/4), len / 4) + MKRL(result+2, vcn + (2*len/4), fudge + vcn + 1000 + (2*len/4), len / 4) + MKRL(result+3, vcn + (3*len/4), fudge + vcn + 1000 + (3*len/4), len / 4) + MKRL(result+4, vcn + (4*len/4), LCN_RL_NOT_MAPPED, 0) + } else { + MKRL(result+0, vcn, fudge + vcn + 1000, len) + MKRL(result+1, vcn + len, LCN_RL_NOT_MAPPED, 0) + } + return result; } /** @@ -1881,24 +1909,25 @@ static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int * * Returns: */ -static void test_rl_pure_test(int test, BOOL contig, BOOL multi, int vcn, int len, runlist_element *file, int size) { - runlist_element *src; - runlist_element *dst; - runlist_element *res; +static void test_rl_pure_test(int test, BOOL contig, BOOL multi, int vcn, int len, runlist_element *file, int size) +{ + runlist_element *src; + runlist_element *dst; + runlist_element *res; - src = test_rl_pure_src(contig, multi, vcn, len); - dst = ntfs_malloc(4096); - if (!src || !dst) { - printf("Test %2d ---------- FAILED! (no free memory?)\n", test); - return; - } + src = test_rl_pure_src(contig, multi, vcn, len); + dst = ntfs_malloc(4096); + if (!src || !dst) { + printf("Test %2d ---------- FAILED! (no free memory?)\n", test); + return; + } - memcpy(dst, file, size); + memcpy(dst, file, size); - printf("Test %2d ----------\n", test); - res = test_rl_runlists_merge(dst, src); + printf("Test %2d ----------\n", test); + res = test_rl_runlists_merge(dst, src); - free(res); + free(res); } /** @@ -1910,94 +1939,95 @@ static void test_rl_pure_test(int test, BOOL contig, BOOL multi, int vcn, int le * * Returns: */ -static void test_rl_pure(char *contig, char *multi) { - /* VCN, LCN, len */ - static runlist_element file1[] = { - { 0, -1, 100 }, /* HOLE */ - { 100, 1100, 100 }, /* DATA */ - { 200, -1, 100 }, /* HOLE */ - { 300, 1300, 100 }, /* DATA */ - { 400, -1, 100 }, /* HOLE */ - { 500, -3, 0 } /* NOENT */ - }; - static runlist_element file2[] = { - { 0, 1000, 100 }, /* DATA */ - { 100, -1, 100 }, /* HOLE */ - { 200, -3, 0 } /* NOENT */ - }; - static runlist_element file3[] = { - { 0, 1000, 100 }, /* DATA */ - { 100, -3, 0 } /* NOENT */ - }; - static runlist_element file4[] = { - { 0, -3, 0 } /* NOENT */ - }; - static runlist_element file5[] = { - { 0, -2, 100 }, /* NOTMAP */ - { 100, 1100, 100 }, /* DATA */ - { 200, -2, 100 }, /* NOTMAP */ - { 300, 1300, 100 }, /* DATA */ - { 400, -2, 100 }, /* NOTMAP */ - { 500, -3, 0 } /* NOENT */ - }; - static runlist_element file6[] = { - { 0, 1000, 100 }, /* DATA */ - { 100, -2, 100 }, /* NOTMAP */ - { 200, -3, 0 } /* NOENT */ - }; - BOOL c, m; +static void test_rl_pure(char *contig, char *multi) +{ + /* VCN, LCN, len */ + static runlist_element file1[] = { + { 0, -1, 100 }, /* HOLE */ + { 100, 1100, 100 }, /* DATA */ + { 200, -1, 100 }, /* HOLE */ + { 300, 1300, 100 }, /* DATA */ + { 400, -1, 100 }, /* HOLE */ + { 500, -3, 0 } /* NOENT */ + }; + static runlist_element file2[] = { + { 0, 1000, 100 }, /* DATA */ + { 100, -1, 100 }, /* HOLE */ + { 200, -3, 0 } /* NOENT */ + }; + static runlist_element file3[] = { + { 0, 1000, 100 }, /* DATA */ + { 100, -3, 0 } /* NOENT */ + }; + static runlist_element file4[] = { + { 0, -3, 0 } /* NOENT */ + }; + static runlist_element file5[] = { + { 0, -2, 100 }, /* NOTMAP */ + { 100, 1100, 100 }, /* DATA */ + { 200, -2, 100 }, /* NOTMAP */ + { 300, 1300, 100 }, /* DATA */ + { 400, -2, 100 }, /* NOTMAP */ + { 500, -3, 0 } /* NOENT */ + }; + static runlist_element file6[] = { + { 0, 1000, 100 }, /* DATA */ + { 100, -2, 100 }, /* NOTMAP */ + { 200, -3, 0 } /* NOENT */ + }; + BOOL c, m; - if (strcmp(contig, "contig") == 0) - c = TRUE; - else if (strcmp(contig, "noncontig") == 0) - c = FALSE; - else { - printf("rl pure [contig|noncontig] [single|multi]\n"); - return; - } - if (strcmp(multi, "multi") == 0) - m = TRUE; - else if (strcmp(multi, "single") == 0) - m = FALSE; - else { - printf("rl pure [contig|noncontig] [single|multi]\n"); - return; - } + if (strcmp(contig, "contig") == 0) + c = TRUE; + else if (strcmp(contig, "noncontig") == 0) + c = FALSE; + else { + printf("rl pure [contig|noncontig] [single|multi]\n"); + return; + } + if (strcmp(multi, "multi") == 0) + m = TRUE; + else if (strcmp(multi, "single") == 0) + m = FALSE; + else { + printf("rl pure [contig|noncontig] [single|multi]\n"); + return; + } - test_rl_pure_test(1, c, m, 0, 40, file1, sizeof(file1)); - test_rl_pure_test(2, c, m, 40, 40, file1, sizeof(file1)); - test_rl_pure_test(3, c, m, 60, 40, file1, sizeof(file1)); - test_rl_pure_test(4, c, m, 0, 100, file1, sizeof(file1)); - test_rl_pure_test(5, c, m, 200, 40, file1, sizeof(file1)); - test_rl_pure_test(6, c, m, 240, 40, file1, sizeof(file1)); - test_rl_pure_test(7, c, m, 260, 40, file1, sizeof(file1)); - test_rl_pure_test(8, c, m, 200, 100, file1, sizeof(file1)); - test_rl_pure_test(9, c, m, 400, 40, file1, sizeof(file1)); - test_rl_pure_test(10, c, m, 440, 40, file1, sizeof(file1)); - test_rl_pure_test(11, c, m, 460, 40, file1, sizeof(file1)); - test_rl_pure_test(12, c, m, 400, 100, file1, sizeof(file1)); - test_rl_pure_test(13, c, m, 160, 100, file2, sizeof(file2)); - test_rl_pure_test(14, c, m, 100, 140, file2, sizeof(file2)); - test_rl_pure_test(15, c, m, 200, 40, file2, sizeof(file2)); - test_rl_pure_test(16, c, m, 240, 40, file2, sizeof(file2)); - test_rl_pure_test(17, c, m, 100, 40, file3, sizeof(file3)); - test_rl_pure_test(18, c, m, 140, 40, file3, sizeof(file3)); - test_rl_pure_test(19, c, m, 0, 40, file4, sizeof(file4)); - test_rl_pure_test(20, c, m, 40, 40, file4, sizeof(file4)); - test_rl_pure_test(21, c, m, 0, 40, file5, sizeof(file5)); - test_rl_pure_test(22, c, m, 40, 40, file5, sizeof(file5)); - test_rl_pure_test(23, c, m, 60, 40, file5, sizeof(file5)); - test_rl_pure_test(24, c, m, 0, 100, file5, sizeof(file5)); - test_rl_pure_test(25, c, m, 200, 40, file5, sizeof(file5)); - test_rl_pure_test(26, c, m, 240, 40, file5, sizeof(file5)); - test_rl_pure_test(27, c, m, 260, 40, file5, sizeof(file5)); - test_rl_pure_test(28, c, m, 200, 100, file5, sizeof(file5)); - test_rl_pure_test(29, c, m, 400, 40, file5, sizeof(file5)); - test_rl_pure_test(30, c, m, 440, 40, file5, sizeof(file5)); - test_rl_pure_test(31, c, m, 460, 40, file5, sizeof(file5)); - test_rl_pure_test(32, c, m, 400, 100, file5, sizeof(file5)); - test_rl_pure_test(33, c, m, 160, 100, file6, sizeof(file6)); - test_rl_pure_test(34, c, m, 100, 140, file6, sizeof(file6)); + test_rl_pure_test(1, c, m, 0, 40, file1, sizeof(file1)); + test_rl_pure_test(2, c, m, 40, 40, file1, sizeof(file1)); + test_rl_pure_test(3, c, m, 60, 40, file1, sizeof(file1)); + test_rl_pure_test(4, c, m, 0, 100, file1, sizeof(file1)); + test_rl_pure_test(5, c, m, 200, 40, file1, sizeof(file1)); + test_rl_pure_test(6, c, m, 240, 40, file1, sizeof(file1)); + test_rl_pure_test(7, c, m, 260, 40, file1, sizeof(file1)); + test_rl_pure_test(8, c, m, 200, 100, file1, sizeof(file1)); + test_rl_pure_test(9, c, m, 400, 40, file1, sizeof(file1)); + test_rl_pure_test(10, c, m, 440, 40, file1, sizeof(file1)); + test_rl_pure_test(11, c, m, 460, 40, file1, sizeof(file1)); + test_rl_pure_test(12, c, m, 400, 100, file1, sizeof(file1)); + test_rl_pure_test(13, c, m, 160, 100, file2, sizeof(file2)); + test_rl_pure_test(14, c, m, 100, 140, file2, sizeof(file2)); + test_rl_pure_test(15, c, m, 200, 40, file2, sizeof(file2)); + test_rl_pure_test(16, c, m, 240, 40, file2, sizeof(file2)); + test_rl_pure_test(17, c, m, 100, 40, file3, sizeof(file3)); + test_rl_pure_test(18, c, m, 140, 40, file3, sizeof(file3)); + test_rl_pure_test(19, c, m, 0, 40, file4, sizeof(file4)); + test_rl_pure_test(20, c, m, 40, 40, file4, sizeof(file4)); + test_rl_pure_test(21, c, m, 0, 40, file5, sizeof(file5)); + test_rl_pure_test(22, c, m, 40, 40, file5, sizeof(file5)); + test_rl_pure_test(23, c, m, 60, 40, file5, sizeof(file5)); + test_rl_pure_test(24, c, m, 0, 100, file5, sizeof(file5)); + test_rl_pure_test(25, c, m, 200, 40, file5, sizeof(file5)); + test_rl_pure_test(26, c, m, 240, 40, file5, sizeof(file5)); + test_rl_pure_test(27, c, m, 260, 40, file5, sizeof(file5)); + test_rl_pure_test(28, c, m, 200, 100, file5, sizeof(file5)); + test_rl_pure_test(29, c, m, 400, 40, file5, sizeof(file5)); + test_rl_pure_test(30, c, m, 440, 40, file5, sizeof(file5)); + test_rl_pure_test(31, c, m, 460, 40, file5, sizeof(file5)); + test_rl_pure_test(32, c, m, 400, 100, file5, sizeof(file5)); + test_rl_pure_test(33, c, m, 160, 100, file6, sizeof(file6)); + test_rl_pure_test(34, c, m, 100, 140, file6, sizeof(file6)); } /** @@ -2007,22 +2037,23 @@ static void test_rl_pure(char *contig, char *multi) { * * Returns: */ -static void test_rl_zero(void) { - runlist_element *jim = NULL; - runlist_element *bob = NULL; +static void test_rl_zero(void) +{ + runlist_element *jim = NULL; + runlist_element *bob = NULL; - bob = calloc(3, sizeof(runlist_element)); - if (!bob) - return; + bob = calloc(3, sizeof(runlist_element)); + if (!bob) + return; - MKRL(bob+0, 10, 99, 5) - MKRL(bob+1, 15, LCN_RL_NOT_MAPPED, 0) + MKRL(bob+0, 10, 99, 5) + MKRL(bob+1, 15, LCN_RL_NOT_MAPPED, 0) - jim = test_rl_runlists_merge(jim, bob); - if (!jim) - return; + jim = test_rl_runlists_merge(jim, bob); + if (!jim) + return; - free(jim); + free(jim); } /** @@ -2036,28 +2067,29 @@ static void test_rl_zero(void) { * * Returns: */ -static void test_rl_frag_combine(ntfs_volume *vol, ATTR_RECORD *attr1, ATTR_RECORD *attr2, ATTR_RECORD *attr3) { - runlist_element *run1; - runlist_element *run2; - runlist_element *run3; +static void test_rl_frag_combine(ntfs_volume *vol, ATTR_RECORD *attr1, ATTR_RECORD *attr2, ATTR_RECORD *attr3) +{ + runlist_element *run1; + runlist_element *run2; + runlist_element *run3; - run1 = ntfs_mapping_pairs_decompress(vol, attr1, NULL); - if (!run1) - return; + run1 = ntfs_mapping_pairs_decompress(vol, attr1, NULL); + if (!run1) + return; - run2 = ntfs_mapping_pairs_decompress(vol, attr2, NULL); - if (!run2) - return; + run2 = ntfs_mapping_pairs_decompress(vol, attr2, NULL); + if (!run2) + return; - run1 = test_rl_runlists_merge(run1, run2); + run1 = test_rl_runlists_merge(run1, run2); - run3 = ntfs_mapping_pairs_decompress(vol, attr3, NULL); - if (!run3) - return; + run3 = ntfs_mapping_pairs_decompress(vol, attr3, NULL); + if (!run3) + return; - run1 = test_rl_runlists_merge(run1, run3); + run1 = test_rl_runlists_merge(run1, run3); - free(run1); + free(run1); } /** @@ -2068,41 +2100,42 @@ static void test_rl_frag_combine(ntfs_volume *vol, ATTR_RECORD *attr1, ATTR_RECO * * Returns: */ -static void test_rl_frag(char *test) { - ntfs_volume vol; - ATTR_RECORD *attr1 = ntfs_malloc(1024); - ATTR_RECORD *attr2 = ntfs_malloc(1024); - ATTR_RECORD *attr3 = ntfs_malloc(1024); +static void test_rl_frag(char *test) +{ + ntfs_volume vol; + ATTR_RECORD *attr1 = ntfs_malloc(1024); + ATTR_RECORD *attr2 = ntfs_malloc(1024); + ATTR_RECORD *attr3 = ntfs_malloc(1024); - if (!attr1 || !attr2 || !attr3) - goto out; + if (!attr1 || !attr2 || !attr3) + goto out; - vol.sb = NULL; - vol.sector_size_bits = 9; - vol.cluster_size = 2048; - vol.cluster_size_bits = 11; - vol.major_ver = 3; + vol.sb = NULL; + vol.sector_size_bits = 9; + vol.cluster_size = 2048; + vol.cluster_size_bits = 11; + vol.major_ver = 3; - if (!test_rl_read_buffer("runlist-data/attr1.bin", (u8*) attr1, 1024)) - goto out; - if (!test_rl_read_buffer("runlist-data/attr2.bin", (u8*) attr2, 1024)) - goto out; - if (!test_rl_read_buffer("runlist-data/attr3.bin", (u8*) attr3, 1024)) - goto out; + if (!test_rl_read_buffer("runlist-data/attr1.bin", (u8*) attr1, 1024)) + goto out; + if (!test_rl_read_buffer("runlist-data/attr2.bin", (u8*) attr2, 1024)) + goto out; + if (!test_rl_read_buffer("runlist-data/attr3.bin", (u8*) attr3, 1024)) + goto out; - if (strcmp(test, "123") == 0) test_rl_frag_combine(&vol, attr1, attr2, attr3); - else if (strcmp(test, "132") == 0) test_rl_frag_combine(&vol, attr1, attr3, attr2); - else if (strcmp(test, "213") == 0) test_rl_frag_combine(&vol, attr2, attr1, attr3); - else if (strcmp(test, "231") == 0) test_rl_frag_combine(&vol, attr2, attr3, attr1); - else if (strcmp(test, "312") == 0) test_rl_frag_combine(&vol, attr3, attr1, attr2); - else if (strcmp(test, "321") == 0) test_rl_frag_combine(&vol, attr3, attr2, attr1); - else - printf("Frag: No such test '%s'\n", test); + if (strcmp(test, "123") == 0) test_rl_frag_combine(&vol, attr1, attr2, attr3); + else if (strcmp(test, "132") == 0) test_rl_frag_combine(&vol, attr1, attr3, attr2); + else if (strcmp(test, "213") == 0) test_rl_frag_combine(&vol, attr2, attr1, attr3); + else if (strcmp(test, "231") == 0) test_rl_frag_combine(&vol, attr2, attr3, attr1); + else if (strcmp(test, "312") == 0) test_rl_frag_combine(&vol, attr3, attr1, attr2); + else if (strcmp(test, "321") == 0) test_rl_frag_combine(&vol, attr3, attr2, attr1); + else + printf("Frag: No such test '%s'\n", test); out: - free(attr1); - free(attr2); - free(attr3); + free(attr1); + free(attr2); + free(attr3); } /** @@ -2114,14 +2147,15 @@ out: * * Returns: */ -int test_rl_main(int argc, char *argv[]) { - if ((argc == 2) && (strcmp(argv[1], "zero") == 0)) test_rl_zero(); - else if ((argc == 3) && (strcmp(argv[1], "frag") == 0)) test_rl_frag(argv[2]); - else if ((argc == 4) && (strcmp(argv[1], "pure") == 0)) test_rl_pure(argv[2], argv[3]); - else - printf("rl [zero|frag|pure] {args}\n"); +int test_rl_main(int argc, char *argv[]) +{ + if ((argc == 2) && (strcmp(argv[1], "zero") == 0)) test_rl_zero(); + else if ((argc == 3) && (strcmp(argv[1], "frag") == 0)) test_rl_frag(argv[2]); + else if ((argc == 4) && (strcmp(argv[1], "pure") == 0)) test_rl_pure(argv[2], argv[3]); + else + printf("rl [zero|frag|pure] {args}\n"); - return 0; + return 0; } #endif diff --git a/source/libntfs/runlist.h b/source/libntfs/runlist.h index ad709732..43de53cc 100644 --- a/source/libntfs/runlist.h +++ b/source/libntfs/runlist.h @@ -44,9 +44,9 @@ typedef runlist_element runlist; * physically allocated (i.e. this is a hole / data is sparse). */ struct _runlist_element {/* In memory vcn to lcn mapping structure element. */ - VCN vcn; /* vcn = Starting virtual cluster number. */ - LCN lcn; /* lcn = Starting logical cluster number. */ - s64 length; /* Run length in clusters. */ + VCN vcn; /* vcn = Starting virtual cluster number. */ + LCN lcn; /* lcn = Starting logical cluster number. */ + s64 length; /* Run length in clusters. */ }; extern runlist_element *ntfs_rl_extend(runlist_element *rl, int more_entries); @@ -54,27 +54,27 @@ extern runlist_element *ntfs_rl_extend(runlist_element *rl, int more_entries); extern LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn); extern s64 ntfs_rl_pread(const ntfs_volume *vol, const runlist_element *rl, - const s64 pos, s64 count, void *b); + const s64 pos, s64 count, void *b); extern s64 ntfs_rl_pwrite(const ntfs_volume *vol, const runlist_element *rl, - s64 ofs, const s64 pos, s64 count, void *b); + s64 ofs, const s64 pos, s64 count, void *b); extern runlist_element *ntfs_runlists_merge(runlist_element *drl, - runlist_element *srl); + runlist_element *srl); extern runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, - const ATTR_RECORD *attr, runlist_element *old_rl); + const ATTR_RECORD *attr, runlist_element *old_rl); extern int ntfs_get_nr_significant_bytes(const s64 n); extern int ntfs_get_size_for_mapping_pairs(const ntfs_volume *vol, - const runlist_element *rl, const VCN start_vcn, int max_size); + const runlist_element *rl, const VCN start_vcn, int max_size); extern int ntfs_write_significant_bytes(u8 *dst, const u8 *dst_max, - const s64 n); + const s64 n); extern int ntfs_mapping_pairs_build(const ntfs_volume *vol, u8 *dst, - const int dst_len, const runlist_element *rl, - const VCN start_vcn, runlist_element const **stop_rl); + const int dst_len, const runlist_element *rl, + const VCN start_vcn, runlist_element const **stop_rl); extern int ntfs_rl_truncate(runlist **arl, const VCN start_vcn); diff --git a/source/libntfs/security.c b/source/libntfs/security.c index 32e66262..38acce40 100644 --- a/source/libntfs/security.c +++ b/source/libntfs/security.c @@ -72,7 +72,7 @@ #define STUFFSZ 0x4000 /* unitary stuffing size for $SDS */ #define FIRST_SECURITY_ID 0x100 /* Lowest security id */ -/* Mask for attributes which can be forced */ + /* Mask for attributes which can be forced */ #define FILE_ATTR_SETTABLE ( FILE_ATTR_READONLY \ | FILE_ATTR_HIDDEN \ | FILE_ATTR_SYSTEM \ @@ -82,59 +82,57 @@ | FILE_ATTR_NOT_CONTENT_INDEXED ) struct SII { /* this is an image of an $SII index entry */ - le16 offs; - le16 size; - le32 fill1; - le16 indexsz; - le16 indexksz; - le16 flags; - le16 fill2; - le32 keysecurid; + le16 offs; + le16 size; + le32 fill1; + le16 indexsz; + le16 indexksz; + le16 flags; + le16 fill2; + le32 keysecurid; - /* did not find official description for the following */ - le32 hash; - le32 securid; - le32 dataoffsl; /* documented as badly aligned */ - le32 dataoffsh; - le32 datasize; + /* did not find official description for the following */ + le32 hash; + le32 securid; + le32 dataoffsl; /* documented as badly aligned */ + le32 dataoffsh; + le32 datasize; } ; struct SDH { /* this is an image of an $SDH index entry */ - le16 offs; - le16 size; - le32 fill1; - le16 indexsz; - le16 indexksz; - le16 flags; - le16 fill2; - le32 keyhash; - le32 keysecurid; + le16 offs; + le16 size; + le32 fill1; + le16 indexsz; + le16 indexksz; + le16 flags; + le16 fill2; + le32 keyhash; + le32 keysecurid; - /* did not find official description for the following */ - le32 hash; - le32 securid; - le32 dataoffsl; - le32 dataoffsh; - le32 datasize; - le32 fill3; -} ; + /* did not find official description for the following */ + le32 hash; + le32 securid; + le32 dataoffsl; + le32 dataoffsh; + le32 datasize; + le32 fill3; + } ; /* * A few useful constants */ static ntfschar sii_stream[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('S'), - const_cpu_to_le16('I'), - const_cpu_to_le16('I'), - const_cpu_to_le16(0) - }; + const_cpu_to_le16('S'), + const_cpu_to_le16('I'), + const_cpu_to_le16('I'), + const_cpu_to_le16(0) }; static ntfschar sdh_stream[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('S'), - const_cpu_to_le16('D'), - const_cpu_to_le16('H'), - const_cpu_to_le16(0) - }; + const_cpu_to_le16('S'), + const_cpu_to_le16('D'), + const_cpu_to_le16('H'), + const_cpu_to_le16(0) }; /* * null SID (S-1-0-0) @@ -147,8 +145,7 @@ extern const SID *nullsid; */ static const GUID __zero_guid = { const_cpu_to_le32(0), const_cpu_to_le16(0), - const_cpu_to_le16(0), { 0, 0, 0, 0, 0, 0, 0, 0 } - }; + const_cpu_to_le16(0), { 0, 0, 0, 0, 0, 0, 0, 0 } }; static const GUID *const zero_guid = &__zero_guid; /** @@ -158,8 +155,9 @@ static const GUID *const zero_guid = &__zero_guid; * Return TRUE if @guid is a valid pointer to a GUID and it is the zero GUID * and FALSE otherwise. */ -BOOL ntfs_guid_is_zero(const GUID *guid) { - return (memcmp(guid, zero_guid, sizeof(*zero_guid))); +BOOL ntfs_guid_is_zero(const GUID *guid) +{ + return (memcmp(guid, zero_guid, sizeof(*zero_guid))); } /** @@ -178,33 +176,34 @@ BOOL ntfs_guid_is_zero(const GUID *guid) { * On success return the converted string and on failure return NULL with errno * set to the error code. */ -char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) { - char *_guid_str; - int res; +char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) +{ + char *_guid_str; + int res; - if (!guid) { - errno = EINVAL; - return NULL; - } - _guid_str = guid_str; - if (!_guid_str) { - _guid_str = (char*)ntfs_malloc(37); - if (!_guid_str) - return _guid_str; - } - res = snprintf(_guid_str, 37, - "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", - (unsigned int)le32_to_cpu(guid->data1), - le16_to_cpu(guid->data2), le16_to_cpu(guid->data3), - guid->data4[0], guid->data4[1], - guid->data4[2], guid->data4[3], guid->data4[4], - guid->data4[5], guid->data4[6], guid->data4[7]); - if (res == 36) - return _guid_str; - if (!guid_str) - free(_guid_str); - errno = EINVAL; - return NULL; + if (!guid) { + errno = EINVAL; + return NULL; + } + _guid_str = guid_str; + if (!_guid_str) { + _guid_str = (char*)ntfs_malloc(37); + if (!_guid_str) + return _guid_str; + } + res = snprintf(_guid_str, 37, + "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", + (unsigned int)le32_to_cpu(guid->data1), + le16_to_cpu(guid->data2), le16_to_cpu(guid->data3), + guid->data4[0], guid->data4[1], + guid->data4[2], guid->data4[3], guid->data4[4], + guid->data4[5], guid->data4[6], guid->data4[7]); + if (res == 36) + return _guid_str; + if (!guid_str) + free(_guid_str); + errno = EINVAL; + return NULL; } /** @@ -218,40 +217,41 @@ char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) { * On success return the maximum number of bytes needed to store the multi byte * string and on failure return -1 with errno set to the error code. */ -int ntfs_sid_to_mbs_size(const SID *sid) { - int size, i; +int ntfs_sid_to_mbs_size(const SID *sid) +{ + int size, i; - if (!ntfs_sid_is_valid(sid)) { - errno = EINVAL; - return -1; - } - /* Start with "S-". */ - size = 2; - /* - * Add the SID_REVISION. Hopefully the compiler will optimize this - * away as SID_REVISION is a constant. - */ - for (i = SID_REVISION; i > 0; i /= 10) - size++; - /* Add the "-". */ - size++; - /* - * Add the identifier authority. If it needs to be in decimal, the - * maximum is 2^32-1 = 4294967295 = 10 characters. If it needs to be - * in hexadecimal, then maximum is 0x665544332211 = 14 characters. - */ - if (!sid->identifier_authority.high_part) - size += 10; - else - size += 14; - /* - * Finally, add the sub authorities. For each we have a "-" followed - * by a decimal which can be up to 2^32-1 = 4294967295 = 10 characters. - */ - size += (1 + 10) * sid->sub_authority_count; - /* We need the zero byte at the end, too. */ - size++; - return size * sizeof(char); + if (!ntfs_sid_is_valid(sid)) { + errno = EINVAL; + return -1; + } + /* Start with "S-". */ + size = 2; + /* + * Add the SID_REVISION. Hopefully the compiler will optimize this + * away as SID_REVISION is a constant. + */ + for (i = SID_REVISION; i > 0; i /= 10) + size++; + /* Add the "-". */ + size++; + /* + * Add the identifier authority. If it needs to be in decimal, the + * maximum is 2^32-1 = 4294967295 = 10 characters. If it needs to be + * in hexadecimal, then maximum is 0x665544332211 = 14 characters. + */ + if (!sid->identifier_authority.high_part) + size += 10; + else + size += 14; + /* + * Finally, add the sub authorities. For each we have a "-" followed + * by a decimal which can be up to 2^32-1 = 4294967295 = 10 characters. + */ + size += (1 + 10) * sid->sub_authority_count; + /* We need the zero byte at the end, too. */ + size++; + return size * sizeof(char); } /** @@ -284,72 +284,73 @@ int ntfs_sid_to_mbs_size(const SID *sid) { * On success return the converted string and on failure return NULL with errno * set to the error code. */ -char *ntfs_sid_to_mbs(const SID *sid, char *sid_str, size_t sid_str_size) { - u64 u; - le32 leauth; - char *s; - int i, j, cnt; +char *ntfs_sid_to_mbs(const SID *sid, char *sid_str, size_t sid_str_size) +{ + u64 u; + le32 leauth; + char *s; + int i, j, cnt; - /* - * No need to check @sid if !@sid_str since ntfs_sid_to_mbs_size() will - * check @sid, too. 8 is the minimum SID string size. - */ - if (sid_str && (sid_str_size < 8 || !ntfs_sid_is_valid(sid))) { - errno = EINVAL; - return NULL; - } - /* Allocate string if not provided. */ - if (!sid_str) { - cnt = ntfs_sid_to_mbs_size(sid); - if (cnt < 0) - return NULL; - s = (char*)ntfs_malloc(cnt); - if (!s) - return s; - sid_str = s; - /* So we know we allocated it. */ - sid_str_size = 0; - } else { - s = sid_str; - cnt = sid_str_size; - } - /* Start with "S-R-". */ - i = snprintf(s, cnt, "S-%hhu-", (unsigned char)sid->revision); - if (i < 0 || i >= cnt) - goto err_out; - s += i; - cnt -= i; - /* Add the identifier authority. */ - for (u = i = 0, j = 40; i < 6; i++, j -= 8) - u += (u64)sid->identifier_authority.value[i] << j; - if (!sid->identifier_authority.high_part) - i = snprintf(s, cnt, "%lu", (unsigned long)u); - else - i = snprintf(s, cnt, "0x%llx", (unsigned long long)u); - if (i < 0 || i >= cnt) - goto err_out; - s += i; - cnt -= i; - /* Finally, add the sub authorities. */ - for (j = 0; j < sid->sub_authority_count; j++) { - leauth = sid->sub_authority[j]; - i = snprintf(s, cnt, "-%u", (unsigned int) - le32_to_cpu(leauth)); - if (i < 0 || i >= cnt) - goto err_out; - s += i; - cnt -= i; - } - return sid_str; + /* + * No need to check @sid if !@sid_str since ntfs_sid_to_mbs_size() will + * check @sid, too. 8 is the minimum SID string size. + */ + if (sid_str && (sid_str_size < 8 || !ntfs_sid_is_valid(sid))) { + errno = EINVAL; + return NULL; + } + /* Allocate string if not provided. */ + if (!sid_str) { + cnt = ntfs_sid_to_mbs_size(sid); + if (cnt < 0) + return NULL; + s = (char*)ntfs_malloc(cnt); + if (!s) + return s; + sid_str = s; + /* So we know we allocated it. */ + sid_str_size = 0; + } else { + s = sid_str; + cnt = sid_str_size; + } + /* Start with "S-R-". */ + i = snprintf(s, cnt, "S-%hhu-", (unsigned char)sid->revision); + if (i < 0 || i >= cnt) + goto err_out; + s += i; + cnt -= i; + /* Add the identifier authority. */ + for (u = i = 0, j = 40; i < 6; i++, j -= 8) + u += (u64)sid->identifier_authority.value[i] << j; + if (!sid->identifier_authority.high_part) + i = snprintf(s, cnt, "%lu", (unsigned long)u); + else + i = snprintf(s, cnt, "0x%llx", (unsigned long long)u); + if (i < 0 || i >= cnt) + goto err_out; + s += i; + cnt -= i; + /* Finally, add the sub authorities. */ + for (j = 0; j < sid->sub_authority_count; j++) { + leauth = sid->sub_authority[j]; + i = snprintf(s, cnt, "-%u", (unsigned int) + le32_to_cpu(leauth)); + if (i < 0 || i >= cnt) + goto err_out; + s += i; + cnt -= i; + } + return sid_str; err_out: - if (i >= cnt) - i = EMSGSIZE; - else - i = errno; - if (!sid_str_size) - free(sid_str); - errno = i; - return NULL; + if (i >= cnt) + i = EMSGSIZE; + else + i = errno; + if (!sid_str_size) + free(sid_str); + errno = i; + return NULL; } /** @@ -358,17 +359,18 @@ err_out: * * perhaps not a very good random number generator though... */ -void ntfs_generate_guid(GUID *guid) { - unsigned int i; - u8 *p = (u8 *)guid; +void ntfs_generate_guid(GUID *guid) +{ + unsigned int i; + u8 *p = (u8 *)guid; - for (i = 0; i < sizeof(GUID); i++) { - p[i] = (u8)(random() & 0xFF); - if (i == 7) - p[7] = (p[7] & 0x0F) | 0x40; - if (i == 8) - p[8] = (p[8] & 0x3F) | 0x80; - } + for (i = 0; i < sizeof(GUID); i++) { + p[i] = (u8)(random() & 0xFF); + if (i == 7) + p[7] = (p[7] & 0x0F) | 0x40; + if (i == 8) + p[8] = (p[8] & 0x3F) | 0x80; + } } /** @@ -387,16 +389,17 @@ void ntfs_generate_guid(GUID *guid) { * * Return the calculated security hash in little endian. */ -le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, const u32 len) { - const le32 *pos = (const le32*)sd; - const le32 *end = pos + (len >> 2); - u32 hash = 0; +le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, const u32 len) +{ + const le32 *pos = (const le32*)sd; + const le32 *end = pos + (len >> 2); + u32 hash = 0; - while (pos < end) { - hash = le32_to_cpup(pos) + ntfs_rol32(hash, 3); - pos++; - } - return cpu_to_le32(hash); + while (pos < end) { + hash = le32_to_cpup(pos) + ntfs_rol32(hash, 3); + pos++; + } + return cpu_to_le32(hash); } /* @@ -406,40 +409,41 @@ le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, const u32 len) { */ static int ntfs_local_read(ntfs_inode *ni, - ntfschar *stream_name, int stream_name_len, - char *buf, size_t size, off_t offset) { - ntfs_attr *na = NULL; - int res, total = 0; + ntfschar *stream_name, int stream_name_len, + char *buf, size_t size, off_t offset) +{ + ntfs_attr *na = NULL; + int res, total = 0; - na = ntfs_attr_open(ni, AT_DATA, stream_name, stream_name_len); - if (!na) { - res = -errno; - goto exit; - } - if ((size_t)offset < (size_t)na->data_size) { - if (offset + size > (size_t)na->data_size) - size = na->data_size - offset; - while (size) { - res = ntfs_attr_pread(na, offset, size, buf); - if ((off_t)res < (off_t)size) - ntfs_log_perror("ntfs_attr_pread partial read " - "(%lld : %lld <> %d)", - (long long)offset, - (long long)size, res); - if (res <= 0) { - res = -errno; - goto exit; - } - size -= res; - offset += res; - total += res; - } - } - res = total; + na = ntfs_attr_open(ni, AT_DATA, stream_name, stream_name_len); + if (!na) { + res = -errno; + goto exit; + } + if ((size_t)offset < (size_t)na->data_size) { + if (offset + size > (size_t)na->data_size) + size = na->data_size - offset; + while (size) { + res = ntfs_attr_pread(na, offset, size, buf); + if ((off_t)res < (off_t)size) + ntfs_log_perror("ntfs_attr_pread partial read " + "(%lld : %lld <> %d)", + (long long)offset, + (long long)size, res); + if (res <= 0) { + res = -errno; + goto exit; + } + size -= res; + offset += res; + total += res; + } + } + res = total; exit: - if (na) - ntfs_attr_close(na); - return res; + if (na) + ntfs_attr_close(na); + return res; } @@ -450,35 +454,36 @@ exit: */ static int ntfs_local_write(ntfs_inode *ni, - ntfschar *stream_name, int stream_name_len, - char *buf, size_t size, off_t offset) { - ntfs_attr *na = NULL; - int res, total = 0; + ntfschar *stream_name, int stream_name_len, + char *buf, size_t size, off_t offset) +{ + ntfs_attr *na = NULL; + int res, total = 0; - na = ntfs_attr_open(ni, AT_DATA, stream_name, stream_name_len); - if (!na) { - res = -errno; - goto exit; - } - while (size) { - res = ntfs_attr_pwrite(na, offset, size, buf); - if (res < (s64)size) - ntfs_log_perror("ntfs_attr_pwrite partial write (%lld: " - "%lld <> %d)", (long long)offset, - (long long)size, res); - if (res <= 0) { - res = -errno; - goto exit; - } - size -= res; - offset += res; - total += res; - } - res = total; + na = ntfs_attr_open(ni, AT_DATA, stream_name, stream_name_len); + if (!na) { + res = -errno; + goto exit; + } + while (size) { + res = ntfs_attr_pwrite(na, offset, size, buf); + if (res < (s64)size) + ntfs_log_perror("ntfs_attr_pwrite partial write (%lld: " + "%lld <> %d)", (long long)offset, + (long long)size, res); + if (res <= 0) { + res = -errno; + goto exit; + } + size -= res; + offset += res; + total += res; + } + res = total; exit: - if (na) - ntfs_attr_close(na); - return res; + if (na) + ntfs_attr_close(na); + return res; } @@ -487,8 +492,9 @@ exit: * cut and pasted form ntfs_ie_get_first() in index.c */ -static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) { - return (INDEX_ENTRY*)((u8*)ih + le32_to_cpu(ih->entries_offset)); +static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) +{ + return (INDEX_ENTRY*)((u8*)ih + le32_to_cpu(ih->entries_offset)); } /* @@ -510,34 +516,35 @@ static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) { * file. Stuffing is just a way to get to the same result. */ -static int entersecurity_stuff(ntfs_volume *vol, off_t offs) { - int res; - int written; - unsigned long total; - char *stuff; +static int entersecurity_stuff(ntfs_volume *vol, off_t offs) +{ + int res; + int written; + unsigned long total; + char *stuff; - res = 0; - total = 0; - stuff = (char*)ntfs_malloc(STUFFSZ); - if (stuff) { - memset(stuff, 0, STUFFSZ); - do { - written = ntfs_local_write(vol->secure_ni, - STREAM_SDS, 4, stuff, STUFFSZ, offs); - if (written == STUFFSZ) { - total += STUFFSZ; - offs += STUFFSZ; - } else { - errno = ENOSPC; - res = -1; - } - } while (!res && (total < ALIGN_SDS_BLOCK)); - free(stuff); - } else { - errno = ENOMEM; - res = -1; - } - return (res); + res = 0; + total = 0; + stuff = (char*)ntfs_malloc(STUFFSZ); + if (stuff) { + memset(stuff, 0, STUFFSZ); + do { + written = ntfs_local_write(vol->secure_ni, + STREAM_SDS, 4, stuff, STUFFSZ, offs); + if (written == STUFFSZ) { + total += STUFFSZ; + offs += STUFFSZ; + } else { + errno = ENOSPC; + res = -1; + } + } while (!res && (total < ALIGN_SDS_BLOCK)); + free(stuff); + } else { + errno = ENOMEM; + res = -1; + } + return (res); } /* @@ -550,50 +557,51 @@ static int entersecurity_stuff(ntfs_volume *vol, off_t offs) { */ static int entersecurity_data(ntfs_volume *vol, - const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, - le32 hash, le32 keyid, off_t offs, int gap) { - int res; - int written1; - int written2; - char *fullattr; - int fullsz; - SECURITY_DESCRIPTOR_HEADER *phsds; + const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, + le32 hash, le32 keyid, off_t offs, int gap) +{ + int res; + int written1; + int written2; + char *fullattr; + int fullsz; + SECURITY_DESCRIPTOR_HEADER *phsds; - res = -1; - fullsz = attrsz + gap + sizeof(SECURITY_DESCRIPTOR_HEADER); - fullattr = (char*)ntfs_malloc(fullsz); - if (fullattr) { - /* - * Clear the gap from previous descriptor - * this could be useful for appending the second - * copy to the end of file. When creating a new - * 256K block, the gap is cleared while writing - * the first copy - */ - if (gap) - memset(fullattr,0,gap); - memcpy(&fullattr[gap + sizeof(SECURITY_DESCRIPTOR_HEADER)], - attr,attrsz); - phsds = (SECURITY_DESCRIPTOR_HEADER*)&fullattr[gap]; - phsds->hash = hash; - phsds->security_id = keyid; - phsds->offset = cpu_to_le64(offs); - phsds->length = cpu_to_le32(fullsz - gap); - written1 = ntfs_local_write(vol->secure_ni, - STREAM_SDS, 4, fullattr, fullsz, - offs - gap); - written2 = ntfs_local_write(vol->secure_ni, - STREAM_SDS, 4, fullattr, fullsz, - offs - gap + ALIGN_SDS_BLOCK); - if ((written1 == fullsz) - && (written2 == written1)) - res = 0; - else - errno = ENOSPC; - free(fullattr); - } else - errno = ENOMEM; - return (res); + res = -1; + fullsz = attrsz + gap + sizeof(SECURITY_DESCRIPTOR_HEADER); + fullattr = (char*)ntfs_malloc(fullsz); + if (fullattr) { + /* + * Clear the gap from previous descriptor + * this could be useful for appending the second + * copy to the end of file. When creating a new + * 256K block, the gap is cleared while writing + * the first copy + */ + if (gap) + memset(fullattr,0,gap); + memcpy(&fullattr[gap + sizeof(SECURITY_DESCRIPTOR_HEADER)], + attr,attrsz); + phsds = (SECURITY_DESCRIPTOR_HEADER*)&fullattr[gap]; + phsds->hash = hash; + phsds->security_id = keyid; + phsds->offset = cpu_to_le64(offs); + phsds->length = cpu_to_le32(fullsz - gap); + written1 = ntfs_local_write(vol->secure_ni, + STREAM_SDS, 4, fullattr, fullsz, + offs - gap); + written2 = ntfs_local_write(vol->secure_ni, + STREAM_SDS, 4, fullattr, fullsz, + offs - gap + ALIGN_SDS_BLOCK); + if ((written1 == fullsz) + && (written2 == written1)) + res = 0; + else + errno = ENOSPC; + free(fullattr); + } else + errno = ENOMEM; + return (res); } /* @@ -605,71 +613,72 @@ static int entersecurity_data(ntfs_volume *vol, */ static int entersecurity_indexes(ntfs_volume *vol, s64 attrsz, - le32 hash, le32 keyid, off_t offs) { - union { - struct { - le32 dataoffsl; - le32 dataoffsh; - } parts; - le64 all; - } realign; - int res; - ntfs_index_context *xsii; - ntfs_index_context *xsdh; - struct SII newsii; - struct SDH newsdh; + le32 hash, le32 keyid, off_t offs) +{ + union { + struct { + le32 dataoffsl; + le32 dataoffsh; + } parts; + le64 all; + } realign; + int res; + ntfs_index_context *xsii; + ntfs_index_context *xsdh; + struct SII newsii; + struct SDH newsdh; - res = -1; - /* enter a new $SII record */ + res = -1; + /* enter a new $SII record */ - xsii = vol->secure_xsii; - ntfs_index_ctx_reinit(xsii); - newsii.offs = const_cpu_to_le16(20); - newsii.size = const_cpu_to_le16(sizeof(struct SII) - 20); - newsii.fill1 = const_cpu_to_le32(0); - newsii.indexsz = const_cpu_to_le16(sizeof(struct SII)); - newsii.indexksz = const_cpu_to_le16(sizeof(SII_INDEX_KEY)); - newsii.flags = const_cpu_to_le16(0); - newsii.fill2 = const_cpu_to_le16(0); - newsii.keysecurid = keyid; - newsii.hash = hash; - newsii.securid = keyid; - realign.all = cpu_to_le64(offs); - newsii.dataoffsh = realign.parts.dataoffsh; - newsii.dataoffsl = realign.parts.dataoffsl; - newsii.datasize = cpu_to_le32(attrsz - + sizeof(SECURITY_DESCRIPTOR_HEADER)); - if (!ntfs_ie_add(xsii,(INDEX_ENTRY*)&newsii)) { + xsii = vol->secure_xsii; + ntfs_index_ctx_reinit(xsii); + newsii.offs = const_cpu_to_le16(20); + newsii.size = const_cpu_to_le16(sizeof(struct SII) - 20); + newsii.fill1 = const_cpu_to_le32(0); + newsii.indexsz = const_cpu_to_le16(sizeof(struct SII)); + newsii.indexksz = const_cpu_to_le16(sizeof(SII_INDEX_KEY)); + newsii.flags = const_cpu_to_le16(0); + newsii.fill2 = const_cpu_to_le16(0); + newsii.keysecurid = keyid; + newsii.hash = hash; + newsii.securid = keyid; + realign.all = cpu_to_le64(offs); + newsii.dataoffsh = realign.parts.dataoffsh; + newsii.dataoffsl = realign.parts.dataoffsl; + newsii.datasize = cpu_to_le32(attrsz + + sizeof(SECURITY_DESCRIPTOR_HEADER)); + if (!ntfs_ie_add(xsii,(INDEX_ENTRY*)&newsii)) { - /* enter a new $SDH record */ + /* enter a new $SDH record */ - xsdh = vol->secure_xsdh; - ntfs_index_ctx_reinit(xsdh); - newsdh.offs = const_cpu_to_le16(24); - newsdh.size = const_cpu_to_le16( - sizeof(SECURITY_DESCRIPTOR_HEADER)); - newsdh.fill1 = const_cpu_to_le32(0); - newsdh.indexsz = const_cpu_to_le16( - sizeof(struct SDH)); - newsdh.indexksz = const_cpu_to_le16( - sizeof(SDH_INDEX_KEY)); - newsdh.flags = const_cpu_to_le16(0); - newsdh.fill2 = const_cpu_to_le16(0); - newsdh.keyhash = hash; - newsdh.keysecurid = keyid; - newsdh.hash = hash; - newsdh.securid = keyid; - newsdh.dataoffsh = realign.parts.dataoffsh; - newsdh.dataoffsl = realign.parts.dataoffsl; - newsdh.datasize = cpu_to_le32(attrsz - + sizeof(SECURITY_DESCRIPTOR_HEADER)); - /* special filler value, Windows generally */ - /* fills with 0x00490049, sometimes with zero */ - newsdh.fill3 = const_cpu_to_le32(0x00490049); - if (!ntfs_ie_add(xsdh,(INDEX_ENTRY*)&newsdh)) - res = 0; - } - return (res); + xsdh = vol->secure_xsdh; + ntfs_index_ctx_reinit(xsdh); + newsdh.offs = const_cpu_to_le16(24); + newsdh.size = const_cpu_to_le16( + sizeof(SECURITY_DESCRIPTOR_HEADER)); + newsdh.fill1 = const_cpu_to_le32(0); + newsdh.indexsz = const_cpu_to_le16( + sizeof(struct SDH)); + newsdh.indexksz = const_cpu_to_le16( + sizeof(SDH_INDEX_KEY)); + newsdh.flags = const_cpu_to_le16(0); + newsdh.fill2 = const_cpu_to_le16(0); + newsdh.keyhash = hash; + newsdh.keysecurid = keyid; + newsdh.hash = hash; + newsdh.securid = keyid; + newsdh.dataoffsh = realign.parts.dataoffsh; + newsdh.dataoffsl = realign.parts.dataoffsl; + newsdh.datasize = cpu_to_le32(attrsz + + sizeof(SECURITY_DESCRIPTOR_HEADER)); + /* special filler value, Windows generally */ + /* fills with 0x00490049, sometimes with zero */ + newsdh.fill3 = const_cpu_to_le32(0x00490049); + if (!ntfs_ie_add(xsdh,(INDEX_ENTRY*)&newsdh)) + res = 0; + } + return (res); } /* @@ -682,158 +691,159 @@ static int entersecurity_indexes(ntfs_volume *vol, s64 attrsz, */ static le32 entersecurityattr(ntfs_volume *vol, - const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, - le32 hash) { - union { - struct { - le32 dataoffsl; - le32 dataoffsh; - } parts; - le64 all; - } realign; - le32 securid; - le32 keyid; - u32 newkey; - off_t offs; - int gap; - int size; - BOOL found; - struct SII *psii; - INDEX_ENTRY *entry; - INDEX_ENTRY *next; - ntfs_index_context *xsii; - ntfs_attr *na; - int olderrno; + const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, + le32 hash) +{ + union { + struct { + le32 dataoffsl; + le32 dataoffsh; + } parts; + le64 all; + } realign; + le32 securid; + le32 keyid; + u32 newkey; + off_t offs; + int gap; + int size; + BOOL found; + struct SII *psii; + INDEX_ENTRY *entry; + INDEX_ENTRY *next; + ntfs_index_context *xsii; + ntfs_attr *na; + int olderrno; - /* find the first available securid beyond the last key */ - /* in $Secure:$SII. This also determines the first */ - /* available location in $Secure:$SDS, as this stream */ - /* is always appended to and the id's are allocated */ - /* in sequence */ + /* find the first available securid beyond the last key */ + /* in $Secure:$SII. This also determines the first */ + /* available location in $Secure:$SDS, as this stream */ + /* is always appended to and the id's are allocated */ + /* in sequence */ - securid = const_cpu_to_le32(0); - xsii = vol->secure_xsii; - ntfs_index_ctx_reinit(xsii); - offs = size = 0; - keyid = const_cpu_to_le32(-1); - olderrno = errno; - found = !ntfs_index_lookup((char*)&keyid, - sizeof(SII_INDEX_KEY), xsii); - if (!found && (errno != ENOENT)) { - ntfs_log_perror("Inconsistency in index $SII"); - psii = (struct SII*)NULL; - } else { - /* restore errno to avoid misinterpretation */ - errno = olderrno; - entry = xsii->entry; - psii = (struct SII*)xsii->entry; - } - if (psii) { - /* - * Get last entry in block, but must get first one - * one first, as we should already be beyond the - * last one. For some reason the search for the last - * entry sometimes does not return the last block... - * we assume this can only happen in root block - */ - if (xsii->is_in_root) - entry = ntfs_ie_get_first - ((INDEX_HEADER*)&xsii->ir->index); - else - entry = ntfs_ie_get_first - ((INDEX_HEADER*)&xsii->ib->index); - /* - * All index blocks should be at least half full - * so there always is a last entry but one, - * except when creating the first entry in index root. - * A simplified version of next(), limited to - * current index node, could be used - */ - keyid = const_cpu_to_le32(0); - while (entry) { - next = ntfs_index_next(entry,xsii); - if (next) { - psii = (struct SII*)next; - /* save last key and */ - /* available position */ - keyid = psii->keysecurid; - realign.parts.dataoffsh - = psii->dataoffsh; - realign.parts.dataoffsl - = psii->dataoffsl; - offs = le64_to_cpu(realign.all); - size = le32_to_cpu(psii->datasize); - } - entry = next; - } - } - if (!keyid) { - /* - * could not find any entry, before creating the first - * entry, make a double check by making sure size of $SII - * is less than needed for one entry - */ - securid = const_cpu_to_le32(0); - na = ntfs_attr_open(vol->secure_ni,AT_INDEX_ROOT,sii_stream,4); - if (na) { - if ((size_t)na->data_size < sizeof(struct SII)) { - ntfs_log_error("Creating the first security_id\n"); - securid = const_cpu_to_le32(FIRST_SECURITY_ID); - } - ntfs_attr_close(na); - } - if (!securid) { - ntfs_log_error("Error creating a security_id\n"); - errno = EIO; - } - } else { - newkey = le32_to_cpu(keyid) + 1; - securid = cpu_to_le32(newkey); - } - /* - * The security attr has to be written twice 256KB - * apart. This implies that offsets like - * 0x40000*odd_integer must be left available for - * the second copy. So align to next block when - * the last byte overflows on a wrong block. - */ + securid = const_cpu_to_le32(0); + xsii = vol->secure_xsii; + ntfs_index_ctx_reinit(xsii); + offs = size = 0; + keyid = const_cpu_to_le32(-1); + olderrno = errno; + found = !ntfs_index_lookup((char*)&keyid, + sizeof(SII_INDEX_KEY), xsii); + if (!found && (errno != ENOENT)) { + ntfs_log_perror("Inconsistency in index $SII"); + psii = (struct SII*)NULL; + } else { + /* restore errno to avoid misinterpretation */ + errno = olderrno; + entry = xsii->entry; + psii = (struct SII*)xsii->entry; + } + if (psii) { + /* + * Get last entry in block, but must get first one + * one first, as we should already be beyond the + * last one. For some reason the search for the last + * entry sometimes does not return the last block... + * we assume this can only happen in root block + */ + if (xsii->is_in_root) + entry = ntfs_ie_get_first + ((INDEX_HEADER*)&xsii->ir->index); + else + entry = ntfs_ie_get_first + ((INDEX_HEADER*)&xsii->ib->index); + /* + * All index blocks should be at least half full + * so there always is a last entry but one, + * except when creating the first entry in index root. + * A simplified version of next(), limited to + * current index node, could be used + */ + keyid = const_cpu_to_le32(0); + while (entry) { + next = ntfs_index_next(entry,xsii); + if (next) { + psii = (struct SII*)next; + /* save last key and */ + /* available position */ + keyid = psii->keysecurid; + realign.parts.dataoffsh + = psii->dataoffsh; + realign.parts.dataoffsl + = psii->dataoffsl; + offs = le64_to_cpu(realign.all); + size = le32_to_cpu(psii->datasize); + } + entry = next; + } + } + if (!keyid) { + /* + * could not find any entry, before creating the first + * entry, make a double check by making sure size of $SII + * is less than needed for one entry + */ + securid = const_cpu_to_le32(0); + na = ntfs_attr_open(vol->secure_ni,AT_INDEX_ROOT,sii_stream,4); + if (na) { + if ((size_t)na->data_size < sizeof(struct SII)) { + ntfs_log_error("Creating the first security_id\n"); + securid = const_cpu_to_le32(FIRST_SECURITY_ID); + } + ntfs_attr_close(na); + } + if (!securid) { + ntfs_log_error("Error creating a security_id\n"); + errno = EIO; + } + } else { + newkey = le32_to_cpu(keyid) + 1; + securid = cpu_to_le32(newkey); + } + /* + * The security attr has to be written twice 256KB + * apart. This implies that offsets like + * 0x40000*odd_integer must be left available for + * the second copy. So align to next block when + * the last byte overflows on a wrong block. + */ - if (securid) { - gap = (-size) & (ALIGN_SDS_ENTRY - 1); - offs += gap + size; - if ((offs + attrsz + sizeof(SECURITY_DESCRIPTOR_HEADER) - 1) - & ALIGN_SDS_BLOCK) { - offs = ((offs + attrsz - + sizeof(SECURITY_DESCRIPTOR_HEADER) - 1) - | (ALIGN_SDS_BLOCK - 1)) + 1; - } - if (!(offs & (ALIGN_SDS_BLOCK - 1))) - entersecurity_stuff(vol, offs); - /* - * now write the security attr to storage : - * first data, then SII, then SDH - * If failure occurs while writing SDS, data will never - * be accessed through indexes, and will be overwritten - * by the next allocated descriptor - * If failure occurs while writing SII, the id has not - * recorded and will be reallocated later - * If failure occurs while writing SDH, the space allocated - * in SDS or SII will not be reused, an inconsistency - * will persist with no significant consequence - */ - if (entersecurity_data(vol, attr, attrsz, hash, securid, offs, gap) - || entersecurity_indexes(vol, attrsz, hash, securid, offs)) - securid = const_cpu_to_le32(0); - } - /* inode now is dirty, synchronize it all */ - ntfs_index_entry_mark_dirty(vol->secure_xsii); - ntfs_index_ctx_reinit(vol->secure_xsii); - ntfs_index_entry_mark_dirty(vol->secure_xsdh); - ntfs_index_ctx_reinit(vol->secure_xsdh); - NInoSetDirty(vol->secure_ni); - if (ntfs_inode_sync(vol->secure_ni)) - ntfs_log_perror("Could not sync $Secure\n"); - return (securid); + if (securid) { + gap = (-size) & (ALIGN_SDS_ENTRY - 1); + offs += gap + size; + if ((offs + attrsz + sizeof(SECURITY_DESCRIPTOR_HEADER) - 1) + & ALIGN_SDS_BLOCK) { + offs = ((offs + attrsz + + sizeof(SECURITY_DESCRIPTOR_HEADER) - 1) + | (ALIGN_SDS_BLOCK - 1)) + 1; + } + if (!(offs & (ALIGN_SDS_BLOCK - 1))) + entersecurity_stuff(vol, offs); + /* + * now write the security attr to storage : + * first data, then SII, then SDH + * If failure occurs while writing SDS, data will never + * be accessed through indexes, and will be overwritten + * by the next allocated descriptor + * If failure occurs while writing SII, the id has not + * recorded and will be reallocated later + * If failure occurs while writing SDH, the space allocated + * in SDS or SII will not be reused, an inconsistency + * will persist with no significant consequence + */ + if (entersecurity_data(vol, attr, attrsz, hash, securid, offs, gap) + || entersecurity_indexes(vol, attrsz, hash, securid, offs)) + securid = const_cpu_to_le32(0); + } + /* inode now is dirty, synchronize it all */ + ntfs_index_entry_mark_dirty(vol->secure_xsii); + ntfs_index_ctx_reinit(vol->secure_xsii); + ntfs_index_entry_mark_dirty(vol->secure_xsdh); + ntfs_index_ctx_reinit(vol->secure_xsdh); + NInoSetDirty(vol->secure_ni); + if (ntfs_inode_sync(vol->secure_ni)) + ntfs_log_perror("Could not sync $Secure\n"); + return (securid); } /* @@ -846,116 +856,117 @@ static le32 entersecurityattr(ntfs_volume *vol, */ static le32 setsecurityattr(ntfs_volume *vol, - const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz) { - struct SDH *psdh; /* this is an image of index (le) */ - union { - struct { - le32 dataoffsl; - le32 dataoffsh; - } parts; - le64 all; - } realign; - BOOL found; - BOOL collision; - size_t size; - size_t rdsize; - s64 offs; - int res; - ntfs_index_context *xsdh; - char *oldattr; - SDH_INDEX_KEY key; - INDEX_ENTRY *entry; - le32 securid; - le32 hash; - int olderrno; + const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz) +{ + struct SDH *psdh; /* this is an image of index (le) */ + union { + struct { + le32 dataoffsl; + le32 dataoffsh; + } parts; + le64 all; + } realign; + BOOL found; + BOOL collision; + size_t size; + size_t rdsize; + s64 offs; + int res; + ntfs_index_context *xsdh; + char *oldattr; + SDH_INDEX_KEY key; + INDEX_ENTRY *entry; + le32 securid; + le32 hash; + int olderrno; - hash = ntfs_security_hash(attr,attrsz); - oldattr = (char*)NULL; - securid = const_cpu_to_le32(0); - res = 0; - xsdh = vol->secure_xsdh; - if (vol->secure_ni && xsdh && !vol->secure_reentry++) { - ntfs_index_ctx_reinit(xsdh); - /* - * find the nearest key as (hash,0) - * (do not search for partial key : in case of collision, - * it could return a key which is not the first one which - * collides) - */ - key.hash = hash; - key.security_id = const_cpu_to_le32(0); - olderrno = errno; - found = !ntfs_index_lookup((char*)&key, - sizeof(SDH_INDEX_KEY), xsdh); - if (!found && (errno != ENOENT)) - ntfs_log_perror("Inconsistency in index $SDH"); - else { - /* restore errno to avoid misinterpretation */ - errno = olderrno; - entry = xsdh->entry; - found = FALSE; - /* - * lookup() may return a node with no data, - * if so get next - */ - if (entry->ie_flags & INDEX_ENTRY_END) - entry = ntfs_index_next(entry,xsdh); - do { - collision = FALSE; - psdh = (struct SDH*)entry; - if (psdh) - size = (size_t) le32_to_cpu(psdh->datasize) - - sizeof(SECURITY_DESCRIPTOR_HEADER); - else size = 0; - /* if hash is not the same, the key is not present */ - if (psdh && (size > 0) - && (psdh->keyhash == hash)) { - /* if hash is the same */ - /* check the whole record */ - realign.parts.dataoffsh = psdh->dataoffsh; - realign.parts.dataoffsl = psdh->dataoffsl; - offs = le64_to_cpu(realign.all) - + sizeof(SECURITY_DESCRIPTOR_HEADER); - oldattr = (char*)ntfs_malloc(size); - if (oldattr) { - rdsize = ntfs_local_read( - vol->secure_ni, - STREAM_SDS, 4, - oldattr, size, offs); - found = (rdsize == size) - && !memcmp(oldattr,attr,size); - free(oldattr); - /* if the records do not compare */ - /* (hash collision), try next one */ - if (!found) { - entry = ntfs_index_next( - entry,xsdh); - collision = TRUE; - } - } else - res = ENOMEM; - } - } while (collision && entry); - if (found) - securid = psdh->keysecurid; - else { - if (res) { - errno = res; - securid = const_cpu_to_le32(0); - } else { - /* - * no matching key : - * have to build a new one - */ - securid = entersecurityattr(vol, - attr, attrsz, hash); - } - } - } - } - if (--vol->secure_reentry) - ntfs_log_perror("Reentry error, check no multithreading\n"); - return (securid); + hash = ntfs_security_hash(attr,attrsz); + oldattr = (char*)NULL; + securid = const_cpu_to_le32(0); + res = 0; + xsdh = vol->secure_xsdh; + if (vol->secure_ni && xsdh && !vol->secure_reentry++) { + ntfs_index_ctx_reinit(xsdh); + /* + * find the nearest key as (hash,0) + * (do not search for partial key : in case of collision, + * it could return a key which is not the first one which + * collides) + */ + key.hash = hash; + key.security_id = const_cpu_to_le32(0); + olderrno = errno; + found = !ntfs_index_lookup((char*)&key, + sizeof(SDH_INDEX_KEY), xsdh); + if (!found && (errno != ENOENT)) + ntfs_log_perror("Inconsistency in index $SDH"); + else { + /* restore errno to avoid misinterpretation */ + errno = olderrno; + entry = xsdh->entry; + found = FALSE; + /* + * lookup() may return a node with no data, + * if so get next + */ + if (entry->ie_flags & INDEX_ENTRY_END) + entry = ntfs_index_next(entry,xsdh); + do { + collision = FALSE; + psdh = (struct SDH*)entry; + if (psdh) + size = (size_t) le32_to_cpu(psdh->datasize) + - sizeof(SECURITY_DESCRIPTOR_HEADER); + else size = 0; + /* if hash is not the same, the key is not present */ + if (psdh && (size > 0) + && (psdh->keyhash == hash)) { + /* if hash is the same */ + /* check the whole record */ + realign.parts.dataoffsh = psdh->dataoffsh; + realign.parts.dataoffsl = psdh->dataoffsl; + offs = le64_to_cpu(realign.all) + + sizeof(SECURITY_DESCRIPTOR_HEADER); + oldattr = (char*)ntfs_malloc(size); + if (oldattr) { + rdsize = ntfs_local_read( + vol->secure_ni, + STREAM_SDS, 4, + oldattr, size, offs); + found = (rdsize == size) + && !memcmp(oldattr,attr,size); + free(oldattr); + /* if the records do not compare */ + /* (hash collision), try next one */ + if (!found) { + entry = ntfs_index_next( + entry,xsdh); + collision = TRUE; + } + } else + res = ENOMEM; + } + } while (collision && entry); + if (found) + securid = psdh->keysecurid; + else { + if (res) { + errno = res; + securid = const_cpu_to_le32(0); + } else { + /* + * no matching key : + * have to build a new one + */ + securid = entersecurityattr(vol, + attr, attrsz, hash); + } + } + } + } + if (--vol->secure_reentry) + ntfs_log_perror("Reentry error, check no multithreading\n"); + return (securid); } @@ -968,108 +979,109 @@ static le32 setsecurityattr(ntfs_volume *vol, */ static int update_secur_descr(ntfs_volume *vol, - char *newattr, ntfs_inode *ni) { - int newattrsz; - int written; - int res; - ntfs_attr *na; + char *newattr, ntfs_inode *ni) +{ + int newattrsz; + int written; + int res; + ntfs_attr *na; - newattrsz = ntfs_attr_size(newattr); + newattrsz = ntfs_attr_size(newattr); #if !FORCE_FORMAT_v1x - if ((vol->major_ver < 3) || !vol->secure_ni) { + if ((vol->major_ver < 3) || !vol->secure_ni) { #endif - /* update for NTFS format v1.x */ + /* update for NTFS format v1.x */ - /* update the old security attribute */ - na = ntfs_attr_open(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0); - if (na) { - /* resize attribute */ - res = ntfs_attr_truncate(na, (s64) newattrsz); - /* overwrite value */ - if (!res) { - written = (int)ntfs_attr_pwrite(na, (s64) 0, - (s64) newattrsz, newattr); - if (written != newattrsz) { - ntfs_log_error("Failed to update " - "a v1.x security descriptor\n"); - errno = EIO; - res = -1; - } - } + /* update the old security attribute */ + na = ntfs_attr_open(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0); + if (na) { + /* resize attribute */ + res = ntfs_attr_truncate(na, (s64) newattrsz); + /* overwrite value */ + if (!res) { + written = (int)ntfs_attr_pwrite(na, (s64) 0, + (s64) newattrsz, newattr); + if (written != newattrsz) { + ntfs_log_error("Failed to update " + "a v1.x security descriptor\n"); + errno = EIO; + res = -1; + } + } - ntfs_attr_close(na); - /* if old security attribute was found, also */ - /* truncate standard information attribute to v1.x */ - /* this is needed when security data is wanted */ - /* as v1.x though volume is formatted for v3.x */ - na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, - AT_UNNAMED, 0); - if (na) { - clear_nino_flag(ni, v3_Extensions); - /* - * Truncating the record does not sweep extensions - * from copy in memory. Clear security_id to be safe - */ - ni->security_id = const_cpu_to_le32(0); - res = ntfs_attr_truncate(na, (s64)48); - ntfs_attr_close(na); - clear_nino_flag(ni, v3_Extensions); - } - } else { - /* - * insert the new security attribute if there - * were none - */ - res = ntfs_attr_add(ni, AT_SECURITY_DESCRIPTOR, - AT_UNNAMED, 0, (u8*)newattr, - (s64) newattrsz); - } + ntfs_attr_close(na); + /* if old security attribute was found, also */ + /* truncate standard information attribute to v1.x */ + /* this is needed when security data is wanted */ + /* as v1.x though volume is formatted for v3.x */ + na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, + AT_UNNAMED, 0); + if (na) { + clear_nino_flag(ni, v3_Extensions); + /* + * Truncating the record does not sweep extensions + * from copy in memory. Clear security_id to be safe + */ + ni->security_id = const_cpu_to_le32(0); + res = ntfs_attr_truncate(na, (s64)48); + ntfs_attr_close(na); + clear_nino_flag(ni, v3_Extensions); + } + } else { + /* + * insert the new security attribute if there + * were none + */ + res = ntfs_attr_add(ni, AT_SECURITY_DESCRIPTOR, + AT_UNNAMED, 0, (u8*)newattr, + (s64) newattrsz); + } #if !FORCE_FORMAT_v1x - } else { + } else { - /* update for NTFS format v3.x */ + /* update for NTFS format v3.x */ - le32 securid; + le32 securid; - securid = setsecurityattr(vol, - (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, - (s64)newattrsz); - if (securid) { - na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, - AT_UNNAMED, 0); - if (na) { - res = 0; - if (!test_nino_flag(ni, v3_Extensions)) { - /* expand standard information attribute to v3.x */ - res = ntfs_attr_truncate(na, - (s64)sizeof(STANDARD_INFORMATION)); - ni->owner_id = const_cpu_to_le32(0); - ni->quota_charged = const_cpu_to_le64(0); - ni->usn = const_cpu_to_le64(0); - ntfs_attr_remove(ni, - AT_SECURITY_DESCRIPTOR, - AT_UNNAMED, 0); - } - set_nino_flag(ni, v3_Extensions); - ni->security_id = securid; - ntfs_attr_close(na); - } else { - ntfs_log_error("Failed to update " - "standard informations\n"); - errno = EIO; - res = -1; - } - } else - res = -1; - } + securid = setsecurityattr(vol, + (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, + (s64)newattrsz); + if (securid) { + na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, + AT_UNNAMED, 0); + if (na) { + res = 0; + if (!test_nino_flag(ni, v3_Extensions)) { + /* expand standard information attribute to v3.x */ + res = ntfs_attr_truncate(na, + (s64)sizeof(STANDARD_INFORMATION)); + ni->owner_id = const_cpu_to_le32(0); + ni->quota_charged = const_cpu_to_le64(0); + ni->usn = const_cpu_to_le64(0); + ntfs_attr_remove(ni, + AT_SECURITY_DESCRIPTOR, + AT_UNNAMED, 0); + } + set_nino_flag(ni, v3_Extensions); + ni->security_id = securid; + ntfs_attr_close(na); + } else { + ntfs_log_error("Failed to update " + "standard informations\n"); + errno = EIO; + res = -1; + } + } else + res = -1; + } #endif - /* mark node as dirty */ - NInoSetDirty(ni); - ntfs_inode_sync(ni); /* useful ? */ - return (res); + /* mark node as dirty */ + NInoSetDirty(ni); + ntfs_inode_sync(ni); /* useful ? */ + return (res); } /* @@ -1077,7 +1089,7 @@ static int update_secur_descr(ntfs_volume *vol, * This is intended to allow graceful upgrades for files which * were created in previous versions, with a security attributes * and no security id. - * + * * It will allocate a security id and replace the individual * security attribute by a reference to the global one * @@ -1094,55 +1106,56 @@ static int update_secur_descr(ntfs_volume *vol, */ static int upgrade_secur_desc(ntfs_volume *vol, const char *path, - const char *attr, ntfs_inode *ni) { - int attrsz; - int res; - le32 securid; - ntfs_attr *na; + const char *attr, ntfs_inode *ni) +{ + int attrsz; + int res; + le32 securid; + ntfs_attr *na; - /* - * upgrade requires NTFS format v3.x - * also refuse upgrading for special files - */ + /* + * upgrade requires NTFS format v3.x + * also refuse upgrading for special files + */ - if ((vol->major_ver >= 3) - && (path[0] == '/') - && (path[1] != '$') && (path[1] != '\0')) { - attrsz = ntfs_attr_size(attr); - securid = setsecurityattr(vol, - (const SECURITY_DESCRIPTOR_RELATIVE*)attr, - (s64)attrsz); - if (securid) { - na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, - AT_UNNAMED, 0); - if (na) { - res = 0; - /* expand standard information attribute to v3.x */ - res = ntfs_attr_truncate(na, - (s64)sizeof(STANDARD_INFORMATION)); - ni->owner_id = const_cpu_to_le32(0); - ni->quota_charged = const_cpu_to_le64(0); - ni->usn = const_cpu_to_le64(0); - ntfs_attr_remove(ni, AT_SECURITY_DESCRIPTOR, - AT_UNNAMED, 0); - set_nino_flag(ni, v3_Extensions); - ni->security_id = securid; - ntfs_attr_close(na); - } else { - ntfs_log_error("Failed to upgrade " - "standard informations\n"); - errno = EIO; - res = -1; - } - } else - res = -1; - /* mark node as dirty */ - NInoSetDirty(ni); - ntfs_inode_sync(ni); /* useful ? */ - } else - res = 1; + if ((vol->major_ver >= 3) + && (path[0] == '/') + && (path[1] != '$') && (path[1] != '\0')) { + attrsz = ntfs_attr_size(attr); + securid = setsecurityattr(vol, + (const SECURITY_DESCRIPTOR_RELATIVE*)attr, + (s64)attrsz); + if (securid) { + na = ntfs_attr_open(ni, AT_STANDARD_INFORMATION, + AT_UNNAMED, 0); + if (na) { + res = 0; + /* expand standard information attribute to v3.x */ + res = ntfs_attr_truncate(na, + (s64)sizeof(STANDARD_INFORMATION)); + ni->owner_id = const_cpu_to_le32(0); + ni->quota_charged = const_cpu_to_le64(0); + ni->usn = const_cpu_to_le64(0); + ntfs_attr_remove(ni, AT_SECURITY_DESCRIPTOR, + AT_UNNAMED, 0); + set_nino_flag(ni, v3_Extensions); + ni->security_id = securid; + ntfs_attr_close(na); + } else { + ntfs_log_error("Failed to upgrade " + "standard informations\n"); + errno = EIO; + res = -1; + } + } else + res = -1; + /* mark node as dirty */ + NInoSetDirty(ni); + ntfs_inode_sync(ni); /* useful ? */ + } else + res = 1; - return (res); + return (res); } /* @@ -1160,25 +1173,26 @@ static int upgrade_secur_desc(ntfs_volume *vol, const char *path, * */ -static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) { - BOOL ingroup; - int grcnt; - gid_t *groups; - struct MAPPING *user; +static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) +{ + BOOL ingroup; + int grcnt; + gid_t *groups; + struct MAPPING *user; - ingroup = FALSE; - if (uid) { - user = scx->mapping[MAPUSERS]; - while (user && ((uid_t)user->xid != uid)) - user = user->next; - if (user) { - groups = user->groups; - grcnt = user->grcnt; - while ((--grcnt >= 0) && (groups[grcnt] != gid)) { } - ingroup = (grcnt >= 0); - } - } - return (ingroup); + ingroup = FALSE; + if (uid) { + user = scx->mapping[MAPUSERS]; + while (user && ((uid_t)user->xid != uid)) + user = user->next; + if (user) { + groups = user->groups; + grcnt = user->grcnt; + while ((--grcnt >= 0) && (groups[grcnt] != gid)) { } + ingroup = (grcnt >= 0); + } + } + return (ingroup); } @@ -1203,87 +1217,88 @@ static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid * contains the same data. */ -static BOOL groupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) { - static char key[] = "\nGroups:"; - char buf[BUFSZ+1]; - char filename[64]; - enum { INKEY, INSEP, INNUM, INEND } state; - int fd; - char c; - int matched; - BOOL ismember; - int got; - char *p; - gid_t grp; - pid_t tid; +static BOOL groupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) +{ + static char key[] = "\nGroups:"; + char buf[BUFSZ+1]; + char filename[64]; + enum { INKEY, INSEP, INNUM, INEND } state; + int fd; + char c; + int matched; + BOOL ismember; + int got; + char *p; + gid_t grp; + pid_t tid; - if (scx->vol->secure_flags & (1 << SECURITY_STATICGRPS)) - ismember = staticgroupmember(scx, uid, gid); - else { - ismember = FALSE; /* default return */ - tid = scx->tid; - sprintf(filename,"/proc/%u/task/%u/status",tid,tid); - fd = open(filename,O_RDONLY); - if (fd >= 0) { - got = read(fd, buf, BUFSZ); - buf[got] = 0; - state = INKEY; - matched = 0; - p = buf; - grp = 0; - /* - * A simple automaton to process lines like - * Groups: 14 500 513 - */ - do { - c = *p++; - if (!c) { - /* refill buffer */ - got = read(fd, buf, BUFSZ); - buf[got] = 0; - p = buf; - c = *p++; /* 0 at end of file */ - } - switch (state) { - case INKEY : - if (key[matched] == c) { - if (!key[++matched]) - state = INSEP; - } else - if (key[0] == c) - matched = 1; - else - matched = 0; - break; - case INSEP : - if ((c >= '0') && (c <= '9')) { - grp = c - '0'; - state = INNUM; - } else - if ((c != ' ') && (c != '\t')) - state = INEND; - break; - case INNUM : - if ((c >= '0') && (c <= '9')) - grp = grp*10 + c - '0'; - else { - ismember = (grp == gid); - if ((c != ' ') && (c != '\t')) - state = INEND; - else - state = INSEP; - } - default : - break; - } - } while (!ismember && c && (state != INEND)); - close(fd); - if (!c) - ntfs_log_error("No group record found in %s\n",filename); - } else - ntfs_log_error("Could not open %s\n",filename); - } - return (ismember); + if (scx->vol->secure_flags & (1 << SECURITY_STATICGRPS)) + ismember = staticgroupmember(scx, uid, gid); + else { + ismember = FALSE; /* default return */ + tid = scx->tid; + sprintf(filename,"/proc/%u/task/%u/status",tid,tid); + fd = open(filename,O_RDONLY); + if (fd >= 0) { + got = read(fd, buf, BUFSZ); + buf[got] = 0; + state = INKEY; + matched = 0; + p = buf; + grp = 0; + /* + * A simple automaton to process lines like + * Groups: 14 500 513 + */ + do { + c = *p++; + if (!c) { + /* refill buffer */ + got = read(fd, buf, BUFSZ); + buf[got] = 0; + p = buf; + c = *p++; /* 0 at end of file */ + } + switch (state) { + case INKEY : + if (key[matched] == c) { + if (!key[++matched]) + state = INSEP; + } else + if (key[0] == c) + matched = 1; + else + matched = 0; + break; + case INSEP : + if ((c >= '0') && (c <= '9')) { + grp = c - '0'; + state = INNUM; + } else + if ((c != ' ') && (c != '\t')) + state = INEND; + break; + case INNUM : + if ((c >= '0') && (c <= '9')) + grp = grp*10 + c - '0'; + else { + ismember = (grp == gid); + if ((c != ' ') && (c != '\t')) + state = INEND; + else + state = INSEP; + } + default : + break; + } + } while (!ismember && c && (state != INEND)); + close(fd); + if (!c) + ntfs_log_error("No group record found in %s\n",filename); + } else + ntfs_log_error("Could not open %s\n",filename); + } + return (ismember); } /* @@ -1324,28 +1339,29 @@ static BOOL groupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) { */ static struct PERMISSIONS_CACHE *create_caches(struct SECURITY_CONTEXT *scx, - u32 securindex) { - struct PERMISSIONS_CACHE *cache; - unsigned int index1; - unsigned int i; + u32 securindex) +{ + struct PERMISSIONS_CACHE *cache; + unsigned int index1; + unsigned int i; - cache = (struct PERMISSIONS_CACHE*)NULL; - /* create the first permissions blocks */ - index1 = securindex >> CACHE_PERMISSIONS_BITS; - cache = (struct PERMISSIONS_CACHE*) - ntfs_malloc(sizeof(struct PERMISSIONS_CACHE) - + index1*sizeof(struct CACHED_PERMISSIONS*)); - if (cache) { - cache->head.last = index1; - cache->head.p_reads = 0; - cache->head.p_hits = 0; - cache->head.p_writes = 0; - *scx->pseccache = cache; - for (i=0; i<=index1; i++) - cache->cachetable[i] - = (struct CACHED_PERMISSIONS*)NULL; - } - return (cache); + cache = (struct PERMISSIONS_CACHE*)NULL; + /* create the first permissions blocks */ + index1 = securindex >> CACHE_PERMISSIONS_BITS; + cache = (struct PERMISSIONS_CACHE*) + ntfs_malloc(sizeof(struct PERMISSIONS_CACHE) + + index1*sizeof(struct CACHED_PERMISSIONS*)); + if (cache) { + cache->head.last = index1; + cache->head.p_reads = 0; + cache->head.p_hits = 0; + cache->head.p_writes = 0; + *scx->pseccache = cache; + for (i=0; i<=index1; i++) + cache->cachetable[i] + = (struct CACHED_PERMISSIONS*)NULL; + } + return (cache); } /* @@ -1353,114 +1369,118 @@ static struct PERMISSIONS_CACHE *create_caches(struct SECURITY_CONTEXT *scx, * The only purpose is to facilitate the detection of memory leaks */ -static void free_caches(struct SECURITY_CONTEXT *scx) { - unsigned int index1; - struct PERMISSIONS_CACHE *pseccache; +static void free_caches(struct SECURITY_CONTEXT *scx) +{ + unsigned int index1; + struct PERMISSIONS_CACHE *pseccache; - pseccache = *scx->pseccache; - if (pseccache) { - for (index1=0; index1<=pseccache->head.last; index1++) - if (pseccache->cachetable[index1]) { + pseccache = *scx->pseccache; + if (pseccache) { + for (index1=0; index1<=pseccache->head.last; index1++) + if (pseccache->cachetable[index1]) { #if POSIXACLS - struct CACHED_PERMISSIONS *cacheentry; - unsigned int index2; + struct CACHED_PERMISSIONS *cacheentry; + unsigned int index2; - for (index2=0; index2<(1<< CACHE_PERMISSIONS_BITS); index2++) { - cacheentry = &pseccache->cachetable[index1][index2]; - if (cacheentry->valid - && cacheentry->pxdesc) - free(cacheentry->pxdesc); - } + for (index2=0; index2<(1<< CACHE_PERMISSIONS_BITS); index2++) { + cacheentry = &pseccache->cachetable[index1][index2]; + if (cacheentry->valid + && cacheentry->pxdesc) + free(cacheentry->pxdesc); + } #endif - free(pseccache->cachetable[index1]); - } - free(pseccache); - } + free(pseccache->cachetable[index1]); + } + free(pseccache); + } } static int compare(const struct CACHED_SECURID *cached, - const struct CACHED_SECURID *item) { + const struct CACHED_SECURID *item) +{ #if POSIXACLS - size_t csize; - size_t isize; + size_t csize; + size_t isize; - /* only compare data and sizes */ - csize = (cached->variable ? - sizeof(struct POSIX_ACL) - + (((struct POSIX_SECURITY*)cached->variable)->acccnt - + ((struct POSIX_SECURITY*)cached->variable)->defcnt) - *sizeof(struct POSIX_ACE) : - 0); - isize = (item->variable ? - sizeof(struct POSIX_ACL) - + (((struct POSIX_SECURITY*)item->variable)->acccnt - + ((struct POSIX_SECURITY*)item->variable)->defcnt) - *sizeof(struct POSIX_ACE) : - 0); - return ((cached->uid != item->uid) - || (cached->gid != item->gid) - || (cached->dmode != item->dmode) - || (csize != isize) - || (csize - && isize - && memcmp(&((struct POSIX_SECURITY*)cached->variable)->acl, - &((struct POSIX_SECURITY*)item->variable)->acl, csize))); + /* only compare data and sizes */ + csize = (cached->variable ? + sizeof(struct POSIX_ACL) + + (((struct POSIX_SECURITY*)cached->variable)->acccnt + + ((struct POSIX_SECURITY*)cached->variable)->defcnt) + *sizeof(struct POSIX_ACE) : + 0); + isize = (item->variable ? + sizeof(struct POSIX_ACL) + + (((struct POSIX_SECURITY*)item->variable)->acccnt + + ((struct POSIX_SECURITY*)item->variable)->defcnt) + *sizeof(struct POSIX_ACE) : + 0); + return ((cached->uid != item->uid) + || (cached->gid != item->gid) + || (cached->dmode != item->dmode) + || (csize != isize) + || (csize + && isize + && memcmp(&((struct POSIX_SECURITY*)cached->variable)->acl, + &((struct POSIX_SECURITY*)item->variable)->acl, csize))); #else - return ((cached->uid != item->uid) - || (cached->gid != item->gid) - || (cached->dmode != item->dmode)); + return ((cached->uid != item->uid) + || (cached->gid != item->gid) + || (cached->dmode != item->dmode)); #endif } static int leg_compare(const struct CACHED_PERMISSIONS_LEGACY *cached, - const struct CACHED_PERMISSIONS_LEGACY *item) { - return (cached->mft_no != item->mft_no); + const struct CACHED_PERMISSIONS_LEGACY *item) +{ + return (cached->mft_no != item->mft_no); } /* * Resize permission cache table * do not call unless resizing is needed - * + * * If allocation fails, the cache size is not updated * Lack of memory is not considered as an error, the cache is left * consistent and errno is not set. */ static void resize_cache(struct SECURITY_CONTEXT *scx, - u32 securindex) { - struct PERMISSIONS_CACHE *oldcache; - struct PERMISSIONS_CACHE *newcache; - int newcnt; - int oldcnt; - unsigned int index1; - unsigned int i; + u32 securindex) +{ + struct PERMISSIONS_CACHE *oldcache; + struct PERMISSIONS_CACHE *newcache; + int newcnt; + int oldcnt; + unsigned int index1; + unsigned int i; - oldcache = *scx->pseccache; - index1 = securindex >> CACHE_PERMISSIONS_BITS; - newcnt = index1 + 1; - if (newcnt <= ((CACHE_PERMISSIONS_SIZE - + (1 << CACHE_PERMISSIONS_BITS) - - 1) >> CACHE_PERMISSIONS_BITS)) { - /* expand cache beyond current end, do not use realloc() */ - /* to avoid losing data when there is no more memory */ - oldcnt = oldcache->head.last + 1; - newcache = (struct PERMISSIONS_CACHE*) - ntfs_malloc( - sizeof(struct PERMISSIONS_CACHE) - + (newcnt - 1)*sizeof(struct CACHED_PERMISSIONS*)); - if (newcache) { - memcpy(newcache,oldcache, - sizeof(struct PERMISSIONS_CACHE) - + (oldcnt - 1)*sizeof(struct CACHED_PERMISSIONS*)); - free(oldcache); - /* mark new entries as not valid */ - for (i=newcache->head.last+1; i<=index1; i++) - newcache->cachetable[i] - = (struct CACHED_PERMISSIONS*)NULL; - newcache->head.last = index1; - *scx->pseccache = newcache; - } - } + oldcache = *scx->pseccache; + index1 = securindex >> CACHE_PERMISSIONS_BITS; + newcnt = index1 + 1; + if (newcnt <= ((CACHE_PERMISSIONS_SIZE + + (1 << CACHE_PERMISSIONS_BITS) + - 1) >> CACHE_PERMISSIONS_BITS)) { + /* expand cache beyond current end, do not use realloc() */ + /* to avoid losing data when there is no more memory */ + oldcnt = oldcache->head.last + 1; + newcache = (struct PERMISSIONS_CACHE*) + ntfs_malloc( + sizeof(struct PERMISSIONS_CACHE) + + (newcnt - 1)*sizeof(struct CACHED_PERMISSIONS*)); + if (newcache) { + memcpy(newcache,oldcache, + sizeof(struct PERMISSIONS_CACHE) + + (oldcnt - 1)*sizeof(struct CACHED_PERMISSIONS*)); + free(oldcache); + /* mark new entries as not valid */ + for (i=newcache->head.last+1; i<=index1; i++) + newcache->cachetable[i] + = (struct CACHED_PERMISSIONS*)NULL; + newcache->head.last = index1; + *scx->pseccache = newcache; + } + } } /* @@ -1473,156 +1493,156 @@ static void resize_cache(struct SECURITY_CONTEXT *scx, #if POSIXACLS static struct CACHED_PERMISSIONS *enter_cache(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, uid_t uid, gid_t gid, - struct POSIX_SECURITY *pxdesc) + ntfs_inode *ni, uid_t uid, gid_t gid, + struct POSIX_SECURITY *pxdesc) #else static struct CACHED_PERMISSIONS *enter_cache(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode) + ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode) #endif { - struct CACHED_PERMISSIONS *cacheentry; - struct CACHED_PERMISSIONS *cacheblock; - struct PERMISSIONS_CACHE *pcache; - u32 securindex; + struct CACHED_PERMISSIONS *cacheentry; + struct CACHED_PERMISSIONS *cacheblock; + struct PERMISSIONS_CACHE *pcache; + u32 securindex; #if POSIXACLS - int pxsize; - struct POSIX_SECURITY *pxcached; + int pxsize; + struct POSIX_SECURITY *pxcached; #endif - unsigned int index1; - unsigned int index2; - int i; + unsigned int index1; + unsigned int index2; + int i; - /* cacheing is only possible if a security_id has been defined */ - if (test_nino_flag(ni, v3_Extensions) - && ni->security_id) { - /* - * Immediately test the most frequent situation - * where the entry exists - */ - securindex = le32_to_cpu(ni->security_id); - index1 = securindex >> CACHE_PERMISSIONS_BITS; - index2 = securindex & ((1 << CACHE_PERMISSIONS_BITS) - 1); - pcache = *scx->pseccache; - if (pcache - && (pcache->head.last >= index1) - && pcache->cachetable[index1]) { - cacheentry = &pcache->cachetable[index1][index2]; - cacheentry->uid = uid; - cacheentry->gid = gid; + /* cacheing is only possible if a security_id has been defined */ + if (test_nino_flag(ni, v3_Extensions) + && ni->security_id) { + /* + * Immediately test the most frequent situation + * where the entry exists + */ + securindex = le32_to_cpu(ni->security_id); + index1 = securindex >> CACHE_PERMISSIONS_BITS; + index2 = securindex & ((1 << CACHE_PERMISSIONS_BITS) - 1); + pcache = *scx->pseccache; + if (pcache + && (pcache->head.last >= index1) + && pcache->cachetable[index1]) { + cacheentry = &pcache->cachetable[index1][index2]; + cacheentry->uid = uid; + cacheentry->gid = gid; #if POSIXACLS - if (cacheentry->valid && cacheentry->pxdesc) - free(cacheentry->pxdesc); - if (pxdesc) { - pxsize = sizeof(struct POSIX_SECURITY) - + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); - pxcached = (struct POSIX_SECURITY*)malloc(pxsize); - if (pxcached) { - memcpy(pxcached, pxdesc, pxsize); - cacheentry->pxdesc = pxcached; - } else { - cacheentry->valid = 0; - cacheentry = (struct CACHED_PERMISSIONS*)NULL; - } - cacheentry->mode = pxdesc->mode & 07777; - } else - cacheentry->pxdesc = (struct POSIX_SECURITY*)NULL; + if (cacheentry->valid && cacheentry->pxdesc) + free(cacheentry->pxdesc); + if (pxdesc) { + pxsize = sizeof(struct POSIX_SECURITY) + + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); + pxcached = (struct POSIX_SECURITY*)malloc(pxsize); + if (pxcached) { + memcpy(pxcached, pxdesc, pxsize); + cacheentry->pxdesc = pxcached; + } else { + cacheentry->valid = 0; + cacheentry = (struct CACHED_PERMISSIONS*)NULL; + } + cacheentry->mode = pxdesc->mode & 07777; + } else + cacheentry->pxdesc = (struct POSIX_SECURITY*)NULL; #else - cacheentry->mode = mode & 07777; + cacheentry->mode = mode & 07777; #endif - cacheentry->inh_fileid = const_cpu_to_le32(0); - cacheentry->inh_dirid = const_cpu_to_le32(0); - cacheentry->valid = 1; - pcache->head.p_writes++; - } else { - if (!pcache) { - /* create the first cache block */ - pcache = create_caches(scx, securindex); - } else { - if (index1 > pcache->head.last) { - resize_cache(scx, securindex); - pcache = *scx->pseccache; - } - } - /* allocate block, if cache table was allocated */ - if (pcache && (index1 <= pcache->head.last)) { - cacheblock = (struct CACHED_PERMISSIONS*) - malloc(sizeof(struct CACHED_PERMISSIONS) - << CACHE_PERMISSIONS_BITS); - pcache->cachetable[index1] = cacheblock; - for (i=0; i<(1 << CACHE_PERMISSIONS_BITS); i++) - cacheblock[i].valid = 0; - cacheentry = &cacheblock[index2]; - if (cacheentry) { - cacheentry->uid = uid; - cacheentry->gid = gid; + cacheentry->inh_fileid = const_cpu_to_le32(0); + cacheentry->inh_dirid = const_cpu_to_le32(0); + cacheentry->valid = 1; + pcache->head.p_writes++; + } else { + if (!pcache) { + /* create the first cache block */ + pcache = create_caches(scx, securindex); + } else { + if (index1 > pcache->head.last) { + resize_cache(scx, securindex); + pcache = *scx->pseccache; + } + } + /* allocate block, if cache table was allocated */ + if (pcache && (index1 <= pcache->head.last)) { + cacheblock = (struct CACHED_PERMISSIONS*) + malloc(sizeof(struct CACHED_PERMISSIONS) + << CACHE_PERMISSIONS_BITS); + pcache->cachetable[index1] = cacheblock; + for (i=0; i<(1 << CACHE_PERMISSIONS_BITS); i++) + cacheblock[i].valid = 0; + cacheentry = &cacheblock[index2]; + if (cacheentry) { + cacheentry->uid = uid; + cacheentry->gid = gid; #if POSIXACLS - if (pxdesc) { - pxsize = sizeof(struct POSIX_SECURITY) - + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); - pxcached = (struct POSIX_SECURITY*)malloc(pxsize); - if (pxcached) { - memcpy(pxcached, pxdesc, pxsize); - cacheentry->pxdesc = pxcached; - } else { - cacheentry->valid = 0; - cacheentry = (struct CACHED_PERMISSIONS*)NULL; - } - cacheentry->mode = pxdesc->mode & 07777; - } else - cacheentry->pxdesc = (struct POSIX_SECURITY*)NULL; + if (pxdesc) { + pxsize = sizeof(struct POSIX_SECURITY) + + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); + pxcached = (struct POSIX_SECURITY*)malloc(pxsize); + if (pxcached) { + memcpy(pxcached, pxdesc, pxsize); + cacheentry->pxdesc = pxcached; + } else { + cacheentry->valid = 0; + cacheentry = (struct CACHED_PERMISSIONS*)NULL; + } + cacheentry->mode = pxdesc->mode & 07777; + } else + cacheentry->pxdesc = (struct POSIX_SECURITY*)NULL; #else - cacheentry->mode = mode & 07777; + cacheentry->mode = mode & 07777; #endif - cacheentry->inh_fileid = const_cpu_to_le32(0); - cacheentry->inh_dirid = const_cpu_to_le32(0); - cacheentry->valid = 1; - pcache->head.p_writes++; - } - } else - cacheentry = (struct CACHED_PERMISSIONS*)NULL; - } - } else { - cacheentry = (struct CACHED_PERMISSIONS*)NULL; + cacheentry->inh_fileid = const_cpu_to_le32(0); + cacheentry->inh_dirid = const_cpu_to_le32(0); + cacheentry->valid = 1; + pcache->head.p_writes++; + } + } else + cacheentry = (struct CACHED_PERMISSIONS*)NULL; + } + } else { + cacheentry = (struct CACHED_PERMISSIONS*)NULL; #if CACHE_LEGACY_SIZE - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - struct CACHED_PERMISSIONS_LEGACY wanted; - struct CACHED_PERMISSIONS_LEGACY *legacy; + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { + struct CACHED_PERMISSIONS_LEGACY wanted; + struct CACHED_PERMISSIONS_LEGACY *legacy; - wanted.perm.uid = uid; - wanted.perm.gid = gid; + wanted.perm.uid = uid; + wanted.perm.gid = gid; #if POSIXACLS - wanted.perm.mode = pxdesc->mode & 07777; - wanted.perm.inh_fileid = const_cpu_to_le32(0); - wanted.perm.inh_dirid = const_cpu_to_le32(0); - wanted.mft_no = ni->mft_no; - wanted.variable = (void*)pxdesc; - wanted.varsize = sizeof(struct POSIX_SECURITY) - + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); + wanted.perm.mode = pxdesc->mode & 07777; + wanted.perm.inh_fileid = const_cpu_to_le32(0); + wanted.perm.inh_dirid = const_cpu_to_le32(0); + wanted.mft_no = ni->mft_no; + wanted.variable = (void*)pxdesc; + wanted.varsize = sizeof(struct POSIX_SECURITY) + + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); #else - wanted.perm.mode = mode & 07777; - wanted.perm.inh_fileid = const_cpu_to_le32(0); - wanted.perm.inh_dirid = const_cpu_to_le32(0); - wanted.mft_no = ni->mft_no; - wanted.variable = (void*)NULL; - wanted.varsize = 0; + wanted.perm.mode = mode & 07777; + wanted.perm.inh_fileid = const_cpu_to_le32(0); + wanted.perm.inh_dirid = const_cpu_to_le32(0); + wanted.mft_no = ni->mft_no; + wanted.variable = (void*)NULL; + wanted.varsize = 0; #endif - legacy = (struct CACHED_PERMISSIONS_LEGACY*)ntfs_enter_cache( - scx->vol->legacy_cache, GENERIC(&wanted), - (cache_compare)leg_compare); - if (legacy) { - cacheentry = &legacy->perm; + legacy = (struct CACHED_PERMISSIONS_LEGACY*)ntfs_enter_cache( + scx->vol->legacy_cache, GENERIC(&wanted), + (cache_compare)leg_compare); + if (legacy) { + cacheentry = &legacy->perm; #if POSIXACLS - /* - * give direct access to the cached pxdesc - * in the permissions structure - */ - cacheentry->pxdesc = legacy->variable; + /* + * give direct access to the cached pxdesc + * in the permissions structure + */ + cacheentry->pxdesc = legacy->variable; #endif - } - } + } + } #endif - } - return (cacheentry); + } + return (cacheentry); } /* @@ -1635,122 +1655,124 @@ static struct CACHED_PERMISSIONS *enter_cache(struct SECURITY_CONTEXT *scx, */ static struct CACHED_PERMISSIONS *fetch_cache(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni) { - struct CACHED_PERMISSIONS *cacheentry; - struct PERMISSIONS_CACHE *pcache; - u32 securindex; - unsigned int index1; - unsigned int index2; + ntfs_inode *ni) +{ + struct CACHED_PERMISSIONS *cacheentry; + struct PERMISSIONS_CACHE *pcache; + u32 securindex; + unsigned int index1; + unsigned int index2; - /* cacheing is only possible if a security_id has been defined */ - cacheentry = (struct CACHED_PERMISSIONS*)NULL; - if (test_nino_flag(ni, v3_Extensions) - && (ni->security_id)) { - securindex = le32_to_cpu(ni->security_id); - index1 = securindex >> CACHE_PERMISSIONS_BITS; - index2 = securindex & ((1 << CACHE_PERMISSIONS_BITS) - 1); - pcache = *scx->pseccache; - if (pcache - && (pcache->head.last >= index1) - && pcache->cachetable[index1]) { - cacheentry = &pcache->cachetable[index1][index2]; - /* reject if entry is not valid */ - if (!cacheentry->valid) - cacheentry = (struct CACHED_PERMISSIONS*)NULL; - else - pcache->head.p_hits++; - if (pcache) - pcache->head.p_reads++; - } - } + /* cacheing is only possible if a security_id has been defined */ + cacheentry = (struct CACHED_PERMISSIONS*)NULL; + if (test_nino_flag(ni, v3_Extensions) + && (ni->security_id)) { + securindex = le32_to_cpu(ni->security_id); + index1 = securindex >> CACHE_PERMISSIONS_BITS; + index2 = securindex & ((1 << CACHE_PERMISSIONS_BITS) - 1); + pcache = *scx->pseccache; + if (pcache + && (pcache->head.last >= index1) + && pcache->cachetable[index1]) { + cacheentry = &pcache->cachetable[index1][index2]; + /* reject if entry is not valid */ + if (!cacheentry->valid) + cacheentry = (struct CACHED_PERMISSIONS*)NULL; + else + pcache->head.p_hits++; + if (pcache) + pcache->head.p_reads++; + } + } #if CACHE_LEGACY_SIZE - else { - cacheentry = (struct CACHED_PERMISSIONS*)NULL; - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - struct CACHED_PERMISSIONS_LEGACY wanted; - struct CACHED_PERMISSIONS_LEGACY *legacy; + else { + cacheentry = (struct CACHED_PERMISSIONS*)NULL; + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { + struct CACHED_PERMISSIONS_LEGACY wanted; + struct CACHED_PERMISSIONS_LEGACY *legacy; - wanted.mft_no = ni->mft_no; - wanted.variable = (void*)NULL; - wanted.varsize = 0; - legacy = (struct CACHED_PERMISSIONS_LEGACY*)ntfs_fetch_cache( - scx->vol->legacy_cache, GENERIC(&wanted), - (cache_compare)leg_compare); - if (legacy) cacheentry = &legacy->perm; - } - } + wanted.mft_no = ni->mft_no; + wanted.variable = (void*)NULL; + wanted.varsize = 0; + legacy = (struct CACHED_PERMISSIONS_LEGACY*)ntfs_fetch_cache( + scx->vol->legacy_cache, GENERIC(&wanted), + (cache_compare)leg_compare); + if (legacy) cacheentry = &legacy->perm; + } + } #endif #if POSIXACLS - if (cacheentry && !cacheentry->pxdesc) { - ntfs_log_error("No Posix descriptor in cache\n"); - cacheentry = (struct CACHED_PERMISSIONS*)NULL; - } + if (cacheentry && !cacheentry->pxdesc) { + ntfs_log_error("No Posix descriptor in cache\n"); + cacheentry = (struct CACHED_PERMISSIONS*)NULL; + } #endif - return (cacheentry); + return (cacheentry); } /* * Retrieve a security attribute from $Secure */ -static char *retrievesecurityattr(ntfs_volume *vol, SII_INDEX_KEY id) { - struct SII *psii; - union { - struct { - le32 dataoffsl; - le32 dataoffsh; - } parts; - le64 all; - } realign; - int found; - size_t size; - size_t rdsize; - s64 offs; - ntfs_inode *ni; - ntfs_index_context *xsii; - char *securattr; +static char *retrievesecurityattr(ntfs_volume *vol, SII_INDEX_KEY id) +{ + struct SII *psii; + union { + struct { + le32 dataoffsl; + le32 dataoffsh; + } parts; + le64 all; + } realign; + int found; + size_t size; + size_t rdsize; + s64 offs; + ntfs_inode *ni; + ntfs_index_context *xsii; + char *securattr; - securattr = (char*)NULL; - ni = vol->secure_ni; - xsii = vol->secure_xsii; - if (ni && xsii) { - ntfs_index_ctx_reinit(xsii); - found = - !ntfs_index_lookup((char*)&id, - sizeof(SII_INDEX_KEY), xsii); - if (found) { - psii = (struct SII*)xsii->entry; - size = - (size_t) le32_to_cpu(psii->datasize) - - sizeof(SECURITY_DESCRIPTOR_HEADER); - /* work around bad alignment problem */ - realign.parts.dataoffsh = psii->dataoffsh; - realign.parts.dataoffsl = psii->dataoffsl; - offs = le64_to_cpu(realign.all) - + sizeof(SECURITY_DESCRIPTOR_HEADER); + securattr = (char*)NULL; + ni = vol->secure_ni; + xsii = vol->secure_xsii; + if (ni && xsii) { + ntfs_index_ctx_reinit(xsii); + found = + !ntfs_index_lookup((char*)&id, + sizeof(SII_INDEX_KEY), xsii); + if (found) { + psii = (struct SII*)xsii->entry; + size = + (size_t) le32_to_cpu(psii->datasize) + - sizeof(SECURITY_DESCRIPTOR_HEADER); + /* work around bad alignment problem */ + realign.parts.dataoffsh = psii->dataoffsh; + realign.parts.dataoffsl = psii->dataoffsl; + offs = le64_to_cpu(realign.all) + + sizeof(SECURITY_DESCRIPTOR_HEADER); - securattr = (char*)ntfs_malloc(size); - if (securattr) { - rdsize = ntfs_local_read( - ni, STREAM_SDS, 4, - securattr, size, offs); - if ((rdsize != size) - || !ntfs_valid_descr(securattr, - rdsize)) { - /* error to be logged by caller */ - free(securattr); - securattr = (char*)NULL; - } - } - } else - if (errno != ENOENT) - ntfs_log_perror("Inconsistency in index $SII"); - } - if (!securattr) { - ntfs_log_error("Failed to retrieve a security descriptor\n"); - errno = EIO; - } - return (securattr); + securattr = (char*)ntfs_malloc(size); + if (securattr) { + rdsize = ntfs_local_read( + ni, STREAM_SDS, 4, + securattr, size, offs); + if ((rdsize != size) + || !ntfs_valid_descr(securattr, + rdsize)) { + /* error to be logged by caller */ + free(securattr); + securattr = (char*)NULL; + } + } + } else + if (errno != ENOENT) + ntfs_log_perror("Inconsistency in index $SII"); + } + if (!securattr) { + ntfs_log_error("Failed to retrieve a security descriptor\n"); + errno = EIO; + } + return (securattr); } /* @@ -1767,50 +1789,51 @@ static char *retrievesecurityattr(ntfs_volume *vol, SII_INDEX_KEY id) { */ static char *getsecurityattr(ntfs_volume *vol, - const char *path, ntfs_inode *ni) { - SII_INDEX_KEY securid; - char *securattr; - s64 readallsz; + const char *path, ntfs_inode *ni) +{ + SII_INDEX_KEY securid; + char *securattr; + s64 readallsz; - /* - * Warning : in some situations, after fixing by chkdsk, - * v3_Extensions are marked present (long standard informations) - * with a default security descriptor inserted in an - * attribute - */ - if (test_nino_flag(ni, v3_Extensions) - && vol->secure_ni && ni->security_id) { - /* get v3.x descriptor in $Secure */ - securid.security_id = ni->security_id; - securattr = retrievesecurityattr(vol,securid); - if (!securattr) - ntfs_log_error("Bad security descriptor for 0x%lx\n", - (long)le32_to_cpu(ni->security_id)); - } else { - /* get v1.x security attribute */ - readallsz = 0; - securattr = ntfs_attr_readall(ni, AT_SECURITY_DESCRIPTOR, - AT_UNNAMED, 0, &readallsz); - if (securattr && !ntfs_valid_descr(securattr, readallsz)) { - ntfs_log_error("Bad security descriptor for %s\n", - path); - free(securattr); - securattr = (char*)NULL; - } - } - if (!securattr) { - /* - * in some situations, there is no security - * descriptor, and chkdsk does not detect or fix - * anything. This could be a normal situation. - * When this happens, simulate a descriptor with - * minimum rights, so that a real descriptor can - * be created by chown or chmod - */ - ntfs_log_error("No security descriptor found for %s\n",path); - securattr = ntfs_build_descr(0, 0, adminsid, adminsid); - } - return (securattr); + /* + * Warning : in some situations, after fixing by chkdsk, + * v3_Extensions are marked present (long standard informations) + * with a default security descriptor inserted in an + * attribute + */ + if (test_nino_flag(ni, v3_Extensions) + && vol->secure_ni && ni->security_id) { + /* get v3.x descriptor in $Secure */ + securid.security_id = ni->security_id; + securattr = retrievesecurityattr(vol,securid); + if (!securattr) + ntfs_log_error("Bad security descriptor for 0x%lx\n", + (long)le32_to_cpu(ni->security_id)); + } else { + /* get v1.x security attribute */ + readallsz = 0; + securattr = ntfs_attr_readall(ni, AT_SECURITY_DESCRIPTOR, + AT_UNNAMED, 0, &readallsz); + if (securattr && !ntfs_valid_descr(securattr, readallsz)) { + ntfs_log_error("Bad security descriptor for %s\n", + path); + free(securattr); + securattr = (char*)NULL; + } + } + if (!securattr) { + /* + * in some situations, there is no security + * descriptor, and chkdsk does not detect or fix + * anything. This could be a normal situation. + * When this happens, simulate a descriptor with + * minimum rights, so that a real descriptor can + * be created by chown or chmod + */ + ntfs_log_error("No security descriptor found for %s\n",path); + securattr = ntfs_build_descr(0, 0, adminsid, adminsid); + } + return (securattr); } #if POSIXACLS @@ -1823,98 +1846,99 @@ static char *getsecurityattr(ntfs_volume *vol, */ static int access_check_posix(struct SECURITY_CONTEXT *scx, - struct POSIX_SECURITY *pxdesc, mode_t request, - uid_t uid, gid_t gid) { - struct POSIX_ACE *pxace; - int userperms; - int groupperms; - int mask; - BOOL somegroup; - mode_t perms; - int i; + struct POSIX_SECURITY *pxdesc, mode_t request, + uid_t uid, gid_t gid) +{ + struct POSIX_ACE *pxace; + int userperms; + int groupperms; + int mask; + BOOL somegroup; + mode_t perms; + int i; - perms = pxdesc->mode; - /* owner and root access */ - if (!scx->uid || (uid == scx->uid)) { - if (!scx->uid) { - /* root access if owner or other execution */ - if (perms & 0101) - perms = 07777; - else { - /* root access if some group execution */ - groupperms = 0; - mask = 7; - for (i=pxdesc->acccnt-1; i>=0 ; i--) { - pxace = &pxdesc->acl.ace[i]; - switch (pxace->tag) { - case POSIX_ACL_USER_OBJ : - case POSIX_ACL_GROUP_OBJ : - case POSIX_ACL_GROUP : - groupperms |= pxace->perms; - break; - case POSIX_ACL_MASK : - mask = pxace->perms & 7; - break; - default : - break; - } - } - perms = (groupperms & mask & 1) | 6; - } - } else - perms &= 07700; - } else { - /* analyze designated users and get mask */ - userperms = -1; - groupperms = -1; - mask = 7; - for (i=pxdesc->acccnt-1; i>=0 ; i--) { - pxace = &pxdesc->acl.ace[i]; - switch (pxace->tag) { - case POSIX_ACL_USER : - if ((uid_t)pxace->id == scx->uid) - userperms = pxace->perms; - break; - case POSIX_ACL_MASK : - mask = pxace->perms & 7; - break; - default : - break; - } - } - /* designated users */ - if (userperms >= 0) - perms = (perms & 07000) + (userperms & mask); - else { - /* owning group */ - if (!(~(perms >> 3) & request & mask) - && ((gid == scx->gid) - || groupmember(scx, scx->uid, gid))) - perms &= 07070; - else { - /* other groups */ - groupperms = -1; - somegroup = FALSE; - for (i=pxdesc->acccnt-1; i>=0 ; i--) { - pxace = &pxdesc->acl.ace[i]; - if ((pxace->tag == POSIX_ACL_GROUP) - && groupmember(scx, uid, pxace->id)) { - if (!(~pxace->perms & request & mask)) - groupperms = pxace->perms; - somegroup = TRUE; - } - } - if (groupperms >= 0) - perms = (perms & 07000) + (groupperms & mask); - else - if (somegroup) - perms = 0; - else - perms &= 07007; - } - } - } - return (perms); + perms = pxdesc->mode; + /* owner and root access */ + if (!scx->uid || (uid == scx->uid)) { + if (!scx->uid) { + /* root access if owner or other execution */ + if (perms & 0101) + perms = 07777; + else { + /* root access if some group execution */ + groupperms = 0; + mask = 7; + for (i=pxdesc->acccnt-1; i>=0 ; i--) { + pxace = &pxdesc->acl.ace[i]; + switch (pxace->tag) { + case POSIX_ACL_USER_OBJ : + case POSIX_ACL_GROUP_OBJ : + case POSIX_ACL_GROUP : + groupperms |= pxace->perms; + break; + case POSIX_ACL_MASK : + mask = pxace->perms & 7; + break; + default : + break; + } + } + perms = (groupperms & mask & 1) | 6; + } + } else + perms &= 07700; + } else { + /* analyze designated users and get mask */ + userperms = -1; + groupperms = -1; + mask = 7; + for (i=pxdesc->acccnt-1; i>=0 ; i--) { + pxace = &pxdesc->acl.ace[i]; + switch (pxace->tag) { + case POSIX_ACL_USER : + if ((uid_t)pxace->id == scx->uid) + userperms = pxace->perms; + break; + case POSIX_ACL_MASK : + mask = pxace->perms & 7; + break; + default : + break; + } + } + /* designated users */ + if (userperms >= 0) + perms = (perms & 07000) + (userperms & mask); + else { + /* owning group */ + if (!(~(perms >> 3) & request & mask) + && ((gid == scx->gid) + || groupmember(scx, scx->uid, gid))) + perms &= 07070; + else { + /* other groups */ + groupperms = -1; + somegroup = FALSE; + for (i=pxdesc->acccnt-1; i>=0 ; i--) { + pxace = &pxdesc->acl.ace[i]; + if ((pxace->tag == POSIX_ACL_GROUP) + && groupmember(scx, uid, pxace->id)) { + if (!(~pxace->perms & request & mask)) + groupperms = pxace->perms; + somegroup = TRUE; + } + } + if (groupperms >= 0) + perms = (perms & 07000) + (groupperms & mask); + else + if (somegroup) + perms = 0; + else + perms &= 07007; + } + } + } + return (perms); } /* @@ -1927,95 +1951,96 @@ static int access_check_posix(struct SECURITY_CONTEXT *scx, */ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode * ni, mode_t request) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const struct CACHED_PERMISSIONS *cached; - char *securattr; - const SID *usid; /* owner of file/directory */ - const SID *gsid; /* group of file/directory */ - uid_t uid; - gid_t gid; - int perm; - BOOL isdir; - struct POSIX_SECURITY *pxdesc; + const char *path, ntfs_inode * ni, mode_t request) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const struct CACHED_PERMISSIONS *cached; + char *securattr; + const SID *usid; /* owner of file/directory */ + const SID *gsid; /* group of file/directory */ + uid_t uid; + gid_t gid; + int perm; + BOOL isdir; + struct POSIX_SECURITY *pxdesc; - if (!scx->mapping[MAPUSERS]) - perm = 07777; - else { - /* check whether available in cache */ - cached = fetch_cache(scx,ni); - if (cached) { - uid = cached->uid; - gid = cached->gid; - perm = access_check_posix(scx,cached->pxdesc,request,uid,gid); - } else { - perm = 0; /* default to no permission */ - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - != const_cpu_to_le16(0); - securattr = getsecurityattr(scx->vol, path, ni); - if (securattr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*) - securattr; - gsid = (const SID*)& - securattr[le32_to_cpu(phead->group)]; - gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + if (!scx->mapping[MAPUSERS]) + perm = 07777; + else { + /* check whether available in cache */ + cached = fetch_cache(scx,ni); + if (cached) { + uid = cached->uid; + gid = cached->gid; + perm = access_check_posix(scx,cached->pxdesc,request,uid,gid); + } else { + perm = 0; /* default to no permission */ + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + != const_cpu_to_le16(0); + securattr = getsecurityattr(scx->vol, path, ni); + if (securattr) { + phead = (const SECURITY_DESCRIPTOR_RELATIVE*) + securattr; + gsid = (const SID*)& + securattr[le32_to_cpu(phead->group)]; + gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if OWNERFROMACL - usid = ntfs_acl_owner(securattr); - pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, - usid, gsid, isdir); - if (pxdesc) - perm = pxdesc->mode & 07777; - else - perm = -1; - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + usid = ntfs_acl_owner(securattr); + pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, + usid, gsid, isdir); + if (pxdesc) + perm = pxdesc->mode & 07777; + else + perm = -1; + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else - usid = (const SID*)& - securattr[le32_to_cpu(phead->owner)]; - pxdesc = ntfs_build_permissions_posix(scx,securattr, - usid, gsid, isdir); - if (pxdesc) - perm = pxdesc->mode & 07777; - else - perm = -1; - if (!perm && ntfs_same_sid(usid, adminsid)) { - uid = find_tenant(scx, securattr); - if (uid) - perm = 0700; - } else - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + usid = (const SID*)& + securattr[le32_to_cpu(phead->owner)]; + pxdesc = ntfs_build_permissions_posix(scx,securattr, + usid, gsid, isdir); + if (pxdesc) + perm = pxdesc->mode & 07777; + else + perm = -1; + if (!perm && ntfs_same_sid(usid, adminsid)) { + uid = find_tenant(scx, securattr); + if (uid) + perm = 0700; + } else + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif - /* - * Create a security id if there were none - * and upgrade option is selected - */ - if (!test_nino_flag(ni, v3_Extensions) - && (perm >= 0) - && (scx->vol->secure_flags - & (1 << SECURITY_ADDSECURIDS))) { - upgrade_secur_desc(scx->vol, path, - securattr, ni); - /* - * fetch owner and group for cacheing - * if there is a securid - */ - } - if (test_nino_flag(ni, v3_Extensions) - && (perm >= 0)) { - enter_cache(scx, ni, uid, - gid, pxdesc); - } - if (pxdesc) { - perm = access_check_posix(scx,pxdesc,request,uid,gid); - free(pxdesc); - } - free(securattr); - } else { - perm = -1; - uid = gid = 0; - } - } - } - return (perm); + /* + * Create a security id if there were none + * and upgrade option is selected + */ + if (!test_nino_flag(ni, v3_Extensions) + && (perm >= 0) + && (scx->vol->secure_flags + & (1 << SECURITY_ADDSECURIDS))) { + upgrade_secur_desc(scx->vol, path, + securattr, ni); + /* + * fetch owner and group for cacheing + * if there is a securid + */ + } + if (test_nino_flag(ni, v3_Extensions) + && (perm >= 0)) { + enter_cache(scx, ni, uid, + gid, pxdesc); + } + if (pxdesc) { + perm = access_check_posix(scx,pxdesc,request,uid,gid); + free(pxdesc); + } + free(securattr); + } else { + perm = -1; + uid = gid = 0; + } + } + } + return (perm); } /* @@ -2027,127 +2052,128 @@ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, */ int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, char *value, size_t size, - ntfs_inode *ni) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - struct POSIX_SECURITY *pxdesc; - const struct CACHED_PERMISSIONS *cached; - char *securattr; - const SID *usid; /* owner of file/directory */ - const SID *gsid; /* group of file/directory */ - uid_t uid; - gid_t gid; - int perm; - BOOL isdir; - size_t outsize; + const char *name, char *value, size_t size, + ntfs_inode *ni) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + struct POSIX_SECURITY *pxdesc; + const struct CACHED_PERMISSIONS *cached; + char *securattr; + const SID *usid; /* owner of file/directory */ + const SID *gsid; /* group of file/directory */ + uid_t uid; + gid_t gid; + int perm; + BOOL isdir; + size_t outsize; - outsize = 0; /* default to error */ - if (!scx->mapping[MAPUSERS]) - errno = ENOTSUP; - else { - /* check whether available in cache */ - cached = fetch_cache(scx,ni); - if (cached) - pxdesc = cached->pxdesc; - else { - securattr = getsecurityattr(scx->vol, path, ni); - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - != const_cpu_to_le16(0); - if (securattr) { - phead = - (const SECURITY_DESCRIPTOR_RELATIVE*) - securattr; - gsid = (const SID*)& - securattr[le32_to_cpu(phead->group)]; + outsize = 0; /* default to error */ + if (!scx->mapping[MAPUSERS]) + errno = ENOTSUP; + else { + /* check whether available in cache */ + cached = fetch_cache(scx,ni); + if (cached) + pxdesc = cached->pxdesc; + else { + securattr = getsecurityattr(scx->vol, path, ni); + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + != const_cpu_to_le16(0); + if (securattr) { + phead = + (const SECURITY_DESCRIPTOR_RELATIVE*) + securattr; + gsid = (const SID*)& + securattr[le32_to_cpu(phead->group)]; #if OWNERFROMACL - usid = ntfs_acl_owner(securattr); + usid = ntfs_acl_owner(securattr); #else - usid = (const SID*)& - securattr[le32_to_cpu(phead->owner)]; + usid = (const SID*)& + securattr[le32_to_cpu(phead->owner)]; #endif - pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, - usid, gsid, isdir); + pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, + usid, gsid, isdir); - /* - * fetch owner and group for cacheing - */ - if (pxdesc) { - perm = pxdesc->mode & 07777; - /* - * Create a security id if there were none - * and upgrade option is selected - */ - if (!test_nino_flag(ni, v3_Extensions) - && (scx->vol->secure_flags - & (1 << SECURITY_ADDSECURIDS))) { - upgrade_secur_desc(scx->vol, - path, securattr, ni); - } + /* + * fetch owner and group for cacheing + */ + if (pxdesc) { + perm = pxdesc->mode & 07777; + /* + * Create a security id if there were none + * and upgrade option is selected + */ + if (!test_nino_flag(ni, v3_Extensions) + && (scx->vol->secure_flags + & (1 << SECURITY_ADDSECURIDS))) { + upgrade_secur_desc(scx->vol, + path, securattr, ni); + } #if OWNERFROMACL - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else - if (!perm && ntfs_same_sid(usid, adminsid)) { - uid = find_tenant(scx, - securattr); - if (uid) - perm = 0700; - } else - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + if (!perm && ntfs_same_sid(usid, adminsid)) { + uid = find_tenant(scx, + securattr); + if (uid) + perm = 0700; + } else + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif - gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); - if (pxdesc->tagsset & POSIX_ACL_EXTENSIONS) - enter_cache(scx, ni, uid, - gid, pxdesc); - } - free(securattr); - } else - pxdesc = (struct POSIX_SECURITY*)NULL; - } + gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + if (pxdesc->tagsset & POSIX_ACL_EXTENSIONS) + enter_cache(scx, ni, uid, + gid, pxdesc); + } + free(securattr); + } else + pxdesc = (struct POSIX_SECURITY*)NULL; + } - if (pxdesc) { - if (ntfs_valid_posix(pxdesc)) { - if (!strcmp(name,"system.posix_acl_default")) { - if (ni->mrec->flags - & MFT_RECORD_IS_DIRECTORY) - outsize = sizeof(struct POSIX_ACL) - + pxdesc->defcnt*sizeof(struct POSIX_ACE); - else { - /* - * getting default ACL from plain file : - * return EACCES if size > 0 as - * indicated in the man, but return ok - * if size == 0, so that ls does not - * display an error - */ - if (size > 0) { - outsize = 0; - errno = EACCES; - } else - outsize = sizeof(struct POSIX_ACL); - } - if (outsize && (outsize <= size)) { - memcpy(value,&pxdesc->acl,sizeof(struct POSIX_ACL)); - memcpy(&value[sizeof(struct POSIX_ACL)], - &pxdesc->acl.ace[pxdesc->firstdef], - outsize-sizeof(struct POSIX_ACL)); - } - } else { - outsize = sizeof(struct POSIX_ACL) - + pxdesc->acccnt*sizeof(struct POSIX_ACE); - if (outsize <= size) - memcpy(value,&pxdesc->acl,outsize); - } - } else { - outsize = 0; - errno = EIO; - ntfs_log_error("Invalid Posix ACL built\n"); - } - if (!cached) - free(pxdesc); - } else - outsize = 0; - } - return (outsize ? (int)outsize : -errno); + if (pxdesc) { + if (ntfs_valid_posix(pxdesc)) { + if (!strcmp(name,"system.posix_acl_default")) { + if (ni->mrec->flags + & MFT_RECORD_IS_DIRECTORY) + outsize = sizeof(struct POSIX_ACL) + + pxdesc->defcnt*sizeof(struct POSIX_ACE); + else { + /* + * getting default ACL from plain file : + * return EACCES if size > 0 as + * indicated in the man, but return ok + * if size == 0, so that ls does not + * display an error + */ + if (size > 0) { + outsize = 0; + errno = EACCES; + } else + outsize = sizeof(struct POSIX_ACL); + } + if (outsize && (outsize <= size)) { + memcpy(value,&pxdesc->acl,sizeof(struct POSIX_ACL)); + memcpy(&value[sizeof(struct POSIX_ACL)], + &pxdesc->acl.ace[pxdesc->firstdef], + outsize-sizeof(struct POSIX_ACL)); + } + } else { + outsize = sizeof(struct POSIX_ACL) + + pxdesc->acccnt*sizeof(struct POSIX_ACE); + if (outsize <= size) + memcpy(value,&pxdesc->acl,outsize); + } + } else { + outsize = 0; + errno = EIO; + ntfs_log_error("Invalid Posix ACL built\n"); + } + if (!cached) + free(pxdesc); + } else + outsize = 0; + } + return (outsize ? (int)outsize : -errno); } #else /* POSIXACLS */ @@ -2164,93 +2190,94 @@ int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, */ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni, - mode_t request __attribute__((unused))) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const struct CACHED_PERMISSIONS *cached; - char *securattr; - const SID *usid; /* owner of file/directory */ - const SID *gsid; /* group of file/directory */ - BOOL isdir; - uid_t uid; - gid_t gid; - int perm; + const char *path, ntfs_inode *ni, + mode_t request __attribute__((unused))) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const struct CACHED_PERMISSIONS *cached; + char *securattr; + const SID *usid; /* owner of file/directory */ + const SID *gsid; /* group of file/directory */ + BOOL isdir; + uid_t uid; + gid_t gid; + int perm; - if (!scx->mapping[MAPUSERS] || !scx->uid) - perm = 07777; - else { - /* check whether available in cache */ - cached = fetch_cache(scx,ni); - if (cached) { - perm = cached->mode; - uid = cached->uid; - gid = cached->gid; - } else { - perm = 0; /* default to no permission */ - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - != const_cpu_to_le16(0); - securattr = getsecurityattr(scx->vol, path, ni); - if (securattr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*) - securattr; - gsid = (const SID*)& - securattr[le32_to_cpu(phead->group)]; - gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + if (!scx->mapping[MAPUSERS] || !scx->uid) + perm = 07777; + else { + /* check whether available in cache */ + cached = fetch_cache(scx,ni); + if (cached) { + perm = cached->mode; + uid = cached->uid; + gid = cached->gid; + } else { + perm = 0; /* default to no permission */ + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + != const_cpu_to_le16(0); + securattr = getsecurityattr(scx->vol, path, ni); + if (securattr) { + phead = (const SECURITY_DESCRIPTOR_RELATIVE*) + securattr; + gsid = (const SID*)& + securattr[le32_to_cpu(phead->group)]; + gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if OWNERFROMACL - usid = ntfs_acl_owner(securattr); - perm = ntfs_build_permissions(securattr, - usid, gsid, isdir); - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + usid = ntfs_acl_owner(securattr); + perm = ntfs_build_permissions(securattr, + usid, gsid, isdir); + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else - usid = (const SID*)& - securattr[le32_to_cpu(phead->owner)]; - perm = ntfs_build_permissions(securattr, - usid, gsid, isdir); - if (!perm && ntfs_same_sid(usid, adminsid)) { - uid = find_tenant(scx, securattr); - if (uid) - perm = 0700; - } else - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + usid = (const SID*)& + securattr[le32_to_cpu(phead->owner)]; + perm = ntfs_build_permissions(securattr, + usid, gsid, isdir); + if (!perm && ntfs_same_sid(usid, adminsid)) { + uid = find_tenant(scx, securattr); + if (uid) + perm = 0700; + } else + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif - /* - * Create a security id if there were none - * and upgrade option is selected - */ - if (!test_nino_flag(ni, v3_Extensions) - && (perm >= 0) - && (scx->vol->secure_flags - & (1 << SECURITY_ADDSECURIDS))) { - upgrade_secur_desc(scx->vol, path, - securattr, ni); - /* - * fetch owner and group for cacheing - * if there is a securid - */ - } - if (test_nino_flag(ni, v3_Extensions) - && (perm >= 0)) { - enter_cache(scx, ni, uid, - gid, perm); - } - free(securattr); - } else { - perm = -1; - uid = gid = 0; - } - } - if (perm >= 0) { - if (uid == scx->uid) - perm &= 07700; - else - if ((gid == scx->gid) - || groupmember(scx, scx->uid, gid)) - perm &= 07070; - else - perm &= 07007; - } - } - return (perm); + /* + * Create a security id if there were none + * and upgrade option is selected + */ + if (!test_nino_flag(ni, v3_Extensions) + && (perm >= 0) + && (scx->vol->secure_flags + & (1 << SECURITY_ADDSECURIDS))) { + upgrade_secur_desc(scx->vol, path, + securattr, ni); + /* + * fetch owner and group for cacheing + * if there is a securid + */ + } + if (test_nino_flag(ni, v3_Extensions) + && (perm >= 0)) { + enter_cache(scx, ni, uid, + gid, perm); + } + free(securattr); + } else { + perm = -1; + uid = gid = 0; + } + } + if (perm >= 0) { + if (uid == scx->uid) + perm &= 07700; + else + if ((gid == scx->gid) + || groupmember(scx, scx->uid, gid)) + perm &= 07070; + else + perm &= 07007; + } + } + return (perm); } #endif /* POSIXACLS */ @@ -2264,21 +2291,22 @@ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, */ int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name __attribute__((unused)), - char *value, size_t size, ntfs_inode *ni) { - char *securattr; - size_t outsize; + const char *name __attribute__((unused)), + char *value, size_t size, ntfs_inode *ni) +{ + char *securattr; + size_t outsize; - outsize = 0; /* default to no data and no error */ - securattr = getsecurityattr(scx->vol, path, ni); - if (securattr) { - outsize = ntfs_attr_size(securattr); - if (outsize <= size) { - memcpy(value,securattr,outsize); - } - free(securattr); - } - return (outsize ? (int)outsize : -errno); + outsize = 0; /* default to no data and no error */ + securattr = getsecurityattr(scx->vol, path, ni); + if (securattr) { + outsize = ntfs_attr_size(securattr); + if (outsize <= size) { + memcpy(value,securattr,outsize); + } + free(securattr); + } + return (outsize ? (int)outsize : -errno); } /* @@ -2287,100 +2315,101 @@ int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, const char *path, */ int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode * ni, - struct stat *stbuf) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - char *securattr; - const SID *usid; /* owner of file/directory */ - const SID *gsid; /* group of file/directory */ - const struct CACHED_PERMISSIONS *cached; - int perm; - BOOL isdir; + const char *path, ntfs_inode * ni, + struct stat *stbuf) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + char *securattr; + const SID *usid; /* owner of file/directory */ + const SID *gsid; /* group of file/directory */ + const struct CACHED_PERMISSIONS *cached; + int perm; + BOOL isdir; #if POSIXACLS - struct POSIX_SECURITY *pxdesc; + struct POSIX_SECURITY *pxdesc; #endif - if (!scx->mapping[MAPUSERS]) - perm = 07777; - else { - /* check whether available in cache */ - cached = fetch_cache(scx,ni); - if (cached) { - perm = cached->mode; - stbuf->st_uid = cached->uid; - stbuf->st_gid = cached->gid; - stbuf->st_mode = (stbuf->st_mode & ~07777) + perm; - } else { - perm = -1; /* default to error */ - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - != const_cpu_to_le16(0); - securattr = getsecurityattr(scx->vol, path, ni); - if (securattr) { - phead = - (const SECURITY_DESCRIPTOR_RELATIVE*) - securattr; - gsid = (const SID*)& - securattr[le32_to_cpu(phead->group)]; + if (!scx->mapping[MAPUSERS]) + perm = 07777; + else { + /* check whether available in cache */ + cached = fetch_cache(scx,ni); + if (cached) { + perm = cached->mode; + stbuf->st_uid = cached->uid; + stbuf->st_gid = cached->gid; + stbuf->st_mode = (stbuf->st_mode & ~07777) + perm; + } else { + perm = -1; /* default to error */ + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + != const_cpu_to_le16(0); + securattr = getsecurityattr(scx->vol, path, ni); + if (securattr) { + phead = + (const SECURITY_DESCRIPTOR_RELATIVE*) + securattr; + gsid = (const SID*)& + securattr[le32_to_cpu(phead->group)]; #if OWNERFROMACL - usid = ntfs_acl_owner(securattr); + usid = ntfs_acl_owner(securattr); #else - usid = (const SID*)& - securattr[le32_to_cpu(phead->owner)]; + usid = (const SID*)& + securattr[le32_to_cpu(phead->owner)]; #endif #if POSIXACLS - pxdesc = ntfs_build_permissions_posix(scx->mapping, securattr, - usid, gsid, isdir); - if (pxdesc) - perm = pxdesc->mode & 07777; - else - perm = -1; + pxdesc = ntfs_build_permissions_posix(scx->mapping, securattr, + usid, gsid, isdir); + if (pxdesc) + perm = pxdesc->mode & 07777; + else + perm = -1; #else - perm = ntfs_build_permissions(securattr, - usid, gsid, isdir); + perm = ntfs_build_permissions(securattr, + usid, gsid, isdir); #endif - /* - * fetch owner and group for cacheing - */ - if (perm >= 0) { - /* - * Create a security id if there were none - * and upgrade option is selected - */ - if (!test_nino_flag(ni, v3_Extensions) - && (scx->vol->secure_flags - & (1 << SECURITY_ADDSECURIDS))) { - upgrade_secur_desc(scx->vol, - path, securattr, ni); - } + /* + * fetch owner and group for cacheing + */ + if (perm >= 0) { + /* + * Create a security id if there were none + * and upgrade option is selected + */ + if (!test_nino_flag(ni, v3_Extensions) + && (scx->vol->secure_flags + & (1 << SECURITY_ADDSECURIDS))) { + upgrade_secur_desc(scx->vol, + path, securattr, ni); + } #if OWNERFROMACL - stbuf->st_uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + stbuf->st_uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else - if (!perm && ntfs_same_sid(usid, adminsid)) { - stbuf->st_uid = - find_tenant(scx, - securattr); - if (stbuf->st_uid) - perm = 0700; - } else - stbuf->st_uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + if (!perm && ntfs_same_sid(usid, adminsid)) { + stbuf->st_uid = + find_tenant(scx, + securattr); + if (stbuf->st_uid) + perm = 0700; + } else + stbuf->st_uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif - stbuf->st_gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); - stbuf->st_mode = - (stbuf->st_mode & ~07777) + perm; + stbuf->st_gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + stbuf->st_mode = + (stbuf->st_mode & ~07777) + perm; #if POSIXACLS - enter_cache(scx, ni, stbuf->st_uid, - stbuf->st_gid, pxdesc); - free(pxdesc); + enter_cache(scx, ni, stbuf->st_uid, + stbuf->st_gid, pxdesc); + free(pxdesc); #else - enter_cache(scx, ni, stbuf->st_uid, - stbuf->st_gid, perm); + enter_cache(scx, ni, stbuf->st_uid, + stbuf->st_gid, perm); #endif - } - free(securattr); - } - } - } - return (perm); + } + free(securattr); + } + } + } + return (perm); } #if POSIXACLS @@ -2391,161 +2420,163 @@ int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, */ static struct POSIX_SECURITY *inherit_posix(struct SECURITY_CONTEXT *scx, - const char *dir_path, ntfs_inode *dir_ni, - mode_t mode, BOOL isdir) { - const struct CACHED_PERMISSIONS *cached; - const SECURITY_DESCRIPTOR_RELATIVE *phead; - struct POSIX_SECURITY *pxdesc; - struct POSIX_SECURITY *pydesc; - char *securattr; - const SID *usid; - const SID *gsid; - uid_t uid; - gid_t gid; + const char *dir_path, ntfs_inode *dir_ni, + mode_t mode, BOOL isdir) +{ + const struct CACHED_PERMISSIONS *cached; + const SECURITY_DESCRIPTOR_RELATIVE *phead; + struct POSIX_SECURITY *pxdesc; + struct POSIX_SECURITY *pydesc; + char *securattr; + const SID *usid; + const SID *gsid; + uid_t uid; + gid_t gid; - pydesc = (struct POSIX_SECURITY*)NULL; - /* check whether parent directory is available in cache */ - cached = fetch_cache(scx,dir_ni); - if (cached) { - uid = cached->uid; - gid = cached->gid; - pxdesc = cached->pxdesc; - if (pxdesc) { - pydesc = ntfs_build_inherited_posix(pxdesc,mode, - scx->umask,isdir); - } - } else { - securattr = getsecurityattr(scx->vol, dir_path, dir_ni); - if (securattr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*) - securattr; - gsid = (const SID*)& - securattr[le32_to_cpu(phead->group)]; - gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + pydesc = (struct POSIX_SECURITY*)NULL; + /* check whether parent directory is available in cache */ + cached = fetch_cache(scx,dir_ni); + if (cached) { + uid = cached->uid; + gid = cached->gid; + pxdesc = cached->pxdesc; + if (pxdesc) { + pydesc = ntfs_build_inherited_posix(pxdesc,mode, + scx->umask,isdir); + } + } else { + securattr = getsecurityattr(scx->vol, dir_path, dir_ni); + if (securattr) { + phead = (const SECURITY_DESCRIPTOR_RELATIVE*) + securattr; + gsid = (const SID*)& + securattr[le32_to_cpu(phead->group)]; + gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if OWNERFROMACL - usid = ntfs_acl_owner(securattr); - pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, - usid, gsid, TRUE); - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + usid = ntfs_acl_owner(securattr); + pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, + usid, gsid, TRUE); + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #else - usid = (const SID*)& - securattr[le32_to_cpu(phead->owner)]; - pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, - usid, gsid, TRUE); - if (pxdesc && ntfs_same_sid(usid, adminsid)) { - uid = find_tenant(scx, securattr); - } else - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + usid = (const SID*)& + securattr[le32_to_cpu(phead->owner)]; + pxdesc = ntfs_build_permissions_posix(scx->mapping,securattr, + usid, gsid, TRUE); + if (pxdesc && ntfs_same_sid(usid, adminsid)) { + uid = find_tenant(scx, securattr); + } else + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); #endif - if (pxdesc) { - /* - * Create a security id if there were none - * and upgrade option is selected - */ - if (!test_nino_flag(dir_ni, v3_Extensions) - && (scx->vol->secure_flags - & (1 << SECURITY_ADDSECURIDS))) { - upgrade_secur_desc(scx->vol, dir_path, - securattr, dir_ni); - /* - * fetch owner and group for cacheing - * if there is a securid - */ - } - if (test_nino_flag(dir_ni, v3_Extensions)) { - enter_cache(scx, dir_ni, uid, - gid, pxdesc); - } - pydesc = ntfs_build_inherited_posix(pxdesc, - mode, scx->umask, isdir); - free(pxdesc); - } - free(securattr); - } - } - return (pydesc); + if (pxdesc) { + /* + * Create a security id if there were none + * and upgrade option is selected + */ + if (!test_nino_flag(dir_ni, v3_Extensions) + && (scx->vol->secure_flags + & (1 << SECURITY_ADDSECURIDS))) { + upgrade_secur_desc(scx->vol, dir_path, + securattr, dir_ni); + /* + * fetch owner and group for cacheing + * if there is a securid + */ + } + if (test_nino_flag(dir_ni, v3_Extensions)) { + enter_cache(scx, dir_ni, uid, + gid, pxdesc); + } + pydesc = ntfs_build_inherited_posix(pxdesc, + mode, scx->umask, isdir); + free(pxdesc); + } + free(securattr); + } + } + return (pydesc); } /* * Allocate a security_id for a file being created - * + * * Returns zero if not possible (NTFS v3.x required) */ le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, const char *dir_path, - ntfs_inode *dir_ni, mode_t mode, BOOL isdir) { + uid_t uid, gid_t gid, const char *dir_path, + ntfs_inode *dir_ni, mode_t mode, BOOL isdir) +{ #if !FORCE_FORMAT_v1x - const struct CACHED_SECURID *cached; - struct CACHED_SECURID wanted; - struct POSIX_SECURITY *pxdesc; - char *newattr; - int newattrsz; - const SID *usid; - const SID *gsid; - BIGSID defusid; - BIGSID defgsid; - le32 securid; + const struct CACHED_SECURID *cached; + struct CACHED_SECURID wanted; + struct POSIX_SECURITY *pxdesc; + char *newattr; + int newattrsz; + const SID *usid; + const SID *gsid; + BIGSID defusid; + BIGSID defgsid; + le32 securid; #endif - securid = const_cpu_to_le32(0); + securid = const_cpu_to_le32(0); #if !FORCE_FORMAT_v1x - pxdesc = inherit_posix(scx, dir_path, dir_ni, mode, isdir); - if (pxdesc) { - /* check whether target securid is known in cache */ + pxdesc = inherit_posix(scx, dir_path, dir_ni, mode, isdir); + if (pxdesc) { + /* check whether target securid is known in cache */ - wanted.uid = uid; - wanted.gid = gid; - wanted.dmode = pxdesc->mode & mode & 07777; - if (isdir) wanted.dmode |= 0x10000; - wanted.variable = (void*)pxdesc; - wanted.varsize = sizeof(struct POSIX_SECURITY) - + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); - cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( - scx->vol->securid_cache, GENERIC(&wanted), - (cache_compare)compare); - /* quite simple, if we are lucky */ - if (cached) - securid = cached->securid; + wanted.uid = uid; + wanted.gid = gid; + wanted.dmode = pxdesc->mode & mode & 07777; + if (isdir) wanted.dmode |= 0x10000; + wanted.variable = (void*)pxdesc; + wanted.varsize = sizeof(struct POSIX_SECURITY) + + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); + cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( + scx->vol->securid_cache, GENERIC(&wanted), + (cache_compare)compare); + /* quite simple, if we are lucky */ + if (cached) + securid = cached->securid; - /* not in cache : make sure we can create ids */ + /* not in cache : make sure we can create ids */ - if (!cached && (scx->vol->major_ver >= 3)) { - usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); - gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); - if (!usid || !gsid) { - ntfs_log_error("File created by an unmapped user/group %d/%d\n", - (int)uid, (int)gid); - usid = gsid = adminsid; - } - newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, - isdir, usid, gsid); - if (newattr) { - newattrsz = ntfs_attr_size(newattr); - securid = setsecurityattr(scx->vol, - (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, - newattrsz); - if (securid) { - /* update cache, for subsequent use */ - wanted.securid = securid; - ntfs_enter_cache(scx->vol->securid_cache, - GENERIC(&wanted), - (cache_compare)compare); - } - free(newattr); - } else { - /* - * could not build new security attribute - * errno set by ntfs_build_descr() - */ - } - } - free(pxdesc); - } + if (!cached && (scx->vol->major_ver >= 3)) { + usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); + gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); + if (!usid || !gsid) { + ntfs_log_error("File created by an unmapped user/group %d/%d\n", + (int)uid, (int)gid); + usid = gsid = adminsid; + } + newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, + isdir, usid, gsid); + if (newattr) { + newattrsz = ntfs_attr_size(newattr); + securid = setsecurityattr(scx->vol, + (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, + newattrsz); + if (securid) { + /* update cache, for subsequent use */ + wanted.securid = securid; + ntfs_enter_cache(scx->vol->securid_cache, + GENERIC(&wanted), + (cache_compare)compare); + } + free(newattr); + } else { + /* + * could not build new security attribute + * errno set by ntfs_build_descr() + */ + } + } + free(pxdesc); + } #endif - return (securid); + return (securid); } /* @@ -2554,132 +2585,134 @@ le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, */ int ntfs_set_inherited_posix(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, uid_t uid, gid_t gid, - const char *dir_path, ntfs_inode *dir_ni, mode_t mode) { - struct POSIX_SECURITY *pxdesc; - char *newattr; - const SID *usid; - const SID *gsid; - BIGSID defusid; - BIGSID defgsid; - BOOL isdir; - int res; + ntfs_inode *ni, uid_t uid, gid_t gid, + const char *dir_path, ntfs_inode *dir_ni, mode_t mode) +{ + struct POSIX_SECURITY *pxdesc; + char *newattr; + const SID *usid; + const SID *gsid; + BIGSID defusid; + BIGSID defgsid; + BOOL isdir; + int res; - res = -1; - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); - pxdesc = inherit_posix(scx, dir_path, dir_ni, mode, isdir); - if (pxdesc) { - usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); - gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); - if (!usid || !gsid) { - ntfs_log_error("File created by an unmapped user/group %d/%d\n", - (int)uid, (int)gid); - usid = gsid = adminsid; - } - newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, - isdir, usid, gsid); - if (newattr) { - /* Adjust Windows read-only flag */ - res = update_secur_descr(scx->vol, newattr, ni); - if (!res) { - if (mode & S_IWUSR) - ni->flags &= ~FILE_ATTR_READONLY; - else - ni->flags |= FILE_ATTR_READONLY; - } + res = -1; + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); + pxdesc = inherit_posix(scx, dir_path, dir_ni, mode, isdir); + if (pxdesc) { + usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); + gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); + if (!usid || !gsid) { + ntfs_log_error("File created by an unmapped user/group %d/%d\n", + (int)uid, (int)gid); + usid = gsid = adminsid; + } + newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, + isdir, usid, gsid); + if (newattr) { + /* Adjust Windows read-only flag */ + res = update_secur_descr(scx->vol, newattr, ni); + if (!res) { + if (mode & S_IWUSR) + ni->flags &= ~FILE_ATTR_READONLY; + else + ni->flags |= FILE_ATTR_READONLY; + } #if CACHE_LEGACY_SIZE - /* also invalidate legacy cache */ - if (isdir && !ni->security_id) { - struct CACHED_PERMISSIONS_LEGACY legacy; + /* also invalidate legacy cache */ + if (isdir && !ni->security_id) { + struct CACHED_PERMISSIONS_LEGACY legacy; - legacy.mft_no = ni->mft_no; - legacy.variable = pxdesc; - legacy.varsize = sizeof(struct POSIX_SECURITY) - + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); - ntfs_invalidate_cache(scx->vol->legacy_cache, - GENERIC(&legacy), - (cache_compare)leg_compare); - } + legacy.mft_no = ni->mft_no; + legacy.variable = pxdesc; + legacy.varsize = sizeof(struct POSIX_SECURITY) + + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); + ntfs_invalidate_cache(scx->vol->legacy_cache, + GENERIC(&legacy), + (cache_compare)leg_compare); + } #endif - free(newattr); + free(newattr); - } else { - /* - * could not build new security attribute - * errno set by ntfs_build_descr() - */ - } - } - return (res); + } else { + /* + * could not build new security attribute + * errno set by ntfs_build_descr() + */ + } + } + return (res); } #else le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, mode_t mode, BOOL isdir) { + uid_t uid, gid_t gid, mode_t mode, BOOL isdir) +{ #if !FORCE_FORMAT_v1x - const struct CACHED_SECURID *cached; - struct CACHED_SECURID wanted; - char *newattr; - int newattrsz; - const SID *usid; - const SID *gsid; - BIGSID defusid; - BIGSID defgsid; - le32 securid; + const struct CACHED_SECURID *cached; + struct CACHED_SECURID wanted; + char *newattr; + int newattrsz; + const SID *usid; + const SID *gsid; + BIGSID defusid; + BIGSID defgsid; + le32 securid; #endif - securid = const_cpu_to_le32(0); + securid = const_cpu_to_le32(0); #if !FORCE_FORMAT_v1x - /* check whether target securid is known in cache */ + /* check whether target securid is known in cache */ - wanted.uid = uid; - wanted.gid = gid; - wanted.dmode = mode & 07777; - if (isdir) wanted.dmode |= 0x10000; - wanted.variable = (void*)NULL; - wanted.varsize = 0; - cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( - scx->vol->securid_cache, GENERIC(&wanted), - (cache_compare)compare); - /* quite simple, if we are lucky */ - if (cached) - securid = cached->securid; + wanted.uid = uid; + wanted.gid = gid; + wanted.dmode = mode & 07777; + if (isdir) wanted.dmode |= 0x10000; + wanted.variable = (void*)NULL; + wanted.varsize = 0; + cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( + scx->vol->securid_cache, GENERIC(&wanted), + (cache_compare)compare); + /* quite simple, if we are lucky */ + if (cached) + securid = cached->securid; - /* not in cache : make sure we can create ids */ + /* not in cache : make sure we can create ids */ - if (!cached && (scx->vol->major_ver >= 3)) { - usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); - gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); - if (!usid || !gsid) { - ntfs_log_error("File created by an unmapped user/group %d/%d\n", - (int)uid, (int)gid); - usid = gsid = adminsid; - } - newattr = ntfs_build_descr(mode, isdir, usid, gsid); - if (newattr) { - newattrsz = ntfs_attr_size(newattr); - securid = setsecurityattr(scx->vol, - (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, - newattrsz); - if (securid) { - /* update cache, for subsequent use */ - wanted.securid = securid; - ntfs_enter_cache(scx->vol->securid_cache, - GENERIC(&wanted), - (cache_compare)compare); - } - free(newattr); - } else { - /* - * could not build new security attribute - * errno set by ntfs_build_descr() - */ - } - } + if (!cached && (scx->vol->major_ver >= 3)) { + usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); + gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); + if (!usid || !gsid) { + ntfs_log_error("File created by an unmapped user/group %d/%d\n", + (int)uid, (int)gid); + usid = gsid = adminsid; + } + newattr = ntfs_build_descr(mode, isdir, usid, gsid); + if (newattr) { + newattrsz = ntfs_attr_size(newattr); + securid = setsecurityattr(scx->vol, + (const SECURITY_DESCRIPTOR_RELATIVE*)newattr, + newattrsz); + if (securid) { + /* update cache, for subsequent use */ + wanted.securid = securid; + ntfs_enter_cache(scx->vol->securid_cache, + GENERIC(&wanted), + (cache_compare)compare); + } + free(newattr); + } else { + /* + * could not build new security attribute + * errno set by ntfs_build_descr() + */ + } + } #endif - return (securid); + return (securid); } #endif @@ -2687,128 +2720,128 @@ le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, /* * Update ownership and mode of a file, reusing an existing * security descriptor when possible - * + * * Returns zero if successful */ #if POSIXACLS int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - uid_t uid, gid_t gid, mode_t mode, - struct POSIX_SECURITY *pxdesc) + uid_t uid, gid_t gid, mode_t mode, + struct POSIX_SECURITY *pxdesc) #else int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - uid_t uid, gid_t gid, mode_t mode) + uid_t uid, gid_t gid, mode_t mode) #endif { - int res; - const struct CACHED_SECURID *cached; - struct CACHED_SECURID wanted; - char *newattr; - const SID *usid; - const SID *gsid; - BIGSID defusid; - BIGSID defgsid; - BOOL isdir; + int res; + const struct CACHED_SECURID *cached; + struct CACHED_SECURID wanted; + char *newattr; + const SID *usid; + const SID *gsid; + BIGSID defusid; + BIGSID defgsid; + BOOL isdir; - res = 0; + res = 0; - /* check whether target securid is known in cache */ + /* check whether target securid is known in cache */ - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); - wanted.uid = uid; - wanted.gid = gid; - wanted.dmode = mode & 07777; - if (isdir) wanted.dmode |= 0x10000; + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); + wanted.uid = uid; + wanted.gid = gid; + wanted.dmode = mode & 07777; + if (isdir) wanted.dmode |= 0x10000; #if POSIXACLS - wanted.variable = (void*)pxdesc; - if (pxdesc) - wanted.varsize = sizeof(struct POSIX_SECURITY) - + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); - else - wanted.varsize = 0; + wanted.variable = (void*)pxdesc; + if (pxdesc) + wanted.varsize = sizeof(struct POSIX_SECURITY) + + (pxdesc->acccnt + pxdesc->defcnt)*sizeof(struct POSIX_ACE); + else + wanted.varsize = 0; #else - wanted.variable = (void*)NULL; - wanted.varsize = 0; + wanted.variable = (void*)NULL; + wanted.varsize = 0; #endif - if (test_nino_flag(ni, v3_Extensions)) { - cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( - scx->vol->securid_cache, GENERIC(&wanted), - (cache_compare)compare); - /* quite simple, if we are lucky */ - if (cached) { - ni->security_id = cached->securid; - NInoSetDirty(ni); - } - } else cached = (struct CACHED_SECURID*)NULL; + if (test_nino_flag(ni, v3_Extensions)) { + cached = (const struct CACHED_SECURID*)ntfs_fetch_cache( + scx->vol->securid_cache, GENERIC(&wanted), + (cache_compare)compare); + /* quite simple, if we are lucky */ + if (cached) { + ni->security_id = cached->securid; + NInoSetDirty(ni); + } + } else cached = (struct CACHED_SECURID*)NULL; - if (!cached) { - /* - * Do not use usid and gsid from former attributes, - * but recompute them to get repeatable results - * which can be kept in cache. - */ - usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); - gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); - if (!usid || !gsid) { - ntfs_log_error("File made owned by an unmapped user/group %d/%d\n", - uid, gid); - usid = gsid = adminsid; - } + if (!cached) { + /* + * Do not use usid and gsid from former attributes, + * but recompute them to get repeatable results + * which can be kept in cache. + */ + usid = ntfs_find_usid(scx->mapping[MAPUSERS],uid,(SID*)&defusid); + gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS],gid,(SID*)&defgsid); + if (!usid || !gsid) { + ntfs_log_error("File made owned by an unmapped user/group %d/%d\n", + uid, gid); + usid = gsid = adminsid; + } #if POSIXACLS - if (pxdesc) - newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, - isdir, usid, gsid); - else - newattr = ntfs_build_descr(mode, - isdir, usid, gsid); + if (pxdesc) + newattr = ntfs_build_descr_posix(scx->mapping, pxdesc, + isdir, usid, gsid); + else + newattr = ntfs_build_descr(mode, + isdir, usid, gsid); #else - newattr = ntfs_build_descr(mode, - isdir, usid, gsid); + newattr = ntfs_build_descr(mode, + isdir, usid, gsid); #endif - if (newattr) { - res = update_secur_descr(scx->vol, newattr, ni); - if (!res) { - /* adjust Windows read-only flag */ - if (mode & S_IWUSR) - ni->flags &= ~FILE_ATTR_READONLY; - else - ni->flags |= FILE_ATTR_READONLY; - /* update cache, for subsequent use */ - if (test_nino_flag(ni, v3_Extensions)) { - wanted.securid = ni->security_id; - ntfs_enter_cache(scx->vol->securid_cache, - GENERIC(&wanted), - (cache_compare)compare); - } + if (newattr) { + res = update_secur_descr(scx->vol, newattr, ni); + if (!res) { + /* adjust Windows read-only flag */ + if (mode & S_IWUSR) + ni->flags &= ~FILE_ATTR_READONLY; + else + ni->flags |= FILE_ATTR_READONLY; + /* update cache, for subsequent use */ + if (test_nino_flag(ni, v3_Extensions)) { + wanted.securid = ni->security_id; + ntfs_enter_cache(scx->vol->securid_cache, + GENERIC(&wanted), + (cache_compare)compare); + } #if CACHE_LEGACY_SIZE - /* also invalidate legacy cache */ - if (isdir && !ni->security_id) { - struct CACHED_PERMISSIONS_LEGACY legacy; + /* also invalidate legacy cache */ + if (isdir && !ni->security_id) { + struct CACHED_PERMISSIONS_LEGACY legacy; - legacy.mft_no = ni->mft_no; + legacy.mft_no = ni->mft_no; #if POSIXACLS - legacy.variable = wanted.variable; - legacy.varsize = wanted.varsize; + legacy.variable = wanted.variable; + legacy.varsize = wanted.varsize; #else - legacy.variable = (void*)NULL; - legacy.varsize = 0; + legacy.variable = (void*)NULL; + legacy.varsize = 0; #endif - ntfs_invalidate_cache(scx->vol->legacy_cache, - GENERIC(&legacy), - (cache_compare)leg_compare); - } + ntfs_invalidate_cache(scx->vol->legacy_cache, + GENERIC(&legacy), + (cache_compare)leg_compare); + } #endif - } - free(newattr); - } else { - /* - * could not build new security attribute - * errno set by ntfs_build_descr() - */ - res = -1; - } - } - return (res); + } + free(newattr); + } else { + /* + * could not build new security attribute + * errno set by ntfs_build_descr() + */ + res = -1; + } + } + return (res); } /* @@ -2819,47 +2852,48 @@ int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, */ BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni) { - const struct CACHED_PERMISSIONS *cached; - char *oldattr; - const SID *usid; - uid_t processuid; - uid_t uid; - BOOL gotowner; - int allowed; + const char *path, ntfs_inode *ni) +{ + const struct CACHED_PERMISSIONS *cached; + char *oldattr; + const SID *usid; + uid_t processuid; + uid_t uid; + BOOL gotowner; + int allowed; - gotowner = FALSE; /* default */ - processuid = scx->uid; - /* get the owner, either from cache or from old attribute */ - cached = fetch_cache(scx, ni); - if (cached) { - uid = cached->uid; - gotowner = TRUE; - } else { - oldattr = getsecurityattr(scx->vol,path, ni); - if (oldattr) { + gotowner = FALSE; /* default */ + processuid = scx->uid; + /* get the owner, either from cache or from old attribute */ + cached = fetch_cache(scx, ni); + if (cached) { + uid = cached->uid; + gotowner = TRUE; + } else { + oldattr = getsecurityattr(scx->vol,path, ni); + if (oldattr) { #if OWNERFROMACL - usid = ntfs_acl_owner(oldattr); + usid = ntfs_acl_owner(oldattr); #else - const SECURITY_DESCRIPTOR_RELATIVE *phead; + const SECURITY_DESCRIPTOR_RELATIVE *phead; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; - usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; + usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; #endif - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); - gotowner = TRUE; - free(oldattr); - } - } - allowed = FALSE; - if (gotowner) { - /* TODO : use CAP_FOWNER process capability */ - if (!processuid || (processuid == uid)) - allowed = TRUE; - else - errno = EPERM; - } - return (allowed); + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + gotowner = TRUE; + free(oldattr); + } + } + allowed = FALSE; + if (gotowner) { +/* TODO : use CAP_FOWNER process capability */ + if (!processuid || (processuid == uid)) + allowed = TRUE; + else + errno = EPERM; + } + return (allowed); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -2875,99 +2909,100 @@ BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, */ int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, const char *value, size_t size, - int flags, ntfs_inode *ni) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const struct CACHED_PERMISSIONS *cached; - char *oldattr; - uid_t processuid; - const SID *usid; - const SID *gsid; - uid_t uid; - uid_t gid; - int res; - mode_t mode; - BOOL isdir; - BOOL deflt; - BOOL exist; - int count; - struct POSIX_SECURITY *oldpxdesc; - struct POSIX_SECURITY *newpxdesc; + const char *name, const char *value, size_t size, + int flags, ntfs_inode *ni) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const struct CACHED_PERMISSIONS *cached; + char *oldattr; + uid_t processuid; + const SID *usid; + const SID *gsid; + uid_t uid; + uid_t gid; + int res; + mode_t mode; + BOOL isdir; + BOOL deflt; + BOOL exist; + int count; + struct POSIX_SECURITY *oldpxdesc; + struct POSIX_SECURITY *newpxdesc; - /* get the current pxsec, either from cache or from old attribute */ - res = -1; - deflt = !strcmp(name,"system.posix_acl_default"); - if (size) - count = (size - sizeof(struct POSIX_ACL)) / sizeof(struct POSIX_ACE); - else - count = 0; - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); - newpxdesc = (struct POSIX_SECURITY*)NULL; - if (!deflt || isdir || !size) { - cached = fetch_cache(scx, ni); - if (cached) { - uid = cached->uid; - gid = cached->gid; - oldpxdesc = cached->pxdesc; - if (oldpxdesc) { - mode = oldpxdesc->mode; - newpxdesc = ntfs_replace_acl(oldpxdesc, - (const struct POSIX_ACL*)value,count,deflt); - } - } else { - oldattr = getsecurityattr(scx->vol,path, ni); - if (oldattr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; + /* get the current pxsec, either from cache or from old attribute */ + res = -1; + deflt = !strcmp(name,"system.posix_acl_default"); + if (size) + count = (size - sizeof(struct POSIX_ACL)) / sizeof(struct POSIX_ACE); + else + count = 0; + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); + newpxdesc = (struct POSIX_SECURITY*)NULL; + if (!deflt || isdir || !size) { + cached = fetch_cache(scx, ni); + if (cached) { + uid = cached->uid; + gid = cached->gid; + oldpxdesc = cached->pxdesc; + if (oldpxdesc) { + mode = oldpxdesc->mode; + newpxdesc = ntfs_replace_acl(oldpxdesc, + (const struct POSIX_ACL*)value,count,deflt); + } + } else { + oldattr = getsecurityattr(scx->vol,path, ni); + if (oldattr) { + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; #if OWNERFROMACL - usid = ntfs_acl_owner(oldattr); + usid = ntfs_acl_owner(oldattr); #else - usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; + usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; #endif - gsid = (const SID*)&oldattr[le32_to_cpu(phead->group)]; - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); - gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); - oldpxdesc = ntfs_build_permissions_posix(scx->mapping, - oldattr, usid, gsid, isdir); - if (oldpxdesc) { - if (deflt) - exist = oldpxdesc->defcnt > 0; - else - exist = oldpxdesc->acccnt > 3; - if ((exist && (flags & XATTR_CREATE)) - || (!exist && (flags & XATTR_REPLACE))) { - errno = (exist ? EEXIST : ENODATA); - } else { - mode = oldpxdesc->mode; - newpxdesc = ntfs_replace_acl(oldpxdesc, - (const struct POSIX_ACL*)value,count,deflt); - } - free(oldpxdesc); - } - free(oldattr); - } - } - } else - errno = EINVAL; + gsid = (const SID*)&oldattr[le32_to_cpu(phead->group)]; + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + oldpxdesc = ntfs_build_permissions_posix(scx->mapping, + oldattr, usid, gsid, isdir); + if (oldpxdesc) { + if (deflt) + exist = oldpxdesc->defcnt > 0; + else + exist = oldpxdesc->acccnt > 3; + if ((exist && (flags & XATTR_CREATE)) + || (!exist && (flags & XATTR_REPLACE))) { + errno = (exist ? EEXIST : ENODATA); + } else { + mode = oldpxdesc->mode; + newpxdesc = ntfs_replace_acl(oldpxdesc, + (const struct POSIX_ACL*)value,count,deflt); + } + free(oldpxdesc); + } + free(oldattr); + } + } + } else + errno = EINVAL; - if (newpxdesc) { - processuid = scx->uid; - /* TODO : use CAP_FOWNER process capability */ - if (!processuid || (uid == processuid)) { - /* - * clear setgid if file group does - * not match process group - */ - if (processuid && (gid != scx->gid) - && !groupmember(scx, scx->uid, gid)) { - newpxdesc->mode &= ~S_ISGID; - } - res = ntfs_set_owner_mode(scx, ni, uid, gid, - newpxdesc->mode, newpxdesc); - } else - errno = EPERM; - free(newpxdesc); - } - return (res ? -1 : 0); + if (newpxdesc) { + processuid = scx->uid; +/* TODO : use CAP_FOWNER process capability */ + if (!processuid || (uid == processuid)) { + /* + * clear setgid if file group does + * not match process group + */ + if (processuid && (gid != scx->gid) + && !groupmember(scx, scx->uid, gid)) { + newpxdesc->mode &= ~S_ISGID; + } + res = ntfs_set_owner_mode(scx, ni, uid, gid, + newpxdesc->mode, newpxdesc); + } else + errno = EPERM; + free(newpxdesc); + } + return (res ? -1 : 0); } /* @@ -2977,9 +3012,10 @@ int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, */ int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, ntfs_inode *ni) { - return (ntfs_set_posix_acl(scx, path, name, - (const char*)NULL, 0, 0, ni)); + const char *name, ntfs_inode *ni) +{ + return (ntfs_set_posix_acl(scx, path, name, + (const char*)NULL, 0, 0, ni)); } #endif @@ -2991,55 +3027,56 @@ int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, */ int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, - const char *path __attribute__((unused)), - const char *name __attribute__((unused)), - const char *value, size_t size, int flags, - ntfs_inode *ni) { - char *attr; - int res; + const char *path __attribute__((unused)), + const char *name __attribute__((unused)), + const char *value, size_t size, int flags, + ntfs_inode *ni) +{ + char *attr; + int res; - res = -1; - if ((size > 0) - && !(flags & XATTR_CREATE) - && ntfs_valid_descr(value,size) - && (ntfs_attr_size(value) == size)) { - /* need copying in order to write */ - attr = (char*)ntfs_malloc(size); - if (attr) { - memcpy(attr,value,size); - res = update_secur_descr(scx->vol, attr, ni); - /* - * No need to invalidate standard caches : - * the relation between a securid and - * the associated protection is unchanged, - * only the relation between a file and - * its securid and protection is changed. - */ + res = -1; + if ((size > 0) + && !(flags & XATTR_CREATE) + && ntfs_valid_descr(value,size) + && (ntfs_attr_size(value) == size)) { + /* need copying in order to write */ + attr = (char*)ntfs_malloc(size); + if (attr) { + memcpy(attr,value,size); + res = update_secur_descr(scx->vol, attr, ni); + /* + * No need to invalidate standard caches : + * the relation between a securid and + * the associated protection is unchanged, + * only the relation between a file and + * its securid and protection is changed. + */ #if CACHE_LEGACY_SIZE - /* - * we must however invalidate the legacy - * cache, which is based on inode numbers. - * For safety, invalidate even if updating - * failed. - */ - if ((ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - && !ni->security_id) { - struct CACHED_PERMISSIONS_LEGACY legacy; + /* + * we must however invalidate the legacy + * cache, which is based on inode numbers. + * For safety, invalidate even if updating + * failed. + */ + if ((ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + && !ni->security_id) { + struct CACHED_PERMISSIONS_LEGACY legacy; - legacy.mft_no = ni->mft_no; - legacy.variable = (char*)NULL; - legacy.varsize = 0; - ntfs_invalidate_cache(scx->vol->legacy_cache, - GENERIC(&legacy), - (cache_compare)leg_compare); - } + legacy.mft_no = ni->mft_no; + legacy.variable = (char*)NULL; + legacy.varsize = 0; + ntfs_invalidate_cache(scx->vol->legacy_cache, + GENERIC(&legacy), + (cache_compare)leg_compare); + } #endif - free(attr); - } else - errno = ENOMEM; - } else - errno = EINVAL; - return (res ? -1 : 0); + free(attr); + } else + errno = ENOMEM; + } else + errno = EINVAL; + return (res ? -1 : 0); } #endif /* HAVE_SETXATTR */ @@ -3055,108 +3092,109 @@ int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, */ int ntfs_set_mode(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni, mode_t mode) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const struct CACHED_PERMISSIONS *cached; - char *oldattr; - const SID *usid; - const SID *gsid; - uid_t processuid; - uid_t uid; - uid_t gid; - int res; + const char *path, ntfs_inode *ni, mode_t mode) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const struct CACHED_PERMISSIONS *cached; + char *oldattr; + const SID *usid; + const SID *gsid; + uid_t processuid; + uid_t uid; + uid_t gid; + int res; #if POSIXACLS - BOOL isdir; - int pxsize; - const struct POSIX_SECURITY *oldpxdesc; - struct POSIX_SECURITY *newpxdesc = (struct POSIX_SECURITY*)NULL; + BOOL isdir; + int pxsize; + const struct POSIX_SECURITY *oldpxdesc; + struct POSIX_SECURITY *newpxdesc = (struct POSIX_SECURITY*)NULL; #endif - /* get the current owner, either from cache or from old attribute */ - res = 0; - cached = fetch_cache(scx, ni); - if (cached) { - uid = cached->uid; - gid = cached->gid; + /* get the current owner, either from cache or from old attribute */ + res = 0; + cached = fetch_cache(scx, ni); + if (cached) { + uid = cached->uid; + gid = cached->gid; #if POSIXACLS - oldpxdesc = cached->pxdesc; - if (oldpxdesc) { - /* must copy before merging */ - pxsize = sizeof(struct POSIX_SECURITY) - + (oldpxdesc->acccnt + oldpxdesc->defcnt)*sizeof(struct POSIX_ACE); - newpxdesc = (struct POSIX_SECURITY*)malloc(pxsize); - if (newpxdesc) { - memcpy(newpxdesc, oldpxdesc, pxsize); - if (ntfs_merge_mode_posix(newpxdesc, mode)) - res = -1; - } else - res = -1; - } else - newpxdesc = (struct POSIX_SECURITY*)NULL; + oldpxdesc = cached->pxdesc; + if (oldpxdesc) { + /* must copy before merging */ + pxsize = sizeof(struct POSIX_SECURITY) + + (oldpxdesc->acccnt + oldpxdesc->defcnt)*sizeof(struct POSIX_ACE); + newpxdesc = (struct POSIX_SECURITY*)malloc(pxsize); + if (newpxdesc) { + memcpy(newpxdesc, oldpxdesc, pxsize); + if (ntfs_merge_mode_posix(newpxdesc, mode)) + res = -1; + } else + res = -1; + } else + newpxdesc = (struct POSIX_SECURITY*)NULL; #endif - } else { - oldattr = getsecurityattr(scx->vol,path, ni); - if (oldattr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; + } else { + oldattr = getsecurityattr(scx->vol,path, ni); + if (oldattr) { + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; #if OWNERFROMACL - usid = ntfs_acl_owner(oldattr); + usid = ntfs_acl_owner(oldattr); #else - usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; + usid = (const SID*)&oldattr[le32_to_cpu(phead->owner)]; #endif - gsid = (const SID*)&oldattr[le32_to_cpu(phead->group)]; - uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); - gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + gsid = (const SID*)&oldattr[le32_to_cpu(phead->group)]; + uid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + gid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); #if POSIXACLS - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); - newpxdesc = ntfs_build_permissions_posix(scx->mapping, - oldattr, usid, gsid, isdir); - if (!newpxdesc || ntfs_merge_mode_posix(newpxdesc, mode)) - res = -1; + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) != const_cpu_to_le16(0); + newpxdesc = ntfs_build_permissions_posix(scx->mapping, + oldattr, usid, gsid, isdir); + if (!newpxdesc || ntfs_merge_mode_posix(newpxdesc, mode)) + res = -1; #endif - free(oldattr); - } else - res = -1; - } + free(oldattr); + } else + res = -1; + } - if (!res) { - processuid = scx->uid; - /* TODO : use CAP_FOWNER process capability */ - if (!processuid || (uid == processuid)) { - /* - * clear setgid if file group does - * not match process group - */ - if (processuid && (gid != scx->gid) - && !groupmember(scx, scx->uid, gid)) - mode &= ~S_ISGID; + if (!res) { + processuid = scx->uid; +/* TODO : use CAP_FOWNER process capability */ + if (!processuid || (uid == processuid)) { + /* + * clear setgid if file group does + * not match process group + */ + if (processuid && (gid != scx->gid) + && !groupmember(scx, scx->uid, gid)) + mode &= ~S_ISGID; #if POSIXACLS - if (newpxdesc) { - newpxdesc->mode = mode; - res = ntfs_set_owner_mode(scx, ni, uid, gid, - mode, newpxdesc); - } else - res = ntfs_set_owner_mode(scx, ni, uid, gid, - mode, newpxdesc); + if (newpxdesc) { + newpxdesc->mode = mode; + res = ntfs_set_owner_mode(scx, ni, uid, gid, + mode, newpxdesc); + } else + res = ntfs_set_owner_mode(scx, ni, uid, gid, + mode, newpxdesc); #else - res = ntfs_set_owner_mode(scx, ni, uid, gid, mode); + res = ntfs_set_owner_mode(scx, ni, uid, gid, mode); #endif - } else { - errno = EPERM; - res = -1; /* neither owner nor root */ - } - } else { - /* - * Should not happen : a default descriptor is generated - * by getsecurityattr() when there are none - */ - ntfs_log_error("File has no security descriptor\n"); - res = -1; - errno = EIO; - } + } else { + errno = EPERM; + res = -1; /* neither owner nor root */ + } + } else { + /* + * Should not happen : a default descriptor is generated + * by getsecurityattr() when there are none + */ + ntfs_log_error("File has no security descriptor\n"); + res = -1; + errno = EIO; + } #if POSIXACLS - if (newpxdesc) free(newpxdesc); + if (newpxdesc) free(newpxdesc); #endif - return (res ? -1 : 0); + return (res ? -1 : 0); } /* @@ -3164,68 +3202,69 @@ int ntfs_set_mode(struct SECURITY_CONTEXT *scx, * cannot be inherited */ -int ntfs_sd_add_everyone(ntfs_inode *ni) { - /* JPA SECURITY_DESCRIPTOR_ATTR *sd; */ - SECURITY_DESCRIPTOR_RELATIVE *sd; - ACL *acl; - ACCESS_ALLOWED_ACE *ace; - SID *sid; - int ret, sd_len; +int ntfs_sd_add_everyone(ntfs_inode *ni) +{ + /* JPA SECURITY_DESCRIPTOR_ATTR *sd; */ + SECURITY_DESCRIPTOR_RELATIVE *sd; + ACL *acl; + ACCESS_ALLOWED_ACE *ace; + SID *sid; + int ret, sd_len; + + /* Create SECURITY_DESCRIPTOR attribute (everyone has full access). */ + /* + * Calculate security descriptor length. We have 2 sub-authorities in + * owner and group SIDs, but structure SID contain only one, so add + * 4 bytes to every SID. + */ + sd_len = sizeof(SECURITY_DESCRIPTOR_ATTR) + 2 * (sizeof(SID) + 4) + + sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE); + sd = (SECURITY_DESCRIPTOR_RELATIVE*)ntfs_calloc(sd_len); + if (!sd) + return -1; + + sd->revision = SECURITY_DESCRIPTOR_REVISION; + sd->control = SE_DACL_PRESENT | SE_SELF_RELATIVE; + + sid = (SID*)((u8*)sd + sizeof(SECURITY_DESCRIPTOR_ATTR)); + sid->revision = SID_REVISION; + sid->sub_authority_count = 2; + sid->sub_authority[0] = const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID); + sid->sub_authority[1] = const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS); + sid->identifier_authority.value[5] = 5; + sd->owner = cpu_to_le32((u8*)sid - (u8*)sd); + + sid = (SID*)((u8*)sid + sizeof(SID) + 4); + sid->revision = SID_REVISION; + sid->sub_authority_count = 2; + sid->sub_authority[0] = const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID); + sid->sub_authority[1] = const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS); + sid->identifier_authority.value[5] = 5; + sd->group = cpu_to_le32((u8*)sid - (u8*)sd); + + acl = (ACL*)((u8*)sid + sizeof(SID) + 4); + acl->revision = ACL_REVISION; + acl->size = const_cpu_to_le16(sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE)); + acl->ace_count = const_cpu_to_le16(1); + sd->dacl = cpu_to_le32((u8*)acl - (u8*)sd); + + ace = (ACCESS_ALLOWED_ACE*)((u8*)acl + sizeof(ACL)); + ace->type = ACCESS_ALLOWED_ACE_TYPE; + ace->flags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; + ace->size = const_cpu_to_le16(sizeof(ACCESS_ALLOWED_ACE)); + ace->mask = const_cpu_to_le32(0x1f01ff); /* FIXME */ + ace->sid.revision = SID_REVISION; + ace->sid.sub_authority_count = 1; + ace->sid.sub_authority[0] = const_cpu_to_le32(0); + ace->sid.identifier_authority.value[5] = 1; - /* Create SECURITY_DESCRIPTOR attribute (everyone has full access). */ - /* - * Calculate security descriptor length. We have 2 sub-authorities in - * owner and group SIDs, but structure SID contain only one, so add - * 4 bytes to every SID. - */ - sd_len = sizeof(SECURITY_DESCRIPTOR_ATTR) + 2 * (sizeof(SID) + 4) + - sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE); - sd = (SECURITY_DESCRIPTOR_RELATIVE*)ntfs_calloc(sd_len); - if (!sd) - return -1; - - sd->revision = SECURITY_DESCRIPTOR_REVISION; - sd->control = SE_DACL_PRESENT | SE_SELF_RELATIVE; - - sid = (SID*)((u8*)sd + sizeof(SECURITY_DESCRIPTOR_ATTR)); - sid->revision = SID_REVISION; - sid->sub_authority_count = 2; - sid->sub_authority[0] = const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID); - sid->sub_authority[1] = const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS); - sid->identifier_authority.value[5] = 5; - sd->owner = cpu_to_le32((u8*)sid - (u8*)sd); - - sid = (SID*)((u8*)sid + sizeof(SID) + 4); - sid->revision = SID_REVISION; - sid->sub_authority_count = 2; - sid->sub_authority[0] = const_cpu_to_le32(SECURITY_BUILTIN_DOMAIN_RID); - sid->sub_authority[1] = const_cpu_to_le32(DOMAIN_ALIAS_RID_ADMINS); - sid->identifier_authority.value[5] = 5; - sd->group = cpu_to_le32((u8*)sid - (u8*)sd); - - acl = (ACL*)((u8*)sid + sizeof(SID) + 4); - acl->revision = ACL_REVISION; - acl->size = const_cpu_to_le16(sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE)); - acl->ace_count = const_cpu_to_le16(1); - sd->dacl = cpu_to_le32((u8*)acl - (u8*)sd); - - ace = (ACCESS_ALLOWED_ACE*)((u8*)acl + sizeof(ACL)); - ace->type = ACCESS_ALLOWED_ACE_TYPE; - ace->flags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; - ace->size = const_cpu_to_le16(sizeof(ACCESS_ALLOWED_ACE)); - ace->mask = const_cpu_to_le32(0x1f01ff); /* FIXME */ - ace->sid.revision = SID_REVISION; - ace->sid.sub_authority_count = 1; - ace->sid.sub_authority[0] = const_cpu_to_le32(0); - ace->sid.identifier_authority.value[5] = 1; - - ret = ntfs_attr_add(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0, (u8*)sd, - sd_len); - if (ret) - ntfs_log_perror("Failed to add initial SECURITY_DESCRIPTOR"); - - free(sd); - return ret; + ret = ntfs_attr_add(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0, (u8*)sd, + sd_len); + if (ret) + ntfs_log_perror("Failed to add initial SECURITY_DESCRIPTOR"); + + free(sd); + return ret; } /* @@ -3241,75 +3280,76 @@ int ntfs_sd_add_everyone(ntfs_inode *ni) { */ int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni, - int accesstype) { /* access type required (S_Ixxx values) */ - int perm; - int res; - int allow; - struct stat stbuf; + const char *path, ntfs_inode *ni, + int accesstype) /* access type required (S_Ixxx values) */ +{ + int perm; + int res; + int allow; + struct stat stbuf; #if POSIXACLS - /* shortcut, use only if Posix ACLs in use */ - if (scx->vol->secure_flags & (1 << SECURITY_DEFAULT)) return (1); + /* shortcut, use only if Posix ACLs in use */ + if (scx->vol->secure_flags & (1 << SECURITY_DEFAULT)) return (1); #endif - /* - * Always allow for root unless execution is requested. - * (was checked by fuse until kernel 2.6.29) - * Also always allow if no mapping has been defined - */ - if (!scx->mapping[MAPUSERS] - || (!scx->uid - && (!(accesstype & S_IEXEC) - || (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)))) - allow = 1; - else { - perm = ntfs_get_perm(scx, path, ni, accesstype); - if (perm >= 0) { - res = EACCES; - switch (accesstype) { - case S_IEXEC: - allow = (perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0; - break; - case S_IWRITE: - allow = (perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0; - break; - case S_IWRITE + S_IEXEC: - allow = ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) - && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); - break; - case S_IREAD: - allow = (perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0; - break; - case S_IREAD + S_IEXEC: - allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) - && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); - break; - case S_IREAD + S_IWRITE: - allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) - && ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0); - break; - case S_IWRITE + S_IEXEC + S_ISVTX: - if (perm & S_ISVTX) { - if ((ntfs_get_owner_mode(scx,path,ni,&stbuf) >= 0) - && (stbuf.st_uid == scx->uid)) - allow = 1; - else - allow = 2; - } else - allow = ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) - && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); - break; - default : - res = EINVAL; - allow = 0; - break; - } - if (!allow) - errno = res; - } else - allow = 0; - } - return (allow); + /* + * Always allow for root unless execution is requested. + * (was checked by fuse until kernel 2.6.29) + * Also always allow if no mapping has been defined + */ + if (!scx->mapping[MAPUSERS] + || (!scx->uid + && (!(accesstype & S_IEXEC) + || (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)))) + allow = 1; + else { + perm = ntfs_get_perm(scx, path, ni, accesstype); + if (perm >= 0) { + res = EACCES; + switch (accesstype) { + case S_IEXEC: + allow = (perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0; + break; + case S_IWRITE: + allow = (perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0; + break; + case S_IWRITE + S_IEXEC: + allow = ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) + && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); + break; + case S_IREAD: + allow = (perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0; + break; + case S_IREAD + S_IEXEC: + allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) + && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); + break; + case S_IREAD + S_IWRITE: + allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) + && ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0); + break; + case S_IWRITE + S_IEXEC + S_ISVTX: + if (perm & S_ISVTX) { + if ((ntfs_get_owner_mode(scx,path,ni,&stbuf) >= 0) + && (stbuf.st_uid == scx->uid)) + allow = 1; + else + allow = 2; + } else + allow = ((perm & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) + && ((perm & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0); + break; + default : + res = EINVAL; + allow = 0; + break; + } + if (!allow) + errno = res; + } else + allow = 0; + } + return (allow); } /* @@ -3318,56 +3358,57 @@ int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, * * Returns true if access is allowed, including user is root and * no user mapping defined - * + * * Sets errno if there is a problem or if not allowed * * This is used for Posix ACL and checking creation of DOS file names */ BOOL ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, - const char *path, int accesstype) { - int allow; - char *dirpath; - char *name; - ntfs_inode *ni; - ntfs_inode *dir_ni; - struct stat stbuf; + const char *path, int accesstype) +{ + int allow; + char *dirpath; + char *name; + ntfs_inode *ni; + ntfs_inode *dir_ni; + struct stat stbuf; #if POSIXACLS - /* shortcut, use only if Posix ACLs in use */ - if (scx->vol->secure_flags & (1 << SECURITY_DEFAULT)) return (TRUE); + /* shortcut, use only if Posix ACLs in use */ + if (scx->vol->secure_flags & (1 << SECURITY_DEFAULT)) return (TRUE); #endif - allow = 0; - dirpath = strdup(path); - if (dirpath) { - /* the root of file system is seen as a parent of itself */ - /* is that correct ? */ - name = strrchr(dirpath, '/'); - *name = 0; - dir_ni = ntfs_pathname_to_inode(scx->vol, NULL, dirpath); - if (dir_ni) { - allow = ntfs_allowed_access(scx,dirpath, - dir_ni, accesstype); - ntfs_inode_close(dir_ni); - /* - * for an not-owned sticky directory, have to - * check whether file itself is owned - */ - if ((accesstype == (S_IWRITE + S_IEXEC + S_ISVTX)) - && (allow == 2)) { - ni = ntfs_pathname_to_inode(scx->vol, NULL, - path); - allow = FALSE; - if (ni) { - allow = (ntfs_get_owner_mode(scx,path,ni,&stbuf) >= 0) - && (stbuf.st_uid == scx->uid); - ntfs_inode_close(ni); - } - } - } - free(dirpath); - } - return (allow); /* errno is set if not allowed */ + allow = 0; + dirpath = strdup(path); + if (dirpath) { + /* the root of file system is seen as a parent of itself */ + /* is that correct ? */ + name = strrchr(dirpath, '/'); + *name = 0; + dir_ni = ntfs_pathname_to_inode(scx->vol, NULL, dirpath); + if (dir_ni) { + allow = ntfs_allowed_access(scx,dirpath, + dir_ni, accesstype); + ntfs_inode_close(dir_ni); + /* + * for an not-owned sticky directory, have to + * check whether file itself is owned + */ + if ((accesstype == (S_IWRITE + S_IEXEC + S_ISVTX)) + && (allow == 2)) { + ni = ntfs_pathname_to_inode(scx->vol, NULL, + path); + allow = FALSE; + if (ni) { + allow = (ntfs_get_owner_mode(scx,path,ni,&stbuf) >= 0) + && (stbuf.st_uid == scx->uid); + ntfs_inode_close(ni); + } + } + } + free(dirpath); + } + return (allow); /* errno is set if not allowed */ } /* @@ -3377,118 +3418,119 @@ BOOL ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, */ int ntfs_set_owner(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni, uid_t uid, gid_t gid) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const struct CACHED_PERMISSIONS *cached; - char *oldattr; - const SID *usid; - const SID *gsid; - uid_t fileuid; - uid_t filegid; - mode_t mode; - int perm; - BOOL isdir; - int res; + const char *path, ntfs_inode *ni, uid_t uid, gid_t gid) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const struct CACHED_PERMISSIONS *cached; + char *oldattr; + const SID *usid; + const SID *gsid; + uid_t fileuid; + uid_t filegid; + mode_t mode; + int perm; + BOOL isdir; + int res; #if POSIXACLS - struct POSIX_SECURITY *pxdesc; - BOOL pxdescbuilt = FALSE; + struct POSIX_SECURITY *pxdesc; + BOOL pxdescbuilt = FALSE; #endif - res = 0; - /* get the current owner and mode from cache or security attributes */ - oldattr = (char*)NULL; - cached = fetch_cache(scx,ni); - if (cached) { - fileuid = cached->uid; - filegid = cached->gid; - mode = cached->mode; + res = 0; + /* get the current owner and mode from cache or security attributes */ + oldattr = (char*)NULL; + cached = fetch_cache(scx,ni); + if (cached) { + fileuid = cached->uid; + filegid = cached->gid; + mode = cached->mode; #if POSIXACLS - pxdesc = cached->pxdesc; - if (!pxdesc) - res = -1; + pxdesc = cached->pxdesc; + if (!pxdesc) + res = -1; #endif - } else { - fileuid = 0; - filegid = 0; - mode = 0; - oldattr = getsecurityattr(scx->vol, path, ni); - if (oldattr) { - isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - != const_cpu_to_le16(0); - phead = (const SECURITY_DESCRIPTOR_RELATIVE*) - oldattr; - gsid = (const SID*) - &oldattr[le32_to_cpu(phead->group)]; + } else { + fileuid = 0; + filegid = 0; + mode = 0; + oldattr = getsecurityattr(scx->vol, path, ni); + if (oldattr) { + isdir = (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + != const_cpu_to_le16(0); + phead = (const SECURITY_DESCRIPTOR_RELATIVE*) + oldattr; + gsid = (const SID*) + &oldattr[le32_to_cpu(phead->group)]; #if OWNERFROMACL - usid = ntfs_acl_owner(oldattr); + usid = ntfs_acl_owner(oldattr); #else - usid = (const SID*) - &oldattr[le32_to_cpu(phead->owner)]; + usid = (const SID*) + &oldattr[le32_to_cpu(phead->owner)]; #endif #if POSIXACLS - pxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, - usid, gsid, isdir); - if (pxdesc) { - pxdescbuilt = TRUE; - fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); - filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); - mode = perm = pxdesc->mode; - } else - res = -1; + pxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, + usid, gsid, isdir); + if (pxdesc) { + pxdescbuilt = TRUE; + fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + mode = perm = pxdesc->mode; + } else + res = -1; #else - mode = perm = ntfs_build_permissions(oldattr, - usid, gsid, isdir); - if (perm >= 0) { - fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); - filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); - } else - res = -1; + mode = perm = ntfs_build_permissions(oldattr, + usid, gsid, isdir); + if (perm >= 0) { + fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + } else + res = -1; #endif - free(oldattr); - } else - res = -1; - } - if (!res) { - /* check requested by root */ - /* or chgrp requested by owner to an owned group */ - if (!scx->uid - || ((((int)uid < 0) || (uid == fileuid)) - && ((gid == scx->gid) || groupmember(scx, scx->uid, gid)) - && (fileuid == scx->uid))) { - /* replace by the new usid and gsid */ - /* or reuse old gid and sid for cacheing */ - if ((int)uid < 0) - uid = fileuid; - if ((int)gid < 0) - gid = filegid; - /* clear setuid and setgid if owner has changed */ - /* unless request originated by root */ - if (uid && (fileuid != uid)) - mode &= 01777; + free(oldattr); + } else + res = -1; + } + if (!res) { + /* check requested by root */ + /* or chgrp requested by owner to an owned group */ + if (!scx->uid + || ((((int)uid < 0) || (uid == fileuid)) + && ((gid == scx->gid) || groupmember(scx, scx->uid, gid)) + && (fileuid == scx->uid))) { + /* replace by the new usid and gsid */ + /* or reuse old gid and sid for cacheing */ + if ((int)uid < 0) + uid = fileuid; + if ((int)gid < 0) + gid = filegid; + /* clear setuid and setgid if owner has changed */ + /* unless request originated by root */ + if (uid && (fileuid != uid)) + mode &= 01777; #if POSIXACLS - res = ntfs_set_owner_mode(scx, ni, uid, gid, - mode, pxdesc); + res = ntfs_set_owner_mode(scx, ni, uid, gid, + mode, pxdesc); #else - res = ntfs_set_owner_mode(scx, ni, uid, gid, mode); + res = ntfs_set_owner_mode(scx, ni, uid, gid, mode); #endif - } else { - res = -1; /* neither owner nor root */ - errno = EPERM; - } + } else { + res = -1; /* neither owner nor root */ + errno = EPERM; + } #if POSIXACLS - if (pxdescbuilt) - free(pxdesc); + if (pxdescbuilt) + free(pxdesc); #endif - } else { - /* - * Should not happen : a default descriptor is generated - * by getsecurityattr() when there are none - */ - ntfs_log_error("File has no security descriptor\n"); - res = -1; - errno = EIO; - } - return (res ? -1 : 0); + } else { + /* + * Should not happen : a default descriptor is generated + * by getsecurityattr() when there are none + */ + ntfs_log_error("File has no security descriptor\n"); + res = -1; + errno = EIO; + } + return (res ? -1 : 0); } /* @@ -3497,117 +3539,118 @@ int ntfs_set_owner(struct SECURITY_CONTEXT *scx, */ static le32 build_inherited_id(struct SECURITY_CONTEXT *scx, - const char *parentattr, BOOL fordir) { - const SECURITY_DESCRIPTOR_RELATIVE *pphead; - const ACL *ppacl; - const SID *usid; - const SID *gsid; - BIGSID defusid; - BIGSID defgsid; - int offpacl; - int offowner; - int offgroup; - SECURITY_DESCRIPTOR_RELATIVE *pnhead; - ACL *pnacl; - int parentattrsz; - char *newattr; - int newattrsz; - int aclsz; - int usidsz; - int gsidsz; - int pos; - le32 securid; + const char *parentattr, BOOL fordir) +{ + const SECURITY_DESCRIPTOR_RELATIVE *pphead; + const ACL *ppacl; + const SID *usid; + const SID *gsid; + BIGSID defusid; + BIGSID defgsid; + int offpacl; + int offowner; + int offgroup; + SECURITY_DESCRIPTOR_RELATIVE *pnhead; + ACL *pnacl; + int parentattrsz; + char *newattr; + int newattrsz; + int aclsz; + int usidsz; + int gsidsz; + int pos; + le32 securid; - parentattrsz = ntfs_attr_size(parentattr); - pphead = (const SECURITY_DESCRIPTOR_RELATIVE*)parentattr; - if (scx->mapping[MAPUSERS]) { - usid = ntfs_find_usid(scx->mapping[MAPUSERS], scx->uid, (SID*)&defusid); - gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS], scx->gid, (SID*)&defgsid); - if (!usid) - usid = adminsid; - if (!gsid) - gsid = adminsid; - } else { - /* - * If there is no user mapping, we have to copy owner - * and group from parent directory. - * Windows never has to do that, because it can always - * rely on a user mapping - */ - offowner = le32_to_cpu(pphead->owner); - usid = (const SID*)&parentattr[offowner]; - offgroup = le32_to_cpu(pphead->group); - gsid = (const SID*)&parentattr[offgroup]; - } - /* - * new attribute is smaller than parent's - * except for differences in SIDs which appear in - * owner, group and possible grants and denials in - * generic creator-owner and creator-group ACEs. - * For directories, an ACE may be duplicated for - * access and inheritance, so we double the count. - */ - usidsz = ntfs_sid_size(usid); - gsidsz = ntfs_sid_size(gsid); - newattrsz = parentattrsz + 3*usidsz + 3*gsidsz; - if (fordir) - newattrsz *= 2; - newattr = (char*)ntfs_malloc(newattrsz); - if (newattr) { - pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)newattr; - pnhead->revision = SECURITY_DESCRIPTOR_REVISION; - pnhead->alignment = 0; - pnhead->control = SE_SELF_RELATIVE; - pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); - /* - * locate and inherit DACL - * do not test SE_DACL_PRESENT (wrong for "DR Watson") - */ - pnhead->dacl = const_cpu_to_le32(0); - if (pphead->dacl) { - offpacl = le32_to_cpu(pphead->dacl); - ppacl = (const ACL*)&parentattr[offpacl]; - pnacl = (ACL*)&newattr[pos]; - aclsz = ntfs_inherit_acl(ppacl, pnacl, usid, gsid, fordir); - if (aclsz) { - pnhead->dacl = cpu_to_le32(pos); - pos += aclsz; - pnhead->control |= SE_DACL_PRESENT; - } - } - /* - * locate and inherit SACL - */ - pnhead->sacl = const_cpu_to_le32(0); - if (pphead->sacl) { - offpacl = le32_to_cpu(pphead->sacl); - ppacl = (const ACL*)&parentattr[offpacl]; - pnacl = (ACL*)&newattr[pos]; - aclsz = ntfs_inherit_acl(ppacl, pnacl, usid, gsid, fordir); - if (aclsz) { - pnhead->sacl = cpu_to_le32(pos); - pos += aclsz; - pnhead->control |= SE_SACL_PRESENT; - } - } - /* - * inherit or redefine owner - */ - memcpy(&newattr[pos],usid,usidsz); - pnhead->owner = cpu_to_le32(pos); - pos += usidsz; - /* - * inherit or redefine group - */ - memcpy(&newattr[pos],gsid,gsidsz); - pnhead->group = cpu_to_le32(pos); - pos += usidsz; - securid = setsecurityattr(scx->vol, - (SECURITY_DESCRIPTOR_RELATIVE*)newattr, pos); - free(newattr); - } else - securid = const_cpu_to_le32(0); - return (securid); + parentattrsz = ntfs_attr_size(parentattr); + pphead = (const SECURITY_DESCRIPTOR_RELATIVE*)parentattr; + if (scx->mapping[MAPUSERS]) { + usid = ntfs_find_usid(scx->mapping[MAPUSERS], scx->uid, (SID*)&defusid); + gsid = ntfs_find_gsid(scx->mapping[MAPGROUPS], scx->gid, (SID*)&defgsid); + if (!usid) + usid = adminsid; + if (!gsid) + gsid = adminsid; + } else { + /* + * If there is no user mapping, we have to copy owner + * and group from parent directory. + * Windows never has to do that, because it can always + * rely on a user mapping + */ + offowner = le32_to_cpu(pphead->owner); + usid = (const SID*)&parentattr[offowner]; + offgroup = le32_to_cpu(pphead->group); + gsid = (const SID*)&parentattr[offgroup]; + } + /* + * new attribute is smaller than parent's + * except for differences in SIDs which appear in + * owner, group and possible grants and denials in + * generic creator-owner and creator-group ACEs. + * For directories, an ACE may be duplicated for + * access and inheritance, so we double the count. + */ + usidsz = ntfs_sid_size(usid); + gsidsz = ntfs_sid_size(gsid); + newattrsz = parentattrsz + 3*usidsz + 3*gsidsz; + if (fordir) + newattrsz *= 2; + newattr = (char*)ntfs_malloc(newattrsz); + if (newattr) { + pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)newattr; + pnhead->revision = SECURITY_DESCRIPTOR_REVISION; + pnhead->alignment = 0; + pnhead->control = SE_SELF_RELATIVE; + pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); + /* + * locate and inherit DACL + * do not test SE_DACL_PRESENT (wrong for "DR Watson") + */ + pnhead->dacl = const_cpu_to_le32(0); + if (pphead->dacl) { + offpacl = le32_to_cpu(pphead->dacl); + ppacl = (const ACL*)&parentattr[offpacl]; + pnacl = (ACL*)&newattr[pos]; + aclsz = ntfs_inherit_acl(ppacl, pnacl, usid, gsid, fordir); + if (aclsz) { + pnhead->dacl = cpu_to_le32(pos); + pos += aclsz; + pnhead->control |= SE_DACL_PRESENT; + } + } + /* + * locate and inherit SACL + */ + pnhead->sacl = const_cpu_to_le32(0); + if (pphead->sacl) { + offpacl = le32_to_cpu(pphead->sacl); + ppacl = (const ACL*)&parentattr[offpacl]; + pnacl = (ACL*)&newattr[pos]; + aclsz = ntfs_inherit_acl(ppacl, pnacl, usid, gsid, fordir); + if (aclsz) { + pnhead->sacl = cpu_to_le32(pos); + pos += aclsz; + pnhead->control |= SE_SACL_PRESENT; + } + } + /* + * inherit or redefine owner + */ + memcpy(&newattr[pos],usid,usidsz); + pnhead->owner = cpu_to_le32(pos); + pos += usidsz; + /* + * inherit or redefine group + */ + memcpy(&newattr[pos],gsid,gsidsz); + pnhead->group = cpu_to_le32(pos); + pos += usidsz; + securid = setsecurityattr(scx->vol, + (SECURITY_DESCRIPTOR_RELATIVE*)newattr, pos); + free(newattr); + } else + securid = const_cpu_to_le32(0); + return (securid); } /* @@ -3627,48 +3670,49 @@ static le32 build_inherited_id(struct SECURITY_CONTEXT *scx, */ le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, - const char *dir_path, ntfs_inode *dir_ni, BOOL fordir) { - struct CACHED_PERMISSIONS *cached; - char *parentattr; - le32 securid; + const char *dir_path, ntfs_inode *dir_ni, BOOL fordir) +{ + struct CACHED_PERMISSIONS *cached; + char *parentattr; + le32 securid; - securid = const_cpu_to_le32(0); - cached = (struct CACHED_PERMISSIONS*)NULL; - /* - * Try to get inherited id from cache - */ - if (test_nino_flag(dir_ni, v3_Extensions) - && dir_ni->security_id) { - cached = fetch_cache(scx, dir_ni); - if (cached) - securid = (fordir ? cached->inh_dirid - : cached->inh_fileid); - } - /* - * Not cached or not available in cache, compute it all - * Note : if parent directory has no id, it is not cacheable - */ - if (!securid) { - parentattr = getsecurityattr(scx->vol, dir_path, dir_ni); - if (parentattr) { - securid = build_inherited_id(scx, - parentattr, fordir); - free(parentattr); - /* - * Store the result into cache for further use - */ - if (securid) { - cached = fetch_cache(scx, dir_ni); - if (cached) { - if (fordir) - cached->inh_dirid = securid; - else - cached->inh_fileid = securid; - } - } - } - } - return (securid); + securid = const_cpu_to_le32(0); + cached = (struct CACHED_PERMISSIONS*)NULL; + /* + * Try to get inherited id from cache + */ + if (test_nino_flag(dir_ni, v3_Extensions) + && dir_ni->security_id) { + cached = fetch_cache(scx, dir_ni); + if (cached) + securid = (fordir ? cached->inh_dirid + : cached->inh_fileid); + } + /* + * Not cached or not available in cache, compute it all + * Note : if parent directory has no id, it is not cacheable + */ + if (!securid) { + parentattr = getsecurityattr(scx->vol, dir_path, dir_ni); + if (parentattr) { + securid = build_inherited_id(scx, + parentattr, fordir); + free(parentattr); + /* + * Store the result into cache for further use + */ + if (securid) { + cached = fetch_cache(scx, dir_ni); + if (cached) { + if (fordir) + cached->inh_dirid = securid; + else + cached->inh_fileid = securid; + } + } + } + } + return (securid); } /* @@ -3678,38 +3722,39 @@ le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, */ static int link_single_group(struct MAPPING *usermapping, struct passwd *user, - gid_t gid) { - struct group *group; - char **grmem; - int grcnt; - gid_t *groups; - int res; + gid_t gid) +{ + struct group *group; + char **grmem; + int grcnt; + gid_t *groups; + int res; - res = 0; - group = getgrgid(gid); - if (group && group->gr_mem) { - grcnt = usermapping->grcnt; - groups = usermapping->groups; - grmem = group->gr_mem; - while (*grmem && strcmp(user->pw_name, *grmem)) - grmem++; - if (*grmem) { - if (!grcnt) - groups = (gid_t*)malloc(sizeof(gid_t)); - else - groups = (gid_t*)realloc(groups, - (grcnt+1)*sizeof(gid_t)); - if (groups) - groups[grcnt++] = gid; - else { - res = -1; - errno = ENOMEM; - } - } - usermapping->grcnt = grcnt; - usermapping->groups = groups; - } - return (res); + res = 0; + group = getgrgid(gid); + if (group && group->gr_mem) { + grcnt = usermapping->grcnt; + groups = usermapping->groups; + grmem = group->gr_mem; + while (*grmem && strcmp(user->pw_name, *grmem)) + grmem++; + if (*grmem) { + if (!grcnt) + groups = (gid_t*)malloc(sizeof(gid_t)); + else + groups = (gid_t*)realloc(groups, + (grcnt+1)*sizeof(gid_t)); + if (groups) + groups[grcnt++] = gid; + else { + res = -1; + errno = ENOMEM; + } + } + usermapping->grcnt = grcnt; + usermapping->groups = groups; + } + return (res); } @@ -3725,32 +3770,33 @@ static int link_single_group(struct MAPPING *usermapping, struct passwd *user, * */ -static int link_group_members(struct SECURITY_CONTEXT *scx) { - struct MAPPING *usermapping; - struct MAPPING *groupmapping; - struct passwd *user; - int res; +static int link_group_members(struct SECURITY_CONTEXT *scx) +{ + struct MAPPING *usermapping; + struct MAPPING *groupmapping; + struct passwd *user; + int res; - res = 0; - for (usermapping=scx->mapping[MAPUSERS]; usermapping && !res; - usermapping=usermapping->next) { - usermapping->grcnt = 0; - usermapping->groups = (gid_t*)NULL; - user = getpwuid(usermapping->xid); - if (user && user->pw_name) { - for (groupmapping=scx->mapping[MAPGROUPS]; - groupmapping && !res; - groupmapping=groupmapping->next) { - if (link_single_group(usermapping, user, - groupmapping->xid)) - res = -1; - } - if (!res && link_single_group(usermapping, - user, (gid_t)0)) - res = -1; - } - } - return (res); + res = 0; + for (usermapping=scx->mapping[MAPUSERS]; usermapping && !res; + usermapping=usermapping->next) { + usermapping->grcnt = 0; + usermapping->groups = (gid_t*)NULL; + user = getpwuid(usermapping->xid); + if (user && user->pw_name) { + for (groupmapping=scx->mapping[MAPGROUPS]; + groupmapping && !res; + groupmapping=groupmapping->next) { + if (link_single_group(usermapping, user, + groupmapping->xid)) + res = -1; + } + if (!res && link_single_group(usermapping, + user, (gid_t)0)) + res = -1; + } + } + return (res); } @@ -3760,35 +3806,36 @@ static int link_group_members(struct SECURITY_CONTEXT *scx) { */ static int ntfs_do_default_mapping(struct SECURITY_CONTEXT *scx, - const SID *usid) { - struct MAPPING *usermapping; - struct MAPPING *groupmapping; - SID *sid; - int sidsz; - int res; + const SID *usid) +{ + struct MAPPING *usermapping; + struct MAPPING *groupmapping; + SID *sid; + int sidsz; + int res; - res = -1; - sidsz = ntfs_sid_size(usid); - sid = (SID*)ntfs_malloc(sidsz); - if (sid) { - memcpy(sid,usid,sidsz); - usermapping = (struct MAPPING*)ntfs_malloc(sizeof(struct MAPPING)); - if (usermapping) { - groupmapping = (struct MAPPING*)ntfs_malloc(sizeof(struct MAPPING)); - if (groupmapping) { - usermapping->sid = sid; - usermapping->xid = scx->uid; - usermapping->next = (struct MAPPING*)NULL; - groupmapping->sid = sid; - groupmapping->xid = scx->uid; - groupmapping->next = (struct MAPPING*)NULL; - scx->mapping[MAPUSERS] = usermapping; - scx->mapping[MAPGROUPS] = groupmapping; - res = 0; - } - } - } - return (res); + res = -1; + sidsz = ntfs_sid_size(usid); + sid = (SID*)ntfs_malloc(sidsz); + if (sid) { + memcpy(sid,usid,sidsz); + usermapping = (struct MAPPING*)ntfs_malloc(sizeof(struct MAPPING)); + if (usermapping) { + groupmapping = (struct MAPPING*)ntfs_malloc(sizeof(struct MAPPING)); + if (groupmapping) { + usermapping->sid = sid; + usermapping->xid = scx->uid; + usermapping->next = (struct MAPPING*)NULL; + groupmapping->sid = sid; + groupmapping->xid = scx->uid; + groupmapping->next = (struct MAPPING*)NULL; + scx->mapping[MAPUSERS] = usermapping; + scx->mapping[MAPGROUPS] = groupmapping; + res = 0; + } + } + } + return (res); } @@ -3801,31 +3848,32 @@ static int ntfs_do_default_mapping(struct SECURITY_CONTEXT *scx, #if 0 /* not activated for now */ static BOOL check_mapping(const struct MAPPING *usermapping, - const struct MAPPING *groupmapping) { - const struct MAPPING *mapping1; - const struct MAPPING *mapping2; - BOOL ambiguous; + const struct MAPPING *groupmapping) +{ + const struct MAPPING *mapping1; + const struct MAPPING *mapping2; + BOOL ambiguous; - ambiguous = FALSE; - for (mapping1=usermapping; mapping1; mapping1=mapping1->next) - for (mapping2=mapping1->next; mapping2; mapping1=mapping2->next) - if (ntfs_same_sid(mapping1->sid,mapping2->sid)) { - if (mapping1->xid != mapping2->xid) - ambiguous = TRUE; - } else { - if (mapping1->xid == mapping2->xid) - ambiguous = TRUE; - } - for (mapping1=groupmapping; mapping1; mapping1=mapping1->next) - for (mapping2=mapping1->next; mapping2; mapping1=mapping2->next) - if (ntfs_same_sid(mapping1->sid,mapping2->sid)) { - if (mapping1->xid != mapping2->xid) - ambiguous = TRUE; - } else { - if (mapping1->xid == mapping2->xid) - ambiguous = TRUE; - } - return (ambiguous); + ambiguous = FALSE; + for (mapping1=usermapping; mapping1; mapping1=mapping1->next) + for (mapping2=mapping1->next; mapping2; mapping1=mapping2->next) + if (ntfs_same_sid(mapping1->sid,mapping2->sid)) { + if (mapping1->xid != mapping2->xid) + ambiguous = TRUE; + } else { + if (mapping1->xid == mapping2->xid) + ambiguous = TRUE; + } + for (mapping1=groupmapping; mapping1; mapping1=mapping1->next) + for (mapping2=mapping1->next; mapping2; mapping1=mapping2->next) + if (ntfs_same_sid(mapping1->sid,mapping2->sid)) { + if (mapping1->xid != mapping2->xid) + ambiguous = TRUE; + } else { + if (mapping1->xid == mapping2->xid) + ambiguous = TRUE; + } + return (ambiguous); } #endif @@ -3835,35 +3883,37 @@ static BOOL check_mapping(const struct MAPPING *usermapping, * returns zero if successful */ -static int ntfs_default_mapping(struct SECURITY_CONTEXT *scx) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - ntfs_inode *ni; - char *securattr; - const SID *usid; - int res; +static int ntfs_default_mapping(struct SECURITY_CONTEXT *scx) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + ntfs_inode *ni; + char *securattr; + const SID *usid; + int res; - res = -1; - ni = ntfs_pathname_to_inode(scx->vol, NULL, "/."); - if (ni) { - securattr = getsecurityattr(scx->vol,"/.",ni); - if (securattr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; - usid = (SID*)&securattr[le32_to_cpu(phead->owner)]; - if (ntfs_is_user_sid(usid)) - res = ntfs_do_default_mapping(scx,usid); - free(securattr); - } - ntfs_inode_close(ni); - } - return (res); + res = -1; + ni = ntfs_pathname_to_inode(scx->vol, NULL, "/."); + if (ni) { + securattr = getsecurityattr(scx->vol,"/.",ni); + if (securattr) { + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)securattr; + usid = (SID*)&securattr[le32_to_cpu(phead->owner)]; + if (ntfs_is_user_sid(usid)) + res = ntfs_do_default_mapping(scx,usid); + free(securattr); + } + ntfs_inode_close(ni); + } + return (res); } /* * Basic read from a user mapping file on another volume */ -static int basicread(void *fileid, char *buf, size_t size, off_t offs __attribute__((unused))) { - return (read(*(int*)fileid, buf, size)); +static int basicread(void *fileid, char *buf, size_t size, off_t offs __attribute__((unused))) +{ + return (read(*(int*)fileid, buf, size)); } @@ -3871,9 +3921,10 @@ static int basicread(void *fileid, char *buf, size_t size, off_t offs __attribut * Read from a user mapping file on current NTFS partition */ -static int localread(void *fileid, char *buf, size_t size, off_t offs) { - return (ntfs_local_read((ntfs_inode*)fileid, - AT_UNNAMED, 0, buf, size, offs)); +static int localread(void *fileid, char *buf, size_t size, off_t offs) +{ + return (ntfs_local_read((ntfs_inode*)fileid, + AT_UNNAMED, 0, buf, size, offs)); } /* @@ -3888,59 +3939,60 @@ static int localread(void *fileid, char *buf, size_t size, off_t offs) { * (failure should not be interpreted as an error) */ -int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path) { - struct MAPLIST *item; - struct MAPLIST *firstitem; - struct MAPPING *usermapping; - struct MAPPING *groupmapping; - ntfs_inode *ni; - int fd; +int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path) +{ + struct MAPLIST *item; + struct MAPLIST *firstitem; + struct MAPPING *usermapping; + struct MAPPING *groupmapping; + ntfs_inode *ni; + int fd; - /* be sure not to map anything until done */ - scx->mapping[MAPUSERS] = (struct MAPPING*)NULL; - scx->mapping[MAPGROUPS] = (struct MAPPING*)NULL; + /* be sure not to map anything until done */ + scx->mapping[MAPUSERS] = (struct MAPPING*)NULL; + scx->mapping[MAPGROUPS] = (struct MAPPING*)NULL; - if (!usermap_path) usermap_path = MAPPINGFILE; - if (usermap_path[0] == '/') { - fd = open(usermap_path,O_RDONLY); - if (fd > 0) { - firstitem = ntfs_read_mapping(basicread, (void*)&fd); - close(fd); - } else - firstitem = (struct MAPLIST*)NULL; - } else { - ni = ntfs_pathname_to_inode(scx->vol, NULL, usermap_path); - if (ni) { - firstitem = ntfs_read_mapping(localread, ni); - ntfs_inode_close(ni); - } else - firstitem = (struct MAPLIST*)NULL; - } + if (!usermap_path) usermap_path = MAPPINGFILE; + if (usermap_path[0] == '/') { + fd = open(usermap_path,O_RDONLY); + if (fd > 0) { + firstitem = ntfs_read_mapping(basicread, (void*)&fd); + close(fd); + } else + firstitem = (struct MAPLIST*)NULL; + } else { + ni = ntfs_pathname_to_inode(scx->vol, NULL, usermap_path); + if (ni) { + firstitem = ntfs_read_mapping(localread, ni); + ntfs_inode_close(ni); + } else + firstitem = (struct MAPLIST*)NULL; + } - if (firstitem) { - usermapping = ntfs_do_user_mapping(firstitem); - groupmapping = ntfs_do_group_mapping(firstitem); - if (usermapping && groupmapping) { - scx->mapping[MAPUSERS] = usermapping; - scx->mapping[MAPGROUPS] = groupmapping; - } else - ntfs_log_error("There were no valid user or no valid group\n"); - /* now we can free the memory copy of input text */ - /* and rely on internal representation */ - while (firstitem) { - item = firstitem->next; - free(firstitem); - firstitem = item; - } - } else { - /* no mapping file, try default mapping */ - if (scx->uid && scx->gid) { - if (!ntfs_default_mapping(scx)) - ntfs_log_info("Using default user mapping\n"); - } - } - return (!scx->mapping[MAPUSERS] || link_group_members(scx)); + if (firstitem) { + usermapping = ntfs_do_user_mapping(firstitem); + groupmapping = ntfs_do_group_mapping(firstitem); + if (usermapping && groupmapping) { + scx->mapping[MAPUSERS] = usermapping; + scx->mapping[MAPGROUPS] = groupmapping; + } else + ntfs_log_error("There were no valid user or no valid group\n"); + /* now we can free the memory copy of input text */ + /* and rely on internal representation */ + while (firstitem) { + item = firstitem->next; + free(firstitem); + firstitem = item; + } + } else { + /* no mapping file, try default mapping */ + if (scx->uid && scx->gid) { + if (!ntfs_default_mapping(scx)) + ntfs_log_info("Using default user mapping\n"); + } + } + return (!scx->mapping[MAPUSERS] || link_group_members(scx)); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -3951,28 +4003,29 @@ int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path) { */ int ntfs_get_ntfs_attrib(const char *path __attribute__((unused)), - char *value, size_t size, ntfs_inode *ni) { - u32 attrib; - size_t outsize; + char *value, size_t size, ntfs_inode *ni) +{ + u32 attrib; + size_t outsize; - outsize = 0; /* default to no data and no error */ - if (ni) { - attrib = le32_to_cpu(ni->flags); - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - attrib |= const_le32_to_cpu(FILE_ATTR_DIRECTORY); - else - attrib &= ~const_le32_to_cpu(FILE_ATTR_DIRECTORY); - if (!attrib) - attrib |= const_le32_to_cpu(FILE_ATTR_NORMAL); - outsize = sizeof(FILE_ATTR_FLAGS); - if (size >= outsize) { - if (value) - memcpy(value,&attrib,outsize); - else - errno = EINVAL; - } - } - return (outsize ? (int)outsize : -errno); + outsize = 0; /* default to no data and no error */ + if (ni) { + attrib = le32_to_cpu(ni->flags); + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + attrib |= const_le32_to_cpu(FILE_ATTR_DIRECTORY); + else + attrib &= ~const_le32_to_cpu(FILE_ATTR_DIRECTORY); + if (!attrib) + attrib |= const_le32_to_cpu(FILE_ATTR_NORMAL); + outsize = sizeof(FILE_ATTR_FLAGS); + if (size >= outsize) { + if (value) + memcpy(value,&attrib,outsize); + else + errno = EINVAL; + } + } + return (outsize ? (int)outsize : -errno); } /* @@ -3983,49 +4036,50 @@ int ntfs_get_ntfs_attrib(const char *path __attribute__((unused)), */ int ntfs_set_ntfs_attrib(const char *path __attribute__((unused)), - const char *value, size_t size, int flags, - ntfs_inode *ni) { - u32 attrib; - le32 settable; - ATTR_FLAGS dirflags; - int res; + const char *value, size_t size, int flags, + ntfs_inode *ni) +{ + u32 attrib; + le32 settable; + ATTR_FLAGS dirflags; + int res; - res = -1; - if (ni && value && (size >= sizeof(FILE_ATTR_FLAGS))) { - if (!(flags & XATTR_CREATE)) { - /* copy to avoid alignment problems */ - memcpy(&attrib,value,sizeof(FILE_ATTR_FLAGS)); - settable = FILE_ATTR_SETTABLE; - res = 0; - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - /* - * Accept changing compression for a directory - * and set index root accordingly - */ - settable |= FILE_ATTR_COMPRESSED; - if ((ni->flags ^ cpu_to_le32(attrib)) - & FILE_ATTR_COMPRESSED) { - if (ni->flags & FILE_ATTR_COMPRESSED) - dirflags = const_cpu_to_le16(0); - else - dirflags = ATTR_IS_COMPRESSED; - res = ntfs_attr_set_flags(ni, - AT_INDEX_ROOT, - NTFS_INDEX_I30, 4, - dirflags, - ATTR_COMPRESSION_MASK); - } - } - if (!res) { - ni->flags = (ni->flags & ~settable) - | (cpu_to_le32(attrib) & settable); - NInoSetDirty(ni); - } - } else - errno = EEXIST; - } else - errno = EINVAL; - return (res ? -1 : 0); + res = -1; + if (ni && value && (size >= sizeof(FILE_ATTR_FLAGS))) { + if (!(flags & XATTR_CREATE)) { + /* copy to avoid alignment problems */ + memcpy(&attrib,value,sizeof(FILE_ATTR_FLAGS)); + settable = FILE_ATTR_SETTABLE; + res = 0; + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { + /* + * Accept changing compression for a directory + * and set index root accordingly + */ + settable |= FILE_ATTR_COMPRESSED; + if ((ni->flags ^ cpu_to_le32(attrib)) + & FILE_ATTR_COMPRESSED) { + if (ni->flags & FILE_ATTR_COMPRESSED) + dirflags = const_cpu_to_le16(0); + else + dirflags = ATTR_IS_COMPRESSED; + res = ntfs_attr_set_flags(ni, + AT_INDEX_ROOT, + NTFS_INDEX_I30, 4, + dirflags, + ATTR_COMPRESSION_MASK); + } + } + if (!res) { + ni->flags = (ni->flags & ~settable) + | (cpu_to_le32(attrib) & settable); + NInoSetDirty(ni); + } + } else + errno = EEXIST; + } else + errno = EINVAL; + return (res ? -1 : 0); } #endif /* HAVE_SETXATTR */ @@ -4037,30 +4091,31 @@ int ntfs_set_ntfs_attrib(const char *path __attribute__((unused)), */ -int ntfs_open_secure(ntfs_volume *vol) { - ntfs_inode *ni; - int res; +int ntfs_open_secure(ntfs_volume *vol) +{ + ntfs_inode *ni; + int res; - res = -1; - vol->secure_ni = (ntfs_inode*)NULL; - vol->secure_xsii = (ntfs_index_context*)NULL; - vol->secure_xsdh = (ntfs_index_context*)NULL; - if (vol->major_ver >= 3) { - /* make sure this is a genuine $Secure inode 9 */ - ni = ntfs_pathname_to_inode(vol, NULL, "$Secure"); - if (ni && (ni->mft_no == 9)) { - vol->secure_reentry = 0; - vol->secure_xsii = ntfs_index_ctx_get(ni, - sii_stream, 4); - vol->secure_xsdh = ntfs_index_ctx_get(ni, - sdh_stream, 4); - if (ni && vol->secure_xsii && vol->secure_xsdh) { - vol->secure_ni = ni; - res = 0; - } - } - } - return (res); + res = -1; + vol->secure_ni = (ntfs_inode*)NULL; + vol->secure_xsii = (ntfs_index_context*)NULL; + vol->secure_xsdh = (ntfs_index_context*)NULL; + if (vol->major_ver >= 3) { + /* make sure this is a genuine $Secure inode 9 */ + ni = ntfs_pathname_to_inode(vol, NULL, "$Secure"); + if (ni && (ni->mft_no == 9)) { + vol->secure_reentry = 0; + vol->secure_xsii = ntfs_index_ctx_get(ni, + sii_stream, 4); + vol->secure_xsdh = ntfs_index_ctx_get(ni, + sdh_stream, 4); + if (ni && vol->secure_xsii && vol->secure_xsdh) { + vol->secure_ni = ni; + res = 0; + } + } + } + return (res); } /* @@ -4068,18 +4123,19 @@ int ntfs_open_secure(ntfs_volume *vol) { * Allocated memory is freed to facilitate the detection of memory leaks */ -void ntfs_close_secure(struct SECURITY_CONTEXT *scx) { - ntfs_volume *vol; +void ntfs_close_secure(struct SECURITY_CONTEXT *scx) +{ + ntfs_volume *vol; - vol = scx->vol; - if (vol->secure_ni) { - ntfs_index_ctx_put(vol->secure_xsii); - ntfs_index_ctx_put(vol->secure_xsdh); - ntfs_inode_close(vol->secure_ni); - - } - ntfs_free_mapping(scx->mapping); - free_caches(scx); + vol = scx->vol; + if (vol->secure_ni) { + ntfs_index_ctx_put(vol->secure_xsii); + ntfs_index_ctx_put(vol->secure_xsdh); + ntfs_inode_close(vol->secure_ni); + + } + ntfs_free_mapping(scx->mapping); + free_caches(scx); } /* @@ -4095,147 +4151,148 @@ void ntfs_close_secure(struct SECURITY_CONTEXT *scx) { */ static BOOL feedsecurityattr(const char *attr, u32 selection, - char *buf, u32 buflen, u32 *psize) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - SECURITY_DESCRIPTOR_RELATIVE *pnhead; - const ACL *pdacl; - const ACL *psacl; - const SID *pusid; - const SID *pgsid; - unsigned int offdacl; - unsigned int offsacl; - unsigned int offowner; - unsigned int offgroup; - unsigned int daclsz; - unsigned int saclsz; - unsigned int usidsz; - unsigned int gsidsz; - unsigned int size; /* size of requested attributes */ - BOOL ok; - unsigned int pos; - unsigned int avail; - le16 control; + char *buf, u32 buflen, u32 *psize) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + SECURITY_DESCRIPTOR_RELATIVE *pnhead; + const ACL *pdacl; + const ACL *psacl; + const SID *pusid; + const SID *pgsid; + unsigned int offdacl; + unsigned int offsacl; + unsigned int offowner; + unsigned int offgroup; + unsigned int daclsz; + unsigned int saclsz; + unsigned int usidsz; + unsigned int gsidsz; + unsigned int size; /* size of requested attributes */ + BOOL ok; + unsigned int pos; + unsigned int avail; + le16 control; - avail = 0; - control = SE_SELF_RELATIVE; - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; - size = sizeof(SECURITY_DESCRIPTOR_RELATIVE); + avail = 0; + control = SE_SELF_RELATIVE; + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; + size = sizeof(SECURITY_DESCRIPTOR_RELATIVE); - /* locate DACL if requested and available */ - if (phead->dacl && (selection & DACL_SECURITY_INFORMATION)) { - offdacl = le32_to_cpu(phead->dacl); - pdacl = (const ACL*)&attr[offdacl]; - daclsz = le16_to_cpu(pdacl->size); - size += daclsz; - avail |= DACL_SECURITY_INFORMATION; - } else - offdacl = daclsz = 0; + /* locate DACL if requested and available */ + if (phead->dacl && (selection & DACL_SECURITY_INFORMATION)) { + offdacl = le32_to_cpu(phead->dacl); + pdacl = (const ACL*)&attr[offdacl]; + daclsz = le16_to_cpu(pdacl->size); + size += daclsz; + avail |= DACL_SECURITY_INFORMATION; + } else + offdacl = daclsz = 0; - /* locate owner if requested and available */ - offowner = le32_to_cpu(phead->owner); - if (offowner && (selection & OWNER_SECURITY_INFORMATION)) { - /* find end of USID */ - pusid = (const SID*)&attr[offowner]; - usidsz = ntfs_sid_size(pusid); - size += usidsz; - avail |= OWNER_SECURITY_INFORMATION; - } else - offowner = usidsz = 0; + /* locate owner if requested and available */ + offowner = le32_to_cpu(phead->owner); + if (offowner && (selection & OWNER_SECURITY_INFORMATION)) { + /* find end of USID */ + pusid = (const SID*)&attr[offowner]; + usidsz = ntfs_sid_size(pusid); + size += usidsz; + avail |= OWNER_SECURITY_INFORMATION; + } else + offowner = usidsz = 0; - /* locate group if requested and available */ - offgroup = le32_to_cpu(phead->group); - if (offgroup && (selection & GROUP_SECURITY_INFORMATION)) { - /* find end of GSID */ - pgsid = (const SID*)&attr[offgroup]; - gsidsz = ntfs_sid_size(pgsid); - size += gsidsz; - avail |= GROUP_SECURITY_INFORMATION; - } else - offgroup = gsidsz = 0; + /* locate group if requested and available */ + offgroup = le32_to_cpu(phead->group); + if (offgroup && (selection & GROUP_SECURITY_INFORMATION)) { + /* find end of GSID */ + pgsid = (const SID*)&attr[offgroup]; + gsidsz = ntfs_sid_size(pgsid); + size += gsidsz; + avail |= GROUP_SECURITY_INFORMATION; + } else + offgroup = gsidsz = 0; - /* locate SACL if requested and available */ - if (phead->sacl && (selection & SACL_SECURITY_INFORMATION)) { - /* find end of SACL */ - offsacl = le32_to_cpu(phead->sacl); - psacl = (const ACL*)&attr[offsacl]; - saclsz = le16_to_cpu(psacl->size); - size += saclsz; - avail |= SACL_SECURITY_INFORMATION; - } else - offsacl = saclsz = 0; + /* locate SACL if requested and available */ + if (phead->sacl && (selection & SACL_SECURITY_INFORMATION)) { + /* find end of SACL */ + offsacl = le32_to_cpu(phead->sacl); + psacl = (const ACL*)&attr[offsacl]; + saclsz = le16_to_cpu(psacl->size); + size += saclsz; + avail |= SACL_SECURITY_INFORMATION; + } else + offsacl = saclsz = 0; - /* - * Check having enough size in destination buffer - * (required size is returned nevertheless so that - * the request can be reissued with adequate size) - */ - if (size > buflen) { - *psize = size; - errno = EINVAL; - ok = FALSE; - } else { - if (selection & OWNER_SECURITY_INFORMATION) - control |= phead->control & SE_OWNER_DEFAULTED; - if (selection & GROUP_SECURITY_INFORMATION) - control |= phead->control & SE_GROUP_DEFAULTED; - if (selection & DACL_SECURITY_INFORMATION) - control |= phead->control - & (SE_DACL_PRESENT - | SE_DACL_DEFAULTED - | SE_DACL_AUTO_INHERITED - | SE_DACL_PROTECTED); - if (selection & SACL_SECURITY_INFORMATION) - control |= phead->control - & (SE_SACL_PRESENT - | SE_SACL_DEFAULTED - | SE_SACL_AUTO_INHERITED - | SE_SACL_PROTECTED); - /* - * copy header and feed new flags, even if no detailed data - */ - memcpy(buf,attr,sizeof(SECURITY_DESCRIPTOR_RELATIVE)); - pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)buf; - pnhead->control = control; - pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); + /* + * Check having enough size in destination buffer + * (required size is returned nevertheless so that + * the request can be reissued with adequate size) + */ + if (size > buflen) { + *psize = size; + errno = EINVAL; + ok = FALSE; + } else { + if (selection & OWNER_SECURITY_INFORMATION) + control |= phead->control & SE_OWNER_DEFAULTED; + if (selection & GROUP_SECURITY_INFORMATION) + control |= phead->control & SE_GROUP_DEFAULTED; + if (selection & DACL_SECURITY_INFORMATION) + control |= phead->control + & (SE_DACL_PRESENT + | SE_DACL_DEFAULTED + | SE_DACL_AUTO_INHERITED + | SE_DACL_PROTECTED); + if (selection & SACL_SECURITY_INFORMATION) + control |= phead->control + & (SE_SACL_PRESENT + | SE_SACL_DEFAULTED + | SE_SACL_AUTO_INHERITED + | SE_SACL_PROTECTED); + /* + * copy header and feed new flags, even if no detailed data + */ + memcpy(buf,attr,sizeof(SECURITY_DESCRIPTOR_RELATIVE)); + pnhead = (SECURITY_DESCRIPTOR_RELATIVE*)buf; + pnhead->control = control; + pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); - /* copy DACL if requested and available */ - if (selection & avail & DACL_SECURITY_INFORMATION) { - pnhead->dacl = cpu_to_le32(pos); - memcpy(&buf[pos],&attr[offdacl],daclsz); - pos += daclsz; - } else - pnhead->dacl = const_cpu_to_le32(0); + /* copy DACL if requested and available */ + if (selection & avail & DACL_SECURITY_INFORMATION) { + pnhead->dacl = cpu_to_le32(pos); + memcpy(&buf[pos],&attr[offdacl],daclsz); + pos += daclsz; + } else + pnhead->dacl = const_cpu_to_le32(0); - /* copy SACL if requested and available */ - if (selection & avail & SACL_SECURITY_INFORMATION) { - pnhead->sacl = cpu_to_le32(pos); - memcpy(&buf[pos],&attr[offsacl],saclsz); - pos += saclsz; - } else - pnhead->sacl = const_cpu_to_le32(0); + /* copy SACL if requested and available */ + if (selection & avail & SACL_SECURITY_INFORMATION) { + pnhead->sacl = cpu_to_le32(pos); + memcpy(&buf[pos],&attr[offsacl],saclsz); + pos += saclsz; + } else + pnhead->sacl = const_cpu_to_le32(0); - /* copy owner if requested and available */ - if (selection & avail & OWNER_SECURITY_INFORMATION) { - pnhead->owner = cpu_to_le32(pos); - memcpy(&buf[pos],&attr[offowner],usidsz); - pos += usidsz; - } else - pnhead->owner = const_cpu_to_le32(0); + /* copy owner if requested and available */ + if (selection & avail & OWNER_SECURITY_INFORMATION) { + pnhead->owner = cpu_to_le32(pos); + memcpy(&buf[pos],&attr[offowner],usidsz); + pos += usidsz; + } else + pnhead->owner = const_cpu_to_le32(0); - /* copy group if requested and available */ - if (selection & avail & GROUP_SECURITY_INFORMATION) { - pnhead->group = cpu_to_le32(pos); - memcpy(&buf[pos],&attr[offgroup],gsidsz); - pos += gsidsz; - } else - pnhead->group = const_cpu_to_le32(0); - if (pos != size) - ntfs_log_error("Error in security descriptor size\n"); - *psize = size; - ok = TRUE; - } + /* copy group if requested and available */ + if (selection & avail & GROUP_SECURITY_INFORMATION) { + pnhead->group = cpu_to_le32(pos); + memcpy(&buf[pos],&attr[offgroup],gsidsz); + pos += gsidsz; + } else + pnhead->group = const_cpu_to_le32(0); + if (pos != size) + ntfs_log_error("Error in security descriptor size\n"); + *psize = size; + ok = TRUE; + } - return (ok); + return (ok); } /* @@ -4246,157 +4303,158 @@ static BOOL feedsecurityattr(const char *attr, u32 selection, */ static BOOL mergesecurityattr(ntfs_volume *vol, const char *oldattr, - const char *newattr, u32 selection, ntfs_inode *ni) { - const SECURITY_DESCRIPTOR_RELATIVE *oldhead; - const SECURITY_DESCRIPTOR_RELATIVE *newhead; - SECURITY_DESCRIPTOR_RELATIVE *targhead; - const ACL *pdacl; - const ACL *psacl; - const SID *powner; - const SID *pgroup; - int offdacl; - int offsacl; - int offowner; - int offgroup; - unsigned int size; - le16 control; - char *target; - int pos; - int oldattrsz; - int newattrsz; - BOOL ok; + const char *newattr, u32 selection, ntfs_inode *ni) +{ + const SECURITY_DESCRIPTOR_RELATIVE *oldhead; + const SECURITY_DESCRIPTOR_RELATIVE *newhead; + SECURITY_DESCRIPTOR_RELATIVE *targhead; + const ACL *pdacl; + const ACL *psacl; + const SID *powner; + const SID *pgroup; + int offdacl; + int offsacl; + int offowner; + int offgroup; + unsigned int size; + le16 control; + char *target; + int pos; + int oldattrsz; + int newattrsz; + BOOL ok; - ok = FALSE; /* default return */ - oldhead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; - newhead = (const SECURITY_DESCRIPTOR_RELATIVE*)newattr; - oldattrsz = ntfs_attr_size(oldattr); - newattrsz = ntfs_attr_size(newattr); - target = (char*)ntfs_malloc(oldattrsz + newattrsz); - if (target) { - targhead = (SECURITY_DESCRIPTOR_RELATIVE*)target; - pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); - control = SE_SELF_RELATIVE; - /* - * copy new DACL if selected - * or keep old DACL if any - */ - if ((selection & DACL_SECURITY_INFORMATION) ? - newhead->dacl : oldhead->dacl) { - if (selection & DACL_SECURITY_INFORMATION) { - offdacl = le32_to_cpu(newhead->dacl); - pdacl = (const ACL*)&newattr[offdacl]; - } else { - offdacl = le32_to_cpu(oldhead->dacl); - pdacl = (const ACL*)&oldattr[offdacl]; - } - size = le16_to_cpu(pdacl->size); - memcpy(&target[pos], pdacl, size); - targhead->dacl = cpu_to_le32(pos); - pos += size; - } else - targhead->dacl = const_cpu_to_le32(0); - if (selection & DACL_SECURITY_INFORMATION) { - control |= newhead->control - & (SE_DACL_PRESENT - | SE_DACL_DEFAULTED - | SE_DACL_PROTECTED); - if (newhead->control & SE_DACL_AUTO_INHERIT_REQ) - control |= SE_DACL_AUTO_INHERITED; - } else - control |= oldhead->control - & (SE_DACL_PRESENT - | SE_DACL_DEFAULTED - | SE_DACL_AUTO_INHERITED - | SE_DACL_PROTECTED); - /* - * copy new SACL if selected - * or keep old SACL if any - */ - if ((selection & SACL_SECURITY_INFORMATION) ? - newhead->sacl : oldhead->sacl) { - if (selection & SACL_SECURITY_INFORMATION) { - offsacl = le32_to_cpu(newhead->sacl); - psacl = (const ACL*)&newattr[offsacl]; - } else { - offsacl = le32_to_cpu(oldhead->sacl); - psacl = (const ACL*)&oldattr[offsacl]; - } - size = le16_to_cpu(psacl->size); - memcpy(&target[pos], psacl, size); - targhead->sacl = cpu_to_le32(pos); - pos += size; - } else - targhead->sacl = const_cpu_to_le32(0); - if (selection & SACL_SECURITY_INFORMATION) { - control |= newhead->control - & (SE_SACL_PRESENT - | SE_SACL_DEFAULTED - | SE_SACL_PROTECTED); - if (newhead->control & SE_SACL_AUTO_INHERIT_REQ) - control |= SE_SACL_AUTO_INHERITED; - } else - control |= oldhead->control - & (SE_SACL_PRESENT - | SE_SACL_DEFAULTED - | SE_SACL_AUTO_INHERITED - | SE_SACL_PROTECTED); - /* - * copy new OWNER if selected - * or keep old OWNER if any - */ - if ((selection & OWNER_SECURITY_INFORMATION) ? - newhead->owner : oldhead->owner) { - if (selection & OWNER_SECURITY_INFORMATION) { - offowner = le32_to_cpu(newhead->owner); - powner = (const SID*)&newattr[offowner]; - } else { - offowner = le32_to_cpu(oldhead->owner); - powner = (const SID*)&oldattr[offowner]; - } - size = ntfs_sid_size(powner); - memcpy(&target[pos], powner, size); - targhead->owner = cpu_to_le32(pos); - pos += size; - } else - targhead->owner = const_cpu_to_le32(0); - if (selection & OWNER_SECURITY_INFORMATION) - control |= newhead->control & SE_OWNER_DEFAULTED; - else - control |= oldhead->control & SE_OWNER_DEFAULTED; - /* - * copy new GROUP if selected - * or keep old GROUP if any - */ - if ((selection & GROUP_SECURITY_INFORMATION) ? - newhead->group : oldhead->group) { - if (selection & GROUP_SECURITY_INFORMATION) { - offgroup = le32_to_cpu(newhead->group); - pgroup = (const SID*)&newattr[offgroup]; - control |= newhead->control - & SE_GROUP_DEFAULTED; - } else { - offgroup = le32_to_cpu(oldhead->group); - pgroup = (const SID*)&oldattr[offgroup]; - control |= oldhead->control - & SE_GROUP_DEFAULTED; - } - size = ntfs_sid_size(pgroup); - memcpy(&target[pos], pgroup, size); - targhead->group = cpu_to_le32(pos); - pos += size; - } else - targhead->group = const_cpu_to_le32(0); - if (selection & GROUP_SECURITY_INFORMATION) - control |= newhead->control & SE_GROUP_DEFAULTED; - else - control |= oldhead->control & SE_GROUP_DEFAULTED; - targhead->revision = SECURITY_DESCRIPTOR_REVISION; - targhead->alignment = 0; - targhead->control = control; - ok = !update_secur_descr(vol, target, ni); - free(target); - } - return (ok); + ok = FALSE; /* default return */ + oldhead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; + newhead = (const SECURITY_DESCRIPTOR_RELATIVE*)newattr; + oldattrsz = ntfs_attr_size(oldattr); + newattrsz = ntfs_attr_size(newattr); + target = (char*)ntfs_malloc(oldattrsz + newattrsz); + if (target) { + targhead = (SECURITY_DESCRIPTOR_RELATIVE*)target; + pos = sizeof(SECURITY_DESCRIPTOR_RELATIVE); + control = SE_SELF_RELATIVE; + /* + * copy new DACL if selected + * or keep old DACL if any + */ + if ((selection & DACL_SECURITY_INFORMATION) ? + newhead->dacl : oldhead->dacl) { + if (selection & DACL_SECURITY_INFORMATION) { + offdacl = le32_to_cpu(newhead->dacl); + pdacl = (const ACL*)&newattr[offdacl]; + } else { + offdacl = le32_to_cpu(oldhead->dacl); + pdacl = (const ACL*)&oldattr[offdacl]; + } + size = le16_to_cpu(pdacl->size); + memcpy(&target[pos], pdacl, size); + targhead->dacl = cpu_to_le32(pos); + pos += size; + } else + targhead->dacl = const_cpu_to_le32(0); + if (selection & DACL_SECURITY_INFORMATION) { + control |= newhead->control + & (SE_DACL_PRESENT + | SE_DACL_DEFAULTED + | SE_DACL_PROTECTED); + if (newhead->control & SE_DACL_AUTO_INHERIT_REQ) + control |= SE_DACL_AUTO_INHERITED; + } else + control |= oldhead->control + & (SE_DACL_PRESENT + | SE_DACL_DEFAULTED + | SE_DACL_AUTO_INHERITED + | SE_DACL_PROTECTED); + /* + * copy new SACL if selected + * or keep old SACL if any + */ + if ((selection & SACL_SECURITY_INFORMATION) ? + newhead->sacl : oldhead->sacl) { + if (selection & SACL_SECURITY_INFORMATION) { + offsacl = le32_to_cpu(newhead->sacl); + psacl = (const ACL*)&newattr[offsacl]; + } else { + offsacl = le32_to_cpu(oldhead->sacl); + psacl = (const ACL*)&oldattr[offsacl]; + } + size = le16_to_cpu(psacl->size); + memcpy(&target[pos], psacl, size); + targhead->sacl = cpu_to_le32(pos); + pos += size; + } else + targhead->sacl = const_cpu_to_le32(0); + if (selection & SACL_SECURITY_INFORMATION) { + control |= newhead->control + & (SE_SACL_PRESENT + | SE_SACL_DEFAULTED + | SE_SACL_PROTECTED); + if (newhead->control & SE_SACL_AUTO_INHERIT_REQ) + control |= SE_SACL_AUTO_INHERITED; + } else + control |= oldhead->control + & (SE_SACL_PRESENT + | SE_SACL_DEFAULTED + | SE_SACL_AUTO_INHERITED + | SE_SACL_PROTECTED); + /* + * copy new OWNER if selected + * or keep old OWNER if any + */ + if ((selection & OWNER_SECURITY_INFORMATION) ? + newhead->owner : oldhead->owner) { + if (selection & OWNER_SECURITY_INFORMATION) { + offowner = le32_to_cpu(newhead->owner); + powner = (const SID*)&newattr[offowner]; + } else { + offowner = le32_to_cpu(oldhead->owner); + powner = (const SID*)&oldattr[offowner]; + } + size = ntfs_sid_size(powner); + memcpy(&target[pos], powner, size); + targhead->owner = cpu_to_le32(pos); + pos += size; + } else + targhead->owner = const_cpu_to_le32(0); + if (selection & OWNER_SECURITY_INFORMATION) + control |= newhead->control & SE_OWNER_DEFAULTED; + else + control |= oldhead->control & SE_OWNER_DEFAULTED; + /* + * copy new GROUP if selected + * or keep old GROUP if any + */ + if ((selection & GROUP_SECURITY_INFORMATION) ? + newhead->group : oldhead->group) { + if (selection & GROUP_SECURITY_INFORMATION) { + offgroup = le32_to_cpu(newhead->group); + pgroup = (const SID*)&newattr[offgroup]; + control |= newhead->control + & SE_GROUP_DEFAULTED; + } else { + offgroup = le32_to_cpu(oldhead->group); + pgroup = (const SID*)&oldattr[offgroup]; + control |= oldhead->control + & SE_GROUP_DEFAULTED; + } + size = ntfs_sid_size(pgroup); + memcpy(&target[pos], pgroup, size); + targhead->group = cpu_to_le32(pos); + pos += size; + } else + targhead->group = const_cpu_to_le32(0); + if (selection & GROUP_SECURITY_INFORMATION) + control |= newhead->control & SE_GROUP_DEFAULTED; + else + control |= oldhead->control & SE_GROUP_DEFAULTED; + targhead->revision = SECURITY_DESCRIPTOR_REVISION; + targhead->alignment = 0; + targhead->control = control; + ok = !update_secur_descr(vol, target, ni); + free(target); + } + return (ok); } /* @@ -4421,36 +4479,37 @@ static BOOL mergesecurityattr(ntfs_volume *vol, const char *oldattr, */ int ntfs_get_file_security(struct SECURITY_API *scapi, - const char *path, u32 selection, - char *buf, u32 buflen, u32 *psize) { - ntfs_inode *ni; - char *attr; - int res; + const char *path, u32 selection, + char *buf, u32 buflen, u32 *psize) +{ + ntfs_inode *ni; + char *attr; + int res; - res = 0; /* default return */ - if (scapi && (scapi->magic == MAGIC_API)) { - ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); - if (ni) { - attr = getsecurityattr(scapi->security.vol, path, ni); - if (attr) { - if (feedsecurityattr(attr,selection, - buf,buflen,psize)) { - if (test_nino_flag(ni, v3_Extensions) - && ni->security_id) - res = le32_to_cpu( - ni->security_id); - else - res = -1; - } - free(attr); - } - ntfs_inode_close(ni); - } else - errno = ENOENT; - if (!res) *psize = 0; - } else - errno = EINVAL; /* do not clear *psize */ - return (res); + res = 0; /* default return */ + if (scapi && (scapi->magic == MAGIC_API)) { + ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); + if (ni) { + attr = getsecurityattr(scapi->security.vol, path, ni); + if (attr) { + if (feedsecurityattr(attr,selection, + buf,buflen,psize)) { + if (test_nino_flag(ni, v3_Extensions) + && ni->security_id) + res = le32_to_cpu( + ni->security_id); + else + res = -1; + } + free(attr); + } + ntfs_inode_close(ni); + } else + errno = ENOENT; + if (!res) *psize = 0; + } else + errno = EINVAL; /* do not clear *psize */ + return (res); } @@ -4473,54 +4532,55 @@ int ntfs_get_file_security(struct SECURITY_API *scapi, */ int ntfs_set_file_security(struct SECURITY_API *scapi, - const char *path, u32 selection, const char *attr) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - ntfs_inode *ni; - int attrsz; - BOOL missing; - char *oldattr; - int res; + const char *path, u32 selection, const char *attr) +{ + const SECURITY_DESCRIPTOR_RELATIVE *phead; + ntfs_inode *ni; + int attrsz; + BOOL missing; + char *oldattr; + int res; - res = 0; /* default return */ - if (scapi && (scapi->magic == MAGIC_API) && attr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; - attrsz = ntfs_attr_size(attr); - /* if selected, owner and group must be present or defaulted */ - missing = ((selection & OWNER_SECURITY_INFORMATION) - && !phead->owner - && !(phead->control & SE_OWNER_DEFAULTED)) - || ((selection & GROUP_SECURITY_INFORMATION) - && !phead->group - && !(phead->control & SE_GROUP_DEFAULTED)); - if (!missing - && (phead->control & SE_SELF_RELATIVE) - && ntfs_valid_descr(attr, attrsz)) { - ni = ntfs_pathname_to_inode(scapi->security.vol, - NULL, path); - if (ni) { - oldattr = getsecurityattr(scapi->security.vol, - path, ni); - if (oldattr) { - if (mergesecurityattr( - scapi->security.vol, - oldattr, attr, - selection, ni)) { - if (test_nino_flag(ni, - v3_Extensions)) - res = le32_to_cpu( - ni->security_id); - else - res = -1; - } - free(oldattr); - } - ntfs_inode_close(ni); - } - } else - errno = EINVAL; - } else - errno = EINVAL; - return (res); + res = 0; /* default return */ + if (scapi && (scapi->magic == MAGIC_API) && attr) { + phead = (const SECURITY_DESCRIPTOR_RELATIVE*)attr; + attrsz = ntfs_attr_size(attr); + /* if selected, owner and group must be present or defaulted */ + missing = ((selection & OWNER_SECURITY_INFORMATION) + && !phead->owner + && !(phead->control & SE_OWNER_DEFAULTED)) + || ((selection & GROUP_SECURITY_INFORMATION) + && !phead->group + && !(phead->control & SE_GROUP_DEFAULTED)); + if (!missing + && (phead->control & SE_SELF_RELATIVE) + && ntfs_valid_descr(attr, attrsz)) { + ni = ntfs_pathname_to_inode(scapi->security.vol, + NULL, path); + if (ni) { + oldattr = getsecurityattr(scapi->security.vol, + path, ni); + if (oldattr) { + if (mergesecurityattr( + scapi->security.vol, + oldattr, attr, + selection, ni)) { + if (test_nino_flag(ni, + v3_Extensions)) + res = le32_to_cpu( + ni->security_id); + else + res = -1; + } + free(oldattr); + } + ntfs_inode_close(ni); + } + } else + errno = EINVAL; + } else + errno = EINVAL; + return (res); } @@ -4538,28 +4598,29 @@ int ntfs_set_file_security(struct SECURITY_API *scapi, * ); */ -int ntfs_get_file_attributes(struct SECURITY_API *scapi, const char *path) { - ntfs_inode *ni; - s32 attrib; +int ntfs_get_file_attributes(struct SECURITY_API *scapi, const char *path) +{ + ntfs_inode *ni; + s32 attrib; - attrib = -1; /* default return */ - if (scapi && (scapi->magic == MAGIC_API) && path) { - ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); - if (ni) { - attrib = le32_to_cpu(ni->flags); - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - attrib |= const_le32_to_cpu(FILE_ATTR_DIRECTORY); - else - attrib &= ~const_le32_to_cpu(FILE_ATTR_DIRECTORY); - if (!attrib) - attrib |= const_le32_to_cpu(FILE_ATTR_NORMAL); + attrib = -1; /* default return */ + if (scapi && (scapi->magic == MAGIC_API) && path) { + ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); + if (ni) { + attrib = le32_to_cpu(ni->flags); + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + attrib |= const_le32_to_cpu(FILE_ATTR_DIRECTORY); + else + attrib &= ~const_le32_to_cpu(FILE_ATTR_DIRECTORY); + if (!attrib) + attrib |= const_le32_to_cpu(FILE_ATTR_NORMAL); - ntfs_inode_close(ni); - } else - errno = ENOENT; - } else - errno = EINVAL; /* do not clear *psize */ - return (attrib); + ntfs_inode_close(ni); + } else + errno = ENOENT; + } else + errno = EINVAL; /* do not clear *psize */ + return (attrib); } @@ -4582,73 +4643,75 @@ int ntfs_get_file_attributes(struct SECURITY_API *scapi, const char *path) { */ BOOL ntfs_set_file_attributes(struct SECURITY_API *scapi, - const char *path, s32 attrib) { - ntfs_inode *ni; - le32 settable; - ATTR_FLAGS dirflags; - int res; + const char *path, s32 attrib) +{ + ntfs_inode *ni; + le32 settable; + ATTR_FLAGS dirflags; + int res; - res = 0; /* default return */ - if (scapi && (scapi->magic == MAGIC_API) && path) { - ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); - if (ni) { - settable = FILE_ATTR_SETTABLE; - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - /* - * Accept changing compression for a directory - * and set index root accordingly - */ - settable |= FILE_ATTR_COMPRESSED; - if ((ni->flags ^ cpu_to_le32(attrib)) - & FILE_ATTR_COMPRESSED) { - if (ni->flags & FILE_ATTR_COMPRESSED) - dirflags = const_cpu_to_le16(0); - else - dirflags = ATTR_IS_COMPRESSED; - res = ntfs_attr_set_flags(ni, - AT_INDEX_ROOT, - NTFS_INDEX_I30, 4, - dirflags, - ATTR_COMPRESSION_MASK); - } - } - if (!res) { - ni->flags = (ni->flags & ~settable) - | (cpu_to_le32(attrib) & settable); - NInoSetDirty(ni); - } - if (!ntfs_inode_close(ni)) - res = -1; - } else - errno = ENOENT; - } - return (res); + res = 0; /* default return */ + if (scapi && (scapi->magic == MAGIC_API) && path) { + ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); + if (ni) { + settable = FILE_ATTR_SETTABLE; + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { + /* + * Accept changing compression for a directory + * and set index root accordingly + */ + settable |= FILE_ATTR_COMPRESSED; + if ((ni->flags ^ cpu_to_le32(attrib)) + & FILE_ATTR_COMPRESSED) { + if (ni->flags & FILE_ATTR_COMPRESSED) + dirflags = const_cpu_to_le16(0); + else + dirflags = ATTR_IS_COMPRESSED; + res = ntfs_attr_set_flags(ni, + AT_INDEX_ROOT, + NTFS_INDEX_I30, 4, + dirflags, + ATTR_COMPRESSION_MASK); + } + } + if (!res) { + ni->flags = (ni->flags & ~settable) + | (cpu_to_le32(attrib) & settable); + NInoSetDirty(ni); + } + if (!ntfs_inode_close(ni)) + res = -1; + } else + errno = ENOENT; + } + return (res); } BOOL ntfs_read_directory(struct SECURITY_API *scapi, - const char *path, ntfs_filldir_t callback, void *context) { - ntfs_inode *ni; - BOOL ok; - s64 pos; + const char *path, ntfs_filldir_t callback, void *context) +{ + ntfs_inode *ni; + BOOL ok; + s64 pos; - ok = FALSE; /* default return */ - if (scapi && (scapi->magic == MAGIC_API) && callback) { - ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); - if (ni) { - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - pos = 0; - ntfs_readdir(ni,&pos,context,callback); - ok = !ntfs_inode_close(ni); - } else { - ntfs_inode_close(ni); - errno = ENOTDIR; - } - } else - errno = ENOENT; - } else - errno = EINVAL; /* do not clear *psize */ - return (ok); + ok = FALSE; /* default return */ + if (scapi && (scapi->magic == MAGIC_API) && callback) { + ni = ntfs_pathname_to_inode(scapi->security.vol, NULL, path); + if (ni) { + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { + pos = 0; + ntfs_readdir(ni,&pos,context,callback); + ok = !ntfs_inode_close(ni); + } else { + ntfs_inode_close(ni); + errno = ENOTDIR; + } + } else + errno = ENOENT; + } else + errno = EINVAL; /* do not clear *psize */ + return (ok); } /* @@ -4658,19 +4721,20 @@ BOOL ntfs_read_directory(struct SECURITY_API *scapi, */ int ntfs_read_sds(struct SECURITY_API *scapi, - char *buf, u32 size, u32 offset) { - int got; + char *buf, u32 size, u32 offset) +{ + int got; - got = -1; /* default return */ - if (scapi && (scapi->magic == MAGIC_API)) { - if (scapi->security.vol->secure_ni) - got = ntfs_local_read(scapi->security.vol->secure_ni, - STREAM_SDS, 4, buf, size, offset); - else - errno = EOPNOTSUPP; - } else - errno = EINVAL; - return (got); + got = -1; /* default return */ + if (scapi && (scapi->magic == MAGIC_API)) { + if (scapi->security.vol->secure_ni) + got = ntfs_local_read(scapi->security.vol->secure_ni, + STREAM_SDS, 4, buf, size, offset); + else + errno = EOPNOTSUPP; + } else + errno = EINVAL; + return (got); } /* @@ -4680,32 +4744,33 @@ int ntfs_read_sds(struct SECURITY_API *scapi, */ INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, - INDEX_ENTRY *entry) { - SII_INDEX_KEY key; - INDEX_ENTRY *ret; - BOOL found; - ntfs_index_context *xsii; + INDEX_ENTRY *entry) +{ + SII_INDEX_KEY key; + INDEX_ENTRY *ret; + BOOL found; + ntfs_index_context *xsii; - ret = (INDEX_ENTRY*)NULL; /* default return */ - if (scapi && (scapi->magic == MAGIC_API)) { - xsii = scapi->security.vol->secure_xsii; - if (xsii) { - if (!entry) { - key.security_id = const_cpu_to_le32(0); - found = !ntfs_index_lookup((char*)&key, - sizeof(SII_INDEX_KEY), xsii); - /* not supposed to find */ - if (!found && (errno == ENOENT)) - ret = xsii->entry; - } else - ret = ntfs_index_next(entry,xsii); - if (!ret) - errno = ENODATA; - } else - errno = EOPNOTSUPP; - } else - errno = EINVAL; - return (ret); + ret = (INDEX_ENTRY*)NULL; /* default return */ + if (scapi && (scapi->magic == MAGIC_API)) { + xsii = scapi->security.vol->secure_xsii; + if (xsii) { + if (!entry) { + key.security_id = const_cpu_to_le32(0); + found = !ntfs_index_lookup((char*)&key, + sizeof(SII_INDEX_KEY), xsii); + /* not supposed to find */ + if (!found && (errno == ENOENT)) + ret = xsii->entry; + } else + ret = ntfs_index_next(entry,xsii); + if (!ret) + errno = ENODATA; + } else + errno = EOPNOTSUPP; + } else + errno = EINVAL; + return (ret); } /* @@ -4715,32 +4780,33 @@ INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, */ INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, - INDEX_ENTRY *entry) { - SDH_INDEX_KEY key; - INDEX_ENTRY *ret; - BOOL found; - ntfs_index_context *xsdh; + INDEX_ENTRY *entry) +{ + SDH_INDEX_KEY key; + INDEX_ENTRY *ret; + BOOL found; + ntfs_index_context *xsdh; - ret = (INDEX_ENTRY*)NULL; /* default return */ - if (scapi && (scapi->magic == MAGIC_API)) { - xsdh = scapi->security.vol->secure_xsdh; - if (xsdh) { - if (!entry) { - key.hash = const_cpu_to_le32(0); - key.security_id = const_cpu_to_le32(0); - found = !ntfs_index_lookup((char*)&key, - sizeof(SDH_INDEX_KEY), xsdh); - /* not supposed to find */ - if (!found && (errno == ENOENT)) - ret = xsdh->entry; - } else - ret = ntfs_index_next(entry,xsdh); - if (!ret) - errno = ENODATA; - } else errno = ENOTSUP; - } else - errno = EINVAL; - return (ret); + ret = (INDEX_ENTRY*)NULL; /* default return */ + if (scapi && (scapi->magic == MAGIC_API)) { + xsdh = scapi->security.vol->secure_xsdh; + if (xsdh) { + if (!entry) { + key.hash = const_cpu_to_le32(0); + key.security_id = const_cpu_to_le32(0); + found = !ntfs_index_lookup((char*)&key, + sizeof(SDH_INDEX_KEY), xsdh); + /* not supposed to find */ + if (!found && (errno == ENOENT)) + ret = xsdh->entry; + } else + ret = ntfs_index_next(entry,xsdh); + if (!ret) + errno = ENODATA; + } else errno = ENOTSUP; + } else + errno = EINVAL; + return (ret); } /* @@ -4750,22 +4816,23 @@ INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, * returns the size of the SID, or zero and errno set if not found */ -int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf) { - const SID *usid; - BIGSID defusid; - int size; +int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf) +{ + const SID *usid; + BIGSID defusid; + int size; - size = 0; - if (scapi && (scapi->magic == MAGIC_API)) { - usid = ntfs_find_usid(scapi->security.mapping[MAPUSERS], uid, (SID*)&defusid); - if (usid) { - size = ntfs_sid_size(usid); - memcpy(buf,usid,size); - } else - errno = ENODATA; - } else - errno = EINVAL; - return (size); + size = 0; + if (scapi && (scapi->magic == MAGIC_API)) { + usid = ntfs_find_usid(scapi->security.mapping[MAPUSERS], uid, (SID*)&defusid); + if (usid) { + size = ntfs_sid_size(usid); + memcpy(buf,usid,size); + } else + errno = ENODATA; + } else + errno = EINVAL; + return (size); } /* @@ -4775,22 +4842,23 @@ int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf) { * returns the size of the SID, or zero and errno set if not found */ -int ntfs_get_gsid(struct SECURITY_API *scapi, gid_t gid, char *buf) { - const SID *gsid; - BIGSID defgsid; - int size; +int ntfs_get_gsid(struct SECURITY_API *scapi, gid_t gid, char *buf) +{ + const SID *gsid; + BIGSID defgsid; + int size; - size = 0; - if (scapi && (scapi->magic == MAGIC_API)) { - gsid = ntfs_find_gsid(scapi->security.mapping[MAPGROUPS], gid, (SID*)&defgsid); - if (gsid) { - size = ntfs_sid_size(gsid); - memcpy(buf,gsid,size); - } else - errno = ENODATA; - } else - errno = EINVAL; - return (size); + size = 0; + if (scapi && (scapi->magic == MAGIC_API)) { + gsid = ntfs_find_gsid(scapi->security.mapping[MAPGROUPS], gid, (SID*)&defgsid); + if (gsid) { + size = ntfs_sid_size(gsid); + memcpy(buf,gsid,size); + } else + errno = ENODATA; + } else + errno = EINVAL; + return (size); } /* @@ -4799,23 +4867,24 @@ int ntfs_get_gsid(struct SECURITY_API *scapi, gid_t gid, char *buf) { * returns the uid, or -1 if not found */ -int ntfs_get_user(struct SECURITY_API *scapi, const SID *usid) { - int uid; +int ntfs_get_user(struct SECURITY_API *scapi, const SID *usid) +{ + int uid; - uid = -1; - if (scapi && (scapi->magic == MAGIC_API) && ntfs_valid_sid(usid)) { - if (ntfs_same_sid(usid,adminsid)) - uid = 0; - else { - uid = ntfs_find_user(scapi->security.mapping[MAPUSERS], usid); - if (!uid) { - uid = -1; - errno = ENODATA; - } - } - } else - errno = EINVAL; - return (uid); + uid = -1; + if (scapi && (scapi->magic == MAGIC_API) && ntfs_valid_sid(usid)) { + if (ntfs_same_sid(usid,adminsid)) + uid = 0; + else { + uid = ntfs_find_user(scapi->security.mapping[MAPUSERS], usid); + if (!uid) { + uid = -1; + errno = ENODATA; + } + } + } else + errno = EINVAL; + return (uid); } /* @@ -4824,23 +4893,24 @@ int ntfs_get_user(struct SECURITY_API *scapi, const SID *usid) { * returns the uid, or -1 if not found */ -int ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid) { - int gid; +int ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid) +{ + int gid; - gid = -1; - if (scapi && (scapi->magic == MAGIC_API) && ntfs_valid_sid(gsid)) { - if (ntfs_same_sid(gsid,adminsid)) - gid = 0; - else { - gid = ntfs_find_group(scapi->security.mapping[MAPGROUPS], gsid); - if (!gid) { - gid = -1; - errno = ENODATA; - } - } - } else - errno = EINVAL; - return (gid); + gid = -1; + if (scapi && (scapi->magic == MAGIC_API) && ntfs_valid_sid(gsid)) { + if (ntfs_same_sid(gsid,adminsid)) + gid = 0; + else { + gid = ntfs_find_group(scapi->security.mapping[MAPGROUPS], gsid); + if (!gid) { + gid = -1; + errno = ENODATA; + } + } + } else + errno = EINVAL; + return (gid); } /* @@ -4854,48 +4924,49 @@ int ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid) { */ struct SECURITY_API *ntfs_initialize_file_security(const char *device, - int flags) { - ntfs_volume *vol; - unsigned long mntflag; - int mnt; - struct SECURITY_API *scapi; - struct SECURITY_CONTEXT *scx; + int flags) +{ + ntfs_volume *vol; + unsigned long mntflag; + int mnt; + struct SECURITY_API *scapi; + struct SECURITY_CONTEXT *scx; - scapi = (struct SECURITY_API*)NULL; - mnt = ntfs_check_if_mounted(device, &mntflag); - if (!mnt && !(mntflag & NTFS_MF_MOUNTED) && !getuid()) { - vol = ntfs_mount(device, flags); - if (vol) { - scapi = (struct SECURITY_API*) - ntfs_malloc(sizeof(struct SECURITY_API)); - if (!ntfs_volume_get_free_space(vol) - && scapi) { - scapi->magic = MAGIC_API; - scapi->seccache = (struct PERMISSIONS_CACHE*)NULL; - scx = &scapi->security; - scx->vol = vol; - scx->uid = getuid(); - scx->gid = getgid(); - scx->pseccache = &scapi->seccache; - scx->vol->secure_flags = 0; - /* accept no mapping and no $Secure */ - ntfs_build_mapping(scx,(const char*)NULL); - ntfs_open_secure(vol); - } else { - if (scapi) - free(scapi); - else - errno = ENOMEM; - mnt = ntfs_umount(vol,FALSE); - scapi = (struct SECURITY_API*)NULL; - } - } - } else - if (getuid()) - errno = EPERM; - else - errno = EBUSY; - return (scapi); + scapi = (struct SECURITY_API*)NULL; + mnt = ntfs_check_if_mounted(device, &mntflag); + if (!mnt && !(mntflag & NTFS_MF_MOUNTED) && !getuid()) { + vol = ntfs_mount(device, flags); + if (vol) { + scapi = (struct SECURITY_API*) + ntfs_malloc(sizeof(struct SECURITY_API)); + if (!ntfs_volume_get_free_space(vol) + && scapi) { + scapi->magic = MAGIC_API; + scapi->seccache = (struct PERMISSIONS_CACHE*)NULL; + scx = &scapi->security; + scx->vol = vol; + scx->uid = getuid(); + scx->gid = getgid(); + scx->pseccache = &scapi->seccache; + scx->vol->secure_flags = 0; + /* accept no mapping and no $Secure */ + ntfs_build_mapping(scx,(const char*)NULL); + ntfs_open_secure(vol); + } else { + if (scapi) + free(scapi); + else + errno = ENOMEM; + mnt = ntfs_umount(vol,FALSE); + scapi = (struct SECURITY_API*)NULL; + } + } + } else + if (getuid()) + errno = EPERM; + else + errno = EBUSY; + return (scapi); } /* @@ -4904,18 +4975,19 @@ struct SECURITY_API *ntfs_initialize_file_security(const char *device, * Returns FALSE if FAILED */ -BOOL ntfs_leave_file_security(struct SECURITY_API *scapi) { - int ok; - ntfs_volume *vol; +BOOL ntfs_leave_file_security(struct SECURITY_API *scapi) +{ + int ok; + ntfs_volume *vol; - ok = FALSE; - if (scapi && (scapi->magic == MAGIC_API) && scapi->security.vol) { - vol = scapi->security.vol; - ntfs_close_secure(&scapi->security); - free(scapi); - if (!ntfs_umount(vol, 0)) - ok = TRUE; - } - return (ok); + ok = FALSE; + if (scapi && (scapi->magic == MAGIC_API) && scapi->security.vol) { + vol = scapi->security.vol; + ntfs_close_secure(&scapi->security); + free(scapi); + if (!ntfs_umount(vol, 0)) + ok = TRUE; + } + return (ok); } diff --git a/source/libntfs/security.h b/source/libntfs/security.h index 22b8cc2c..eaa67b41 100644 --- a/source/libntfs/security.h +++ b/source/libntfs/security.h @@ -1,5 +1,5 @@ /* - * security.h - Exports for handling security/ACLs in NTFS. + * security.h - Exports for handling security/ACLs in NTFS. * Originated from the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov @@ -48,11 +48,11 @@ */ struct MAPPING { - struct MAPPING *next; - int xid; /* linux id : uid or gid */ - SID *sid; /* Windows id : usid or gsid */ - int grcnt; /* group count (for users only) */ - gid_t *groups; /* groups which the user is member of */ + struct MAPPING *next; + int xid; /* linux id : uid or gid */ + SID *sid; /* Windows id : usid or gsid */ + int grcnt; /* group count (for users only) */ + gid_t *groups; /* groups which the user is member of */ }; /* @@ -61,19 +61,16 @@ struct MAPPING { */ struct CACHED_PERMISSIONS { - uid_t uid; - gid_t gid; - le32 inh_fileid; - le32 inh_dirid; + uid_t uid; + gid_t gid; + le32 inh_fileid; + le32 inh_dirid; #if POSIXACLS - struct POSIX_SECURITY *pxdesc; -unsigned int pxdescsize: - 16; + struct POSIX_SECURITY *pxdesc; + unsigned int pxdescsize:16; #endif -unsigned int mode: - 12; -unsigned int valid: - 1; + unsigned int mode:12; + unsigned int valid:1; } ; /* @@ -81,12 +78,12 @@ unsigned int valid: */ struct CACHED_PERMISSIONS_LEGACY { - struct CACHED_PERMISSIONS_LEGACY *next; - void *variable; - size_t varsize; - /* above fields must match "struct CACHED_GENERIC" */ - u64 mft_no; - struct CACHED_PERMISSIONS perm; + struct CACHED_PERMISSIONS_LEGACY *next; + void *variable; + size_t varsize; + /* above fields must match "struct CACHED_GENERIC" */ + u64 mft_no; + struct CACHED_PERMISSIONS perm; } ; /* @@ -94,14 +91,14 @@ struct CACHED_PERMISSIONS_LEGACY { */ struct CACHED_SECURID { - struct CACHED_SECURID *next; - void *variable; - size_t varsize; - /* above fields must match "struct CACHED_GENERIC" */ - uid_t uid; - gid_t gid; - unsigned int dmode; - le32 securid; + struct CACHED_SECURID *next; + void *variable; + size_t varsize; + /* above fields must match "struct CACHED_GENERIC" */ + uid_t uid; + gid_t gid; + unsigned int dmode; + le32 securid; } ; /* @@ -110,11 +107,11 @@ struct CACHED_SECURID { */ struct CACHED_PERMISSIONS_HEADER { - unsigned int last; - /* statistics for permissions */ - unsigned long p_writes; - unsigned long p_reads; - unsigned long p_hits; + unsigned int last; + /* statistics for permissions */ + unsigned long p_writes; + unsigned long p_reads; + unsigned long p_hits; } ; /* @@ -122,8 +119,8 @@ struct CACHED_PERMISSIONS_HEADER { */ struct PERMISSIONS_CACHE { - struct CACHED_PERMISSIONS_HEADER head; - struct CACHED_PERMISSIONS *cachetable[1]; /* array of variable size */ + struct CACHED_PERMISSIONS_HEADER head; + struct CACHED_PERMISSIONS *cachetable[1]; /* array of variable size */ } ; /* @@ -131,11 +128,11 @@ struct PERMISSIONS_CACHE { */ enum { - SECURITY_DEFAULT, /* rely on fuse for permissions checking */ - SECURITY_RAW, /* force same ownership/permissions on files */ - SECURITY_ADDSECURIDS, /* upgrade old security descriptors */ - SECURITY_STATICGRPS, /* use static groups for access control */ - SECURITY_WANTED /* a security related option was present */ + SECURITY_DEFAULT, /* rely on fuse for permissions checking */ + SECURITY_RAW, /* force same ownership/permissions on files */ + SECURITY_ADDSECURIDS, /* upgrade old security descriptors */ + SECURITY_STATICGRPS, /* use static groups for access control */ + SECURITY_WANTED /* a security related option was present */ } ; /* @@ -145,68 +142,68 @@ enum { enum { MAPUSERS, MAPGROUPS, MAPCOUNT } ; struct SECURITY_CONTEXT { - ntfs_volume *vol; - struct MAPPING *mapping[MAPCOUNT]; - struct PERMISSIONS_CACHE **pseccache; - uid_t uid; /* uid of user requesting (not the mounter) */ - gid_t gid; /* gid of user requesting (not the mounter) */ - pid_t tid; /* thread id of thread requesting */ - mode_t umask; /* umask of requesting thread */ -} ; + ntfs_volume *vol; + struct MAPPING *mapping[MAPCOUNT]; + struct PERMISSIONS_CACHE **pseccache; + uid_t uid; /* uid of user requesting (not the mounter) */ + gid_t gid; /* gid of user requesting (not the mounter) */ + pid_t tid; /* thread id of thread requesting */ + mode_t umask; /* umask of requesting thread */ + } ; #if POSIXACLS /* * Posix ACL structures */ - + struct POSIX_ACE { - u16 tag; - u16 perms; - s32 id; + u16 tag; + u16 perms; + s32 id; } ; - + struct POSIX_ACL { - u8 version; - u8 flags; - u16 filler; - struct POSIX_ACE ace[0]; + u8 version; + u8 flags; + u16 filler; + struct POSIX_ACE ace[0]; } ; struct POSIX_SECURITY { - mode_t mode; - int acccnt; - int defcnt; - int firstdef; - u16 tagsset; - struct POSIX_ACL acl; + mode_t mode; + int acccnt; + int defcnt; + int firstdef; + u16 tagsset; + struct POSIX_ACL acl; } ; - + /* * Posix tags, cpu-endian 16 bits */ - -enum { - POSIX_ACL_USER_OBJ = 1, - POSIX_ACL_USER = 2, - POSIX_ACL_GROUP_OBJ = 4, - POSIX_ACL_GROUP = 8, - POSIX_ACL_MASK = 16, - POSIX_ACL_OTHER = 32, - POSIX_ACL_SPECIAL = 64 /* internal use only */ + +enum { + POSIX_ACL_USER_OBJ = 1, + POSIX_ACL_USER = 2, + POSIX_ACL_GROUP_OBJ = 4, + POSIX_ACL_GROUP = 8, + POSIX_ACL_MASK = 16, + POSIX_ACL_OTHER = 32, + POSIX_ACL_SPECIAL = 64 /* internal use only */ } ; #define POSIX_ACL_EXTENSIONS (POSIX_ACL_USER | POSIX_ACL_GROUP | POSIX_ACL_MASK) - + /* * Posix permissions, cpu-endian 16 bits */ - -enum { - POSIX_PERM_X = 1, - POSIX_PERM_W = 2, - POSIX_PERM_R = 4, - POSIX_PERM_DENIAL = 64 /* internal use only */ + +enum { + POSIX_PERM_X = 1, + POSIX_PERM_W = 2, + POSIX_PERM_R = 4, + POSIX_PERM_DENIAL = 64 /* internal use only */ } ; #define POSIX_VERSION 2 @@ -224,83 +221,84 @@ extern char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str); * * Return TRUE if it is valid and FALSE otherwise. */ -static __inline__ BOOL ntfs_sid_is_valid(const SID *sid) { - if (!sid || sid->revision != SID_REVISION || - sid->sub_authority_count > SID_MAX_SUB_AUTHORITIES) - return FALSE; - return TRUE; +static __inline__ BOOL ntfs_sid_is_valid(const SID *sid) +{ + if (!sid || sid->revision != SID_REVISION || + sid->sub_authority_count > SID_MAX_SUB_AUTHORITIES) + return FALSE; + return TRUE; } extern int ntfs_sid_to_mbs_size(const SID *sid); extern char *ntfs_sid_to_mbs(const SID *sid, char *sid_str, - size_t sid_str_size); + size_t sid_str_size); extern void ntfs_generate_guid(GUID *guid); extern int ntfs_sd_add_everyone(ntfs_inode *ni); -extern le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, - const u32 len); +extern le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, + const u32 len); int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path); int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni, struct stat*); + const char *path, ntfs_inode *ni, struct stat*); int ntfs_set_mode(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni, mode_t mode); + const char *path, ntfs_inode *ni, mode_t mode); BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni); + const char *path, ntfs_inode *ni); int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, const char *path, - ntfs_inode *ni, int accesstype); + ntfs_inode *ni, int accesstype); BOOL ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, - const char *path, int accesstype); + const char *path, int accesstype); #if POSIXACLS le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, const char *dir_path, - ntfs_inode *dir_ni, mode_t mode, BOOL isdir); + uid_t uid, gid_t gid, const char *dir_path, + ntfs_inode *dir_ni, mode_t mode, BOOL isdir); #else le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, mode_t mode, BOOL isdir); + uid_t uid, gid_t gid, mode_t mode, BOOL isdir); #endif int ntfs_set_owner(struct SECURITY_CONTEXT *scx, - const char *path, ntfs_inode *ni, uid_t uid, gid_t gid); + const char *path, ntfs_inode *ni, uid_t uid, gid_t gid); #if POSIXACLS int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, uid_t uid, gid_t gid, - mode_t mode, struct POSIX_SECURITY *pxdesc); + ntfs_inode *ni, uid_t uid, gid_t gid, + mode_t mode, struct POSIX_SECURITY *pxdesc); #else int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode); + ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode); #endif le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, - const char *dir_path, ntfs_inode *dir_ni, BOOL fordir); + const char *dir_path, ntfs_inode *dir_ni, BOOL fordir); int ntfs_open_secure(ntfs_volume *vol); void ntfs_close_secure(struct SECURITY_CONTEXT *scx); #if POSIXACLS int ntfs_set_inherited_posix(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, uid_t uid, gid_t gid, - const char *dir_path, ntfs_inode *dir_ni, mode_t mode); + ntfs_inode *ni, uid_t uid, gid_t gid, + const char *dir_path, ntfs_inode *dir_ni, mode_t mode); int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, char *value, size_t size, - ntfs_inode *ni); + const char *name, char *value, size_t size, + ntfs_inode *ni); int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, const char *value, size_t size, - int flags, ntfs_inode *ni); + const char *name, const char *value, size_t size, + int flags, ntfs_inode *ni); int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, ntfs_inode *ni); + const char *name, ntfs_inode *ni); #endif int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, char *value, size_t size, - ntfs_inode *ni); + const char *name, char *value, size_t size, + ntfs_inode *ni); int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, const char *path, - const char *name, const char *value, size_t size, - int flags, ntfs_inode *ni); + const char *name, const char *value, size_t size, + int flags, ntfs_inode *ni); int ntfs_get_ntfs_attrib(const char *path, - char *value, size_t size, ntfs_inode *ni); + char *value, size_t size, ntfs_inode *ni); int ntfs_set_ntfs_attrib(const char *path, - const char *value, size_t size, int flags, - ntfs_inode *ni); + const char *value, size_t size, int flags, + ntfs_inode *ni); /* * Security API for direct access to security descriptors @@ -310,9 +308,9 @@ int ntfs_set_ntfs_attrib(const char *path, #define MAGIC_API 0x09042009 struct SECURITY_API { - u32 magic; - struct SECURITY_CONTEXT security; - struct PERMISSIONS_CACHE *seccache; + u32 magic; + struct SECURITY_CONTEXT security; + struct PERMISSIONS_CACHE *seccache; } ; /* @@ -322,30 +320,30 @@ struct SECURITY_API { * When disk representation (le) is needed, use SE_DACL_PRESENT, etc. */ enum { OWNER_SECURITY_INFORMATION = 1, - GROUP_SECURITY_INFORMATION = 2, - DACL_SECURITY_INFORMATION = 4, - SACL_SECURITY_INFORMATION = 8 - } ; + GROUP_SECURITY_INFORMATION = 2, + DACL_SECURITY_INFORMATION = 4, + SACL_SECURITY_INFORMATION = 8 +} ; int ntfs_get_file_security(struct SECURITY_API *scapi, - const char *path, u32 selection, - char *buf, u32 buflen, u32 *psize); + const char *path, u32 selection, + char *buf, u32 buflen, u32 *psize); int ntfs_set_file_security(struct SECURITY_API *scapi, - const char *path, u32 selection, const char *attr); + const char *path, u32 selection, const char *attr); int ntfs_get_file_attributes(struct SECURITY_API *scapi, - const char *path); + const char *path); BOOL ntfs_set_file_attributes(struct SECURITY_API *scapi, - const char *path, s32 attrib); + const char *path, s32 attrib); BOOL ntfs_read_directory(struct SECURITY_API *scapi, - const char *path, ntfs_filldir_t callback, void *context); + const char *path, ntfs_filldir_t callback, void *context); int ntfs_read_sds(struct SECURITY_API *scapi, - char *buf, u32 size, u32 offset); + char *buf, u32 size, u32 offset); INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, - INDEX_ENTRY *entry); + INDEX_ENTRY *entry); INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, - INDEX_ENTRY *entry); + INDEX_ENTRY *entry); struct SECURITY_API *ntfs_initialize_file_security(const char *device, - int flags); + int flags); BOOL ntfs_leave_file_security(struct SECURITY_API *scx); int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf); diff --git a/source/libntfs/types.h b/source/libntfs/types.h index 008f9ad6..12e58f29 100644 --- a/source/libntfs/types.h +++ b/source/libntfs/types.h @@ -1,5 +1,5 @@ /* - * types.h - Misc type definitions not related to on-disk structure. + * types.h - Misc type definitions not related to on-disk structure. * Originated from the Linux-NTFS project. * * Copyright (c) 2000-2004 Anton Altaparmakov @@ -94,22 +94,22 @@ typedef sle64 leLSN; */ typedef enum { #ifndef FALSE - FALSE = 0, + FALSE = 0, #endif #ifndef NO - NO = 0, + NO = 0, #endif #ifndef ZERO - ZERO = 0, + ZERO = 0, #endif #ifndef TRUE - TRUE = 1, + TRUE = 1, #endif #ifndef YES - YES = 1, + YES = 1, #endif #ifndef ONE - ONE = 1, + ONE = 1, #endif } BOOL; #endif /* GEKKO */ @@ -119,8 +119,8 @@ typedef enum { * enum IGNORE_CASE_BOOL - */ typedef enum { - CASE_SENSITIVE = 0, - IGNORE_CASE = 1, + CASE_SENSITIVE = 0, + IGNORE_CASE = 1, } IGNORE_CASE_BOOL; #define STATUS_OK (0) diff --git a/source/libntfs/unistr.c b/source/libntfs/unistr.c index 060e75df..22eb2c61 100644 --- a/source/libntfs/unistr.c +++ b/source/libntfs/unistr.c @@ -89,17 +89,17 @@ static int nfconvert_utf8 = 1; */ #if 0 static const u8 legal_ansi_char_array[0x40] = { - 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, - 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, + 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, + 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, - 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, - 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, + 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, + 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, - 0x17, 0x07, 0x18, 0x17, 0x17, 0x17, 0x17, 0x17, - 0x17, 0x17, 0x18, 0x16, 0x16, 0x17, 0x07, 0x00, + 0x17, 0x07, 0x18, 0x17, 0x17, 0x17, 0x17, 0x17, + 0x17, 0x17, 0x18, 0x16, 0x16, 0x17, 0x07, 0x00, - 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, - 0x17, 0x17, 0x04, 0x16, 0x18, 0x16, 0x18, 0x18, + 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, + 0x17, 0x17, 0x04, 0x16, 0x18, 0x16, 0x18, 0x18, }; #endif @@ -118,17 +118,18 @@ static const u8 legal_ansi_char_array[0x40] = { * the @upcase table is used to perform a case insensitive comparison. */ BOOL ntfs_names_are_equal(const ntfschar *s1, size_t s1_len, - const ntfschar *s2, size_t s2_len, - const IGNORE_CASE_BOOL ic, - const ntfschar *upcase, const u32 upcase_size) { - if (s1_len != s2_len) - return FALSE; - if (!s1_len) - return TRUE; - if (ic == CASE_SENSITIVE) - return ntfs_ucsncmp(s1, s2, s1_len) ? FALSE: TRUE; - return ntfs_ucsncasecmp(s1, s2, s1_len, upcase, upcase_size) ? FALSE: - TRUE; + const ntfschar *s2, size_t s2_len, + const IGNORE_CASE_BOOL ic, + const ntfschar *upcase, const u32 upcase_size) +{ + if (s1_len != s2_len) + return FALSE; + if (!s1_len) + return TRUE; + if (ic == CASE_SENSITIVE) + return ntfs_ucsncmp(s1, s2, s1_len) ? FALSE: TRUE; + return ntfs_ucsncasecmp(s1, s2, s1_len, upcase, upcase_size) ? FALSE: + TRUE; } /** @@ -155,52 +156,53 @@ BOOL ntfs_names_are_equal(const ntfschar *s1, size_t s1_len, */ int ntfs_names_collate(const ntfschar *name1, const u32 name1_len, - const ntfschar *name2, const u32 name2_len, - const int err_val __attribute__((unused)), - const IGNORE_CASE_BOOL ic, const ntfschar *upcase, - const u32 upcase_len) { - u32 cnt; - ntfschar c1, c2; + const ntfschar *name2, const u32 name2_len, + const int err_val __attribute__((unused)), + const IGNORE_CASE_BOOL ic, const ntfschar *upcase, + const u32 upcase_len) +{ + u32 cnt; + ntfschar c1, c2; #ifdef DEBUG - if (!name1 || !name2 || (ic && (!upcase || !upcase_len))) { - ntfs_log_debug("ntfs_names_collate received NULL pointer!\n"); - exit(1); - } + if (!name1 || !name2 || (ic && (!upcase || !upcase_len))) { + ntfs_log_debug("ntfs_names_collate received NULL pointer!\n"); + exit(1); + } #endif - cnt = min(name1_len, name2_len); - /* JPA average loop count is 8 */ - if (cnt > 0) { - if (ic) - /* JPA this loop in 76% cases */ - do { - c1 = le16_to_cpu(*name1); - name1++; - c2 = le16_to_cpu(*name2); - name2++; - if (c1 < upcase_len) - c1 = le16_to_cpu(upcase[c1]); - if (c2 < upcase_len) - c2 = le16_to_cpu(upcase[c2]); - } while ((c1 == c2) && --cnt); - else - do { - /* JPA this loop in 24% cases */ - c1 = le16_to_cpu(*name1); - name1++; - c2 = le16_to_cpu(*name2); - name2++; - } while ((c1 == c2) && --cnt); - if (c1 < c2) - return -1; - if (c1 > c2) - return 1; - } - if (name1_len < name2_len) - return -1; - if (name1_len == name2_len) - return 0; - return 1; + cnt = min(name1_len, name2_len); + /* JPA average loop count is 8 */ + if (cnt > 0) { + if (ic) + /* JPA this loop in 76% cases */ + do { + c1 = le16_to_cpu(*name1); + name1++; + c2 = le16_to_cpu(*name2); + name2++; + if (c1 < upcase_len) + c1 = le16_to_cpu(upcase[c1]); + if (c2 < upcase_len) + c2 = le16_to_cpu(upcase[c2]); + } while ((c1 == c2) && --cnt); + else + do { + /* JPA this loop in 24% cases */ + c1 = le16_to_cpu(*name1); + name1++; + c2 = le16_to_cpu(*name2); + name2++; + } while ((c1 == c2) && --cnt); + if (c1 < c2) + return -1; + if (c1 > c2) + return 1; + } + if (name1_len < name2_len) + return -1; + if (name1_len == name2_len) + return 0; + return 1; } /** @@ -217,27 +219,28 @@ int ntfs_names_collate(const ntfschar *name1, const u32 name1_len, * if @s1 (or the first @n Unicode characters thereof) is found, respectively, * to be less than, to match, or be greater than @s2. */ -int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n) { - ntfschar c1, c2; - size_t i; +int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n) +{ + ntfschar c1, c2; + size_t i; #ifdef DEBUG - if (!s1 || !s2) { - ntfs_log_debug("ntfs_wcsncmp() received NULL pointer!\n"); - exit(1); - } + if (!s1 || !s2) { + ntfs_log_debug("ntfs_wcsncmp() received NULL pointer!\n"); + exit(1); + } #endif - for (i = 0; i < n; ++i) { - c1 = le16_to_cpu(s1[i]); - c2 = le16_to_cpu(s2[i]); - if (c1 < c2) - return -1; - if (c1 > c2) - return 1; - if (!c1) - break; - } - return 0; + for (i = 0; i < n; ++i) { + c1 = le16_to_cpu(s1[i]); + c2 = le16_to_cpu(s2[i]); + if (c1 < c2) + return -1; + if (c1 > c2) + return 1; + if (!c1) + break; + } + return 0; } /** @@ -259,29 +262,30 @@ int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n) { * to be less than, to match, or be greater than @s2. */ int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, - const ntfschar *upcase, const u32 upcase_size) { - ntfschar c1, c2; - size_t i; + const ntfschar *upcase, const u32 upcase_size) +{ + ntfschar c1, c2; + size_t i; #ifdef DEBUG - if (!s1 || !s2 || !upcase) { - ntfs_log_debug("ntfs_wcsncasecmp() received NULL pointer!\n"); - exit(1); - } + if (!s1 || !s2 || !upcase) { + ntfs_log_debug("ntfs_wcsncasecmp() received NULL pointer!\n"); + exit(1); + } #endif - for (i = 0; i < n; ++i) { - if ((c1 = le16_to_cpu(s1[i])) < upcase_size) - c1 = le16_to_cpu(upcase[c1]); - if ((c2 = le16_to_cpu(s2[i])) < upcase_size) - c2 = le16_to_cpu(upcase[c2]); - if (c1 < c2) - return -1; - if (c1 > c2) - return 1; - if (!c1) - break; - } - return 0; + for (i = 0; i < n; ++i) { + if ((c1 = le16_to_cpu(s1[i])) < upcase_size) + c1 = le16_to_cpu(upcase[c1]); + if ((c2 = le16_to_cpu(s2[i])) < upcase_size) + c2 = le16_to_cpu(upcase[c2]); + if (c1 < c2) + return -1; + if (c1 > c2) + return 1; + if (!c1) + break; + } + return 0; } /** @@ -296,14 +300,15 @@ int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, * * This function never looks beyond @s + @maxlen. */ -u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen) { - u32 i; +u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen) +{ + u32 i; - for (i = 0; i < maxlen; i++) { - if (!le16_to_cpu(s[i])) - break; - } - return i; + for (i = 0; i < maxlen; i++) { + if (!le16_to_cpu(s[i])) + break; + } + return i; } /** @@ -323,17 +328,18 @@ u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen) { * Return a pointer to the new little endian Unicode string on success and NULL * on failure with errno set to the error code. */ -ntfschar *ntfs_ucsndup(const ntfschar *s, u32 maxlen) { - ntfschar *dst; - u32 len; +ntfschar *ntfs_ucsndup(const ntfschar *s, u32 maxlen) +{ + ntfschar *dst; + u32 len; - len = ntfs_ucsnlen(s, maxlen); - dst = ntfs_malloc((len + 1) * sizeof(ntfschar)); - if (dst) { - memcpy(dst, s, len * sizeof(ntfschar)); - dst[len] = cpu_to_le16(L'\0'); - } - return dst; + len = ntfs_ucsnlen(s, maxlen); + dst = ntfs_malloc((len + 1) * sizeof(ntfschar)); + if (dst) { + memcpy(dst, s, len * sizeof(ntfschar)); + dst[len] = cpu_to_le16(L'\0'); + } + return dst; } /** @@ -348,13 +354,14 @@ ntfschar *ntfs_ucsndup(const ntfschar *s, u32 maxlen) { * Returns: */ void ntfs_name_upcase(ntfschar *name, u32 name_len, const ntfschar *upcase, - const u32 upcase_len) { - u32 i; - ntfschar u; + const u32 upcase_len) +{ + u32 i; + ntfschar u; - for (i = 0; i < name_len; i++) - if ((u = le16_to_cpu(name[i])) < upcase_len) - name[i] = upcase[u]; + for (i = 0; i < name_len; i++) + if ((u = le16_to_cpu(name[i])) < upcase_len) + name[i] = upcase[u]; } /** @@ -368,9 +375,10 @@ void ntfs_name_upcase(ntfschar *name, u32 name_len, const ntfschar *upcase, * Returns: */ void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr, - const ntfschar *upcase, const u32 upcase_len) { - ntfs_name_upcase((ntfschar*)&file_name_attr->file_name, - file_name_attr->file_name_length, upcase, upcase_len); + const ntfschar *upcase, const u32 upcase_len) +{ + ntfs_name_upcase((ntfschar*)&file_name_attr->file_name, + file_name_attr->file_name_length, upcase, upcase_len); } /** @@ -387,14 +395,15 @@ void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr, * Returns: */ int ntfs_file_values_compare(const FILE_NAME_ATTR *file_name_attr1, - const FILE_NAME_ATTR *file_name_attr2, - const int err_val, const IGNORE_CASE_BOOL ic, - const ntfschar *upcase, const u32 upcase_len) { - return ntfs_names_collate((ntfschar*)&file_name_attr1->file_name, - file_name_attr1->file_name_length, - (ntfschar*)&file_name_attr2->file_name, - file_name_attr2->file_name_length, - err_val, ic, upcase, upcase_len); + const FILE_NAME_ATTR *file_name_attr2, + const int err_val, const IGNORE_CASE_BOOL ic, + const ntfschar *upcase, const u32 upcase_len) +{ + return ntfs_names_collate((ntfschar*)&file_name_attr1->file_name, + file_name_attr1->file_name_length, + (ntfschar*)&file_name_attr2->file_name, + file_name_attr2->file_name_length, + err_val, ic, upcase, upcase_len); } /* @@ -410,68 +419,69 @@ int ntfs_file_values_compare(const FILE_NAME_ATTR *file_name_attr1, so this patch fixes the resulting issues for systems which use UTF-8 and for others, specifying the locale in fstab brings them the encoding which they want. - + If no locale is defined or there was a problem with setting one up and whenever nl_langinfo(CODESET) returns a sting starting with "ANSI", use an internal UCS-2LE <-> UTF-8 codeset converter to fix the bug where NTFS-3G does not show any path names which include international characters!!! (and also fails on creating them) as result. - + Author: Bernhard Kaindl Jean-Pierre Andre made it compliant with RFC3629/RFC2781. */ - -/* + +/* * Return the amount of 8-bit elements in UTF-8 needed (without the terminating * null) to store a given UTF-16LE string. * * Return -1 with errno set if string has invalid byte sequence or too long. */ -static int utf16_to_utf8_size(const ntfschar *ins, const int ins_len, int outs_len) { - int i, ret = -1; - int count = 0; - BOOL surrog; +static int utf16_to_utf8_size(const ntfschar *ins, const int ins_len, int outs_len) +{ + int i, ret = -1; + int count = 0; + BOOL surrog; - surrog = FALSE; - for (i = 0; i < ins_len && ins[i]; i++) { - unsigned short c = le16_to_cpu(ins[i]); - if (surrog) { - if ((c >= 0xdc00) && (c < 0xe000)) { - surrog = FALSE; - count += 4; - } else - goto fail; - } else - if (c < 0x80) - count++; - else if (c < 0x800) - count += 2; - else if (c < 0xd800) - count += 3; - else if (c < 0xdc00) - surrog = TRUE; + surrog = FALSE; + for (i = 0; i < ins_len && ins[i]; i++) { + unsigned short c = le16_to_cpu(ins[i]); + if (surrog) { + if ((c >= 0xdc00) && (c < 0xe000)) { + surrog = FALSE; + count += 4; + } else + goto fail; + } else + if (c < 0x80) + count++; + else if (c < 0x800) + count += 2; + else if (c < 0xd800) + count += 3; + else if (c < 0xdc00) + surrog = TRUE; #if NOREVBOM - else if ((c >= 0xe000) && (c < 0xfffe)) + else if ((c >= 0xe000) && (c < 0xfffe)) #else - else if (c >= 0xe000) + else if (c >= 0xe000) #endif - count += 3; - else - goto fail; - if (count > outs_len) { - errno = ENAMETOOLONG; - goto out; - } - } - if (surrog) - goto fail; + count += 3; + else + goto fail; + if (count > outs_len) { + errno = ENAMETOOLONG; + goto out; + } + } + if (surrog) + goto fail; - ret = count; + ret = count; out: - return ret; + return ret; fail: - errno = EILSEQ; - goto out; + errno = EILSEQ; + goto out; } /* @@ -484,107 +494,110 @@ fail: * Return -1 with errno set if string has invalid byte sequence or too long. */ static int ntfs_utf16_to_utf8(const ntfschar *ins, const int ins_len, - char **outs, int outs_len) { + char **outs, int outs_len) +{ #if defined(__APPLE__) || defined(__DARWIN__) #ifdef ENABLE_NFCONV - char *original_outs_value = *outs; - int original_outs_len = outs_len; + char *original_outs_value = *outs; + int original_outs_len = outs_len; #endif /* ENABLE_NFCONV */ #endif /* defined(__APPLE__) || defined(__DARWIN__) */ - char *t; - int i, size, ret = -1; - ntfschar halfpair; + char *t; + int i, size, ret = -1; + ntfschar halfpair; - halfpair = 0; - if (!*outs) - outs_len = PATH_MAX; + halfpair = 0; + if (!*outs) + outs_len = PATH_MAX; - size = utf16_to_utf8_size(ins, ins_len, outs_len); + size = utf16_to_utf8_size(ins, ins_len, outs_len); - if (size < 0) - goto out; + if (size < 0) + goto out; - if (!*outs) { - outs_len = size + 1; - *outs = ntfs_malloc(outs_len); - if (!*outs) - goto out; - } + if (!*outs) { + outs_len = size + 1; + *outs = ntfs_malloc(outs_len); + if (!*outs) + goto out; + } - t = *outs; - - for (i = 0; i < ins_len && ins[i]; i++) { - unsigned short c = le16_to_cpu(ins[i]); - /* size not double-checked */ - if (halfpair) { - if ((c >= 0xdc00) && (c < 0xe000)) { - *t++ = 0xf0 + (((halfpair + 64) >> 8) & 7); - *t++ = 0x80 + (((halfpair + 64) >> 2) & 63); - *t++ = 0x80 + ((c >> 6) & 15) + ((halfpair & 3) << 4); - *t++ = 0x80 + (c & 63); - halfpair = 0; - } else - goto fail; - } else if (c < 0x80) { - *t++ = c; - } else { - if (c < 0x800) { - *t++ = (0xc0 | ((c >> 6) & 0x3f)); - *t++ = 0x80 | (c & 0x3f); - } else if (c < 0xd800) { - *t++ = 0xe0 | (c >> 12); - *t++ = 0x80 | ((c >> 6) & 0x3f); - *t++ = 0x80 | (c & 0x3f); - } else if (c < 0xdc00) - halfpair = c; - else if (c >= 0xe000) { - *t++ = 0xe0 | (c >> 12); - *t++ = 0x80 | ((c >> 6) & 0x3f); - *t++ = 0x80 | (c & 0x3f); - } else - goto fail; - } - } - *t = '\0'; + t = *outs; + for (i = 0; i < ins_len && ins[i]; i++) { + unsigned short c = le16_to_cpu(ins[i]); + /* size not double-checked */ + if (halfpair) { + if ((c >= 0xdc00) && (c < 0xe000)) { + *t++ = 0xf0 + (((halfpair + 64) >> 8) & 7); + *t++ = 0x80 + (((halfpair + 64) >> 2) & 63); + *t++ = 0x80 + ((c >> 6) & 15) + ((halfpair & 3) << 4); + *t++ = 0x80 + (c & 63); + halfpair = 0; + } else + goto fail; + } else if (c < 0x80) { + *t++ = c; + } else { + if (c < 0x800) { + *t++ = (0xc0 | ((c >> 6) & 0x3f)); + *t++ = 0x80 | (c & 0x3f); + } else if (c < 0xd800) { + *t++ = 0xe0 | (c >> 12); + *t++ = 0x80 | ((c >> 6) & 0x3f); + *t++ = 0x80 | (c & 0x3f); + } else if (c < 0xdc00) + halfpair = c; + else if (c >= 0xe000) { + *t++ = 0xe0 | (c >> 12); + *t++ = 0x80 | ((c >> 6) & 0x3f); + *t++ = 0x80 | (c & 0x3f); + } else + goto fail; + } + } + *t = '\0'; + #if defined(__APPLE__) || defined(__DARWIN__) #ifdef ENABLE_NFCONV - if (nfconvert_utf8 && (t - *outs) > 0) { - char *new_outs = NULL; - int new_outs_len = ntfs_macosx_normalize_utf8(*outs, &new_outs, 0); // Normalize to decomposed form - if (new_outs_len >= 0 && new_outs != NULL) { - if (original_outs_value != *outs) { - // We have allocated outs ourselves. - free(*outs); - *outs = new_outs; - t = *outs + new_outs_len; - } else { - // We need to copy new_outs into the fixed outs buffer. - memset(*outs, 0, original_outs_len); - strncpy(*outs, new_outs, original_outs_len-1); - t = *outs + original_outs_len; - free(new_outs); - } - } else { - ntfs_log_error("Failed to normalize NTFS string to UTF-8 NFD: %s\n", *outs); - ntfs_log_error(" new_outs=0x%p\n", new_outs); - ntfs_log_error(" new_outs_len=%d\n", new_outs_len); - } - } + if(nfconvert_utf8 && (t - *outs) > 0) { + char *new_outs = NULL; + int new_outs_len = ntfs_macosx_normalize_utf8(*outs, &new_outs, 0); // Normalize to decomposed form + if(new_outs_len >= 0 && new_outs != NULL) { + if(original_outs_value != *outs) { + // We have allocated outs ourselves. + free(*outs); + *outs = new_outs; + t = *outs + new_outs_len; + } + else { + // We need to copy new_outs into the fixed outs buffer. + memset(*outs, 0, original_outs_len); + strncpy(*outs, new_outs, original_outs_len-1); + t = *outs + original_outs_len; + free(new_outs); + } + } + else { + ntfs_log_error("Failed to normalize NTFS string to UTF-8 NFD: %s\n", *outs); + ntfs_log_error(" new_outs=0x%p\n", new_outs); + ntfs_log_error(" new_outs_len=%d\n", new_outs_len); + } + } #endif /* ENABLE_NFCONV */ #endif /* defined(__APPLE__) || defined(__DARWIN__) */ - - ret = t - *outs; + + ret = t - *outs; out: - return ret; + return ret; fail: - errno = EILSEQ; - goto out; + errno = EILSEQ; + goto out; } -/* - * Return the amount of 16-bit elements in UTF-16LE needed +/* + * Return the amount of 16-bit elements in UTF-16LE needed * (without the terminating null) to store given UTF-8 string. * * Return -1 with errno set if it's longer than PATH_MAX or string is invalid. @@ -592,109 +605,111 @@ fail: * Note: This does not check whether the input sequence is a valid utf8 string, * and should be used only in context where such check is made! */ -static int utf8_to_utf16_size(const char *s) { - int ret = -1; - unsigned int byte; - size_t count = 0; +static int utf8_to_utf16_size(const char *s) +{ + int ret = -1; + unsigned int byte; + size_t count = 0; - while ((byte = *((const unsigned char *)s++))) { - if (++count >= PATH_MAX) - goto fail; - if (byte >= 0xF5) { - errno = EILSEQ; - goto out; - } - if (!*s) - break; - if (byte >= 0xC0) - s++; - if (!*s) - break; - if (byte >= 0xE0) - s++; - if (!*s) - break; - if (byte >= 0xF0) { - s++; - if (++count >= PATH_MAX) - goto fail; - } - } - ret = count; + while ((byte = *((const unsigned char *)s++))) { + if (++count >= PATH_MAX) + goto fail; + if (byte >= 0xF5) { + errno = EILSEQ; + goto out; + } + if (!*s) + break; + if (byte >= 0xC0) + s++; + if (!*s) + break; + if (byte >= 0xE0) + s++; + if (!*s) + break; + if (byte >= 0xF0) { + s++; + if (++count >= PATH_MAX) + goto fail; + } + } + ret = count; out: - return ret; + return ret; fail: - errno = ENAMETOOLONG; - goto out; + errno = ENAMETOOLONG; + goto out; } -/* +/* * This converts one UTF-8 sequence to cpu-endian Unicode value * within range U+0 .. U+10ffff and excluding U+D800 .. U+DFFF * - * Return the number of used utf8 bytes or -1 with errno set + * Return the number of used utf8 bytes or -1 with errno set * if sequence is invalid. */ -static int utf8_to_unicode(u32 *wc, const char *s) { - unsigned int byte = *((const unsigned char *)s); +static int utf8_to_unicode(u32 *wc, const char *s) +{ + unsigned int byte = *((const unsigned char *)s); - /* single byte */ - if (byte == 0) { - *wc = (u32) 0; - return 0; - } else if (byte < 0x80) { - *wc = (u32) byte; - return 1; - /* double byte */ - } else if (byte < 0xc2) { - goto fail; - } else if (byte < 0xE0) { - if (strlen(s) < 2) - goto fail; - if ((s[1] & 0xC0) == 0x80) { - *wc = ((u32)(byte & 0x1F) << 6) - | ((u32)(s[1] & 0x3F)); - return 2; - } else - goto fail; - /* three-byte */ - } else if (byte < 0xF0) { - if (strlen(s) < 3) - goto fail; - if (((s[1] & 0xC0) == 0x80) && ((s[2] & 0xC0) == 0x80)) { - *wc = ((u32)(byte & 0x0F) << 12) - | ((u32)(s[1] & 0x3F) << 6) - | ((u32)(s[2] & 0x3F)); - /* Check valid ranges */ + /* single byte */ + if (byte == 0) { + *wc = (u32) 0; + return 0; + } else if (byte < 0x80) { + *wc = (u32) byte; + return 1; + /* double byte */ + } else if (byte < 0xc2) { + goto fail; + } else if (byte < 0xE0) { + if (strlen(s) < 2) + goto fail; + if ((s[1] & 0xC0) == 0x80) { + *wc = ((u32)(byte & 0x1F) << 6) + | ((u32)(s[1] & 0x3F)); + return 2; + } else + goto fail; + /* three-byte */ + } else if (byte < 0xF0) { + if (strlen(s) < 3) + goto fail; + if (((s[1] & 0xC0) == 0x80) && ((s[2] & 0xC0) == 0x80)) { + *wc = ((u32)(byte & 0x0F) << 12) + | ((u32)(s[1] & 0x3F) << 6) + | ((u32)(s[2] & 0x3F)); + /* Check valid ranges */ #if NOREVBOM - if (((*wc >= 0x800) && (*wc <= 0xD7FF)) - || ((*wc >= 0xe000) && (*wc <= 0xFFFD))) - return 3; + if (((*wc >= 0x800) && (*wc <= 0xD7FF)) + || ((*wc >= 0xe000) && (*wc <= 0xFFFD))) + return 3; #else - if (((*wc >= 0x800) && (*wc <= 0xD7FF)) - || ((*wc >= 0xe000) && (*wc <= 0xFFFF))) - return 3; + if (((*wc >= 0x800) && (*wc <= 0xD7FF)) + || ((*wc >= 0xe000) && (*wc <= 0xFFFF))) + return 3; #endif - } - goto fail; - /* four-byte */ - } else if (byte < 0xF5) { - if (strlen(s) < 4) - goto fail; - if (((s[1] & 0xC0) == 0x80) && ((s[2] & 0xC0) == 0x80) - && ((s[3] & 0xC0) == 0x80)) { - *wc = ((u32)(byte & 0x07) << 18) - | ((u32)(s[1] & 0x3F) << 12) - | ((u32)(s[2] & 0x3F) << 6) - | ((u32)(s[3] & 0x3F)); - /* Check valid ranges */ - if ((*wc <= 0x10ffff) && (*wc >= 0x10000)) - return 4; - } - goto fail; - } + } + goto fail; + /* four-byte */ + } else if (byte < 0xF5) { + if (strlen(s) < 4) + goto fail; + if (((s[1] & 0xC0) == 0x80) && ((s[2] & 0xC0) == 0x80) + && ((s[3] & 0xC0) == 0x80)) { + *wc = ((u32)(byte & 0x07) << 18) + | ((u32)(s[1] & 0x3F) << 12) + | ((u32)(s[2] & 0x3F) << 6) + | ((u32)(s[3] & 0x3F)); + /* Check valid ranges */ + if ((*wc <= 0x10ffff) && (*wc >= 0x10000)) + return 4; + } + goto fail; + } fail: - errno = EILSEQ; - return -1; + errno = EILSEQ; + return -1; } /** @@ -702,65 +717,66 @@ fail: * @ins: input multibyte string buffer * @outs: on return contains the (allocated) output utf16 string * @outs_len: length of output buffer in utf16 characters - * + * * Return -1 with errno set. */ -static int ntfs_utf8_to_utf16(const char *ins, ntfschar **outs) { +static int ntfs_utf8_to_utf16(const char *ins, ntfschar **outs) +{ #if defined(__APPLE__) || defined(__DARWIN__) #ifdef ENABLE_NFCONV - char *new_ins = NULL; - if (nfconvert_utf8) { - int new_ins_len; - new_ins_len = ntfs_macosx_normalize_utf8(ins, &new_ins, 1); // Normalize to composed form - if (new_ins_len >= 0) - ins = new_ins; - else - ntfs_log_error("Failed to normalize NTFS string to UTF-8 NFC: %s\n", ins); - } + char *new_ins = NULL; + if(nfconvert_utf8) { + int new_ins_len; + new_ins_len = ntfs_macosx_normalize_utf8(ins, &new_ins, 1); // Normalize to composed form + if(new_ins_len >= 0) + ins = new_ins; + else + ntfs_log_error("Failed to normalize NTFS string to UTF-8 NFC: %s\n", ins); + } #endif /* ENABLE_NFCONV */ #endif /* defined(__APPLE__) || defined(__DARWIN__) */ - const char *t = ins; - u32 wc; - ntfschar *outpos; - int shorts, ret = -1; + const char *t = ins; + u32 wc; + ntfschar *outpos; + int shorts, ret = -1; - shorts = utf8_to_utf16_size(ins); - if (shorts < 0) - goto fail; + shorts = utf8_to_utf16_size(ins); + if (shorts < 0) + goto fail; - if (!*outs) { - *outs = ntfs_malloc((shorts + 1) * sizeof(ntfschar)); - if (!*outs) - goto fail; - } + if (!*outs) { + *outs = ntfs_malloc((shorts + 1) * sizeof(ntfschar)); + if (!*outs) + goto fail; + } - outpos = *outs; + outpos = *outs; - while (1) { - int m = utf8_to_unicode(&wc, t); - if (m < 0) - goto fail; - if (wc < 0x10000) - *outpos++ = cpu_to_le16(wc); - else { - wc -= 0x10000; - *outpos++ = cpu_to_le16((wc >> 10) + 0xd800); - *outpos++ = cpu_to_le16((wc & 0x3ff) + 0xdc00); - } - if (m == 0) - break; - t += m; - } - - ret = --outpos - *outs; + while(1) { + int m = utf8_to_unicode(&wc, t); + if (m < 0) + goto fail; + if (wc < 0x10000) + *outpos++ = cpu_to_le16(wc); + else { + wc -= 0x10000; + *outpos++ = cpu_to_le16((wc >> 10) + 0xd800); + *outpos++ = cpu_to_le16((wc & 0x3ff) + 0xdc00); + } + if (m == 0) + break; + t += m; + } + + ret = --outpos - *outs; fail: #if defined(__APPLE__) || defined(__DARWIN__) #ifdef ENABLE_NFCONV - if (new_ins != NULL) - free(new_ins); + if(new_ins != NULL) + free(new_ins); #endif /* ENABLE_NFCONV */ #endif /* defined(__APPLE__) || defined(__DARWIN__) */ - return ret; + return ret; } /** @@ -789,93 +805,94 @@ fail: * ENOMEM Not enough memory to allocate destination buffer. */ int ntfs_ucstombs(const ntfschar *ins, const int ins_len, char **outs, - int outs_len) { - char *mbs; - wchar_t wc; - int i, o, mbs_len; - int cnt = 0; + int outs_len) +{ + char *mbs; + wchar_t wc; + int i, o, mbs_len; + int cnt = 0; #ifdef HAVE_MBSINIT - mbstate_t mbstate; + mbstate_t mbstate; #endif - if (!ins || !outs) { - errno = EINVAL; - return -1; - } - mbs = *outs; - mbs_len = outs_len; - if (mbs && !mbs_len) { - errno = ENAMETOOLONG; - return -1; - } - if (use_utf8) - return ntfs_utf16_to_utf8(ins, ins_len, outs, outs_len); - if (!mbs) { - mbs_len = (ins_len + 1) * MB_CUR_MAX; - mbs = ntfs_malloc(mbs_len); - if (!mbs) - return -1; - } + if (!ins || !outs) { + errno = EINVAL; + return -1; + } + mbs = *outs; + mbs_len = outs_len; + if (mbs && !mbs_len) { + errno = ENAMETOOLONG; + return -1; + } + if (use_utf8) + return ntfs_utf16_to_utf8(ins, ins_len, outs, outs_len); + if (!mbs) { + mbs_len = (ins_len + 1) * MB_CUR_MAX; + mbs = ntfs_malloc(mbs_len); + if (!mbs) + return -1; + } #ifdef HAVE_MBSINIT - memset(&mbstate, 0, sizeof(mbstate)); + memset(&mbstate, 0, sizeof(mbstate)); #else - wctomb(NULL, 0); + wctomb(NULL, 0); #endif - for (i = o = 0; i < ins_len; i++) { - /* Reallocate memory if necessary or abort. */ - if ((int)(o + MB_CUR_MAX) > mbs_len) { - char *tc; - if (mbs == *outs) { - errno = ENAMETOOLONG; - return -1; - } - tc = ntfs_malloc((mbs_len + 64) & ~63); - if (!tc) - goto err_out; - memcpy(tc, mbs, mbs_len); - mbs_len = (mbs_len + 64) & ~63; - free(mbs); - mbs = tc; - } - /* Convert the LE Unicode character to a CPU wide character. */ - wc = (wchar_t)le16_to_cpu(ins[i]); - if (!wc) - break; - /* Convert the CPU endian wide character to multibyte. */ + for (i = o = 0; i < ins_len; i++) { + /* Reallocate memory if necessary or abort. */ + if ((int)(o + MB_CUR_MAX) > mbs_len) { + char *tc; + if (mbs == *outs) { + errno = ENAMETOOLONG; + return -1; + } + tc = ntfs_malloc((mbs_len + 64) & ~63); + if (!tc) + goto err_out; + memcpy(tc, mbs, mbs_len); + mbs_len = (mbs_len + 64) & ~63; + free(mbs); + mbs = tc; + } + /* Convert the LE Unicode character to a CPU wide character. */ + wc = (wchar_t)le16_to_cpu(ins[i]); + if (!wc) + break; + /* Convert the CPU endian wide character to multibyte. */ #ifdef HAVE_MBSINIT - cnt = wcrtomb(mbs + o, wc, &mbstate); + cnt = wcrtomb(mbs + o, wc, &mbstate); #else - cnt = wctomb(mbs + o, wc); + cnt = wctomb(mbs + o, wc); #endif - if (cnt == -1) - goto err_out; - if (cnt <= 0) { - ntfs_log_debug("Eeek. cnt <= 0, cnt = %i\n", cnt); - errno = EINVAL; - goto err_out; - } - o += cnt; - } + if (cnt == -1) + goto err_out; + if (cnt <= 0) { + ntfs_log_debug("Eeek. cnt <= 0, cnt = %i\n", cnt); + errno = EINVAL; + goto err_out; + } + o += cnt; + } #ifdef HAVE_MBSINIT - /* Make sure we are back in the initial state. */ - if (!mbsinit(&mbstate)) { - ntfs_log_debug("Eeek. mbstate not in initial state!\n"); - errno = EILSEQ; - goto err_out; - } + /* Make sure we are back in the initial state. */ + if (!mbsinit(&mbstate)) { + ntfs_log_debug("Eeek. mbstate not in initial state!\n"); + errno = EILSEQ; + goto err_out; + } #endif - /* Now write the NULL character. */ - mbs[o] = '\0'; - if (*outs != mbs) - *outs = mbs; - return o; + /* Now write the NULL character. */ + mbs[o] = '\0'; + if (*outs != mbs) + *outs = mbs; + return o; err_out: - if (mbs != *outs) { - int eo = errno; - free(mbs); - errno = eo; - } - return -1; + if (mbs != *outs) { + int eo = errno; + free(mbs); + errno = eo; + } + return -1; } /** @@ -886,7 +903,7 @@ err_out: * Convert the input multibyte string @ins, from the current locale into the * corresponding little endian, 2-byte Unicode string. * - * The function allocates the string and the caller is responsible for calling + * The function allocates the string and the caller is responsible for calling * free(*@outs); when finished with it. * * On success the function returns the number of Unicode characters written to @@ -901,113 +918,114 @@ err_out: * ENAMETOOLONG Destination buffer is too small for input string. * ENOMEM Not enough memory to allocate destination buffer. */ -int ntfs_mbstoucs(const char *ins, ntfschar **outs) { - ntfschar *ucs; - const char *s; - wchar_t wc; - int i, o, cnt, ins_len, ucs_len, ins_size; +int ntfs_mbstoucs(const char *ins, ntfschar **outs) +{ + ntfschar *ucs; + const char *s; + wchar_t wc; + int i, o, cnt, ins_len, ucs_len, ins_size; #ifdef HAVE_MBSINIT - mbstate_t mbstate; + mbstate_t mbstate; #endif - if (!ins || !outs) { - errno = EINVAL; - return -1; - } + if (!ins || !outs) { + errno = EINVAL; + return -1; + } + + if (use_utf8) + return ntfs_utf8_to_utf16(ins, outs); - if (use_utf8) - return ntfs_utf8_to_utf16(ins, outs); - - /* Determine the size of the multi-byte string in bytes. */ - ins_size = strlen(ins); - /* Determine the length of the multi-byte string. */ - s = ins; + /* Determine the size of the multi-byte string in bytes. */ + ins_size = strlen(ins); + /* Determine the length of the multi-byte string. */ + s = ins; #if defined(HAVE_MBSINIT) - memset(&mbstate, 0, sizeof(mbstate)); - ins_len = mbsrtowcs(NULL, (const char **)&s, 0, &mbstate); + memset(&mbstate, 0, sizeof(mbstate)); + ins_len = mbsrtowcs(NULL, (const char **)&s, 0, &mbstate); #ifdef __CYGWIN32__ - if (!ins_len && *ins) { - /* Older Cygwin had broken mbsrtowcs() implementation. */ - ins_len = strlen(ins); - } + if (!ins_len && *ins) { + /* Older Cygwin had broken mbsrtowcs() implementation. */ + ins_len = strlen(ins); + } #endif #elif !defined(DJGPP) - ins_len = mbstowcs(NULL, s, 0); + ins_len = mbstowcs(NULL, s, 0); #else - /* Eeek!!! DJGPP has broken mbstowcs() implementation!!! */ - ins_len = strlen(ins); + /* Eeek!!! DJGPP has broken mbstowcs() implementation!!! */ + ins_len = strlen(ins); #endif - if (ins_len == -1) - return ins_len; + if (ins_len == -1) + return ins_len; #ifdef HAVE_MBSINIT - if ((s != ins) || !mbsinit(&mbstate)) { + if ((s != ins) || !mbsinit(&mbstate)) { #else - if (s != ins) { + if (s != ins) { #endif - errno = EILSEQ; - return -1; - } - /* Add the NULL terminator. */ - ins_len++; - ucs_len = ins_len; - ucs = ntfs_malloc(ucs_len * sizeof(ntfschar)); - if (!ucs) - return -1; + errno = EILSEQ; + return -1; + } + /* Add the NULL terminator. */ + ins_len++; + ucs_len = ins_len; + ucs = ntfs_malloc(ucs_len * sizeof(ntfschar)); + if (!ucs) + return -1; #ifdef HAVE_MBSINIT - memset(&mbstate, 0, sizeof(mbstate)); + memset(&mbstate, 0, sizeof(mbstate)); #else - mbtowc(NULL, NULL, 0); + mbtowc(NULL, NULL, 0); #endif - for (i = o = cnt = 0; i < ins_size; i += cnt, o++) { - /* Reallocate memory if necessary. */ - if (o >= ucs_len) { - ntfschar *tc; - ucs_len = (ucs_len * sizeof(ntfschar) + 64) & ~63; - tc = realloc(ucs, ucs_len); - if (!tc) - goto err_out; - ucs = tc; - ucs_len /= sizeof(ntfschar); - } - /* Convert the multibyte character to a wide character. */ + for (i = o = cnt = 0; i < ins_size; i += cnt, o++) { + /* Reallocate memory if necessary. */ + if (o >= ucs_len) { + ntfschar *tc; + ucs_len = (ucs_len * sizeof(ntfschar) + 64) & ~63; + tc = realloc(ucs, ucs_len); + if (!tc) + goto err_out; + ucs = tc; + ucs_len /= sizeof(ntfschar); + } + /* Convert the multibyte character to a wide character. */ #ifdef HAVE_MBSINIT - cnt = mbrtowc(&wc, ins + i, ins_size - i, &mbstate); + cnt = mbrtowc(&wc, ins + i, ins_size - i, &mbstate); #else - cnt = mbtowc(&wc, ins + i, ins_size - i); + cnt = mbtowc(&wc, ins + i, ins_size - i); #endif - if (!cnt) - break; - if (cnt == -1) - goto err_out; - if (cnt < -1) { - ntfs_log_trace("Eeek. cnt = %i\n", cnt); - errno = EINVAL; - goto err_out; - } - /* Make sure we are not overflowing the NTFS Unicode set. */ - if ((unsigned long)wc >= (unsigned long)(1 << - (8 * sizeof(ntfschar)))) { - errno = EILSEQ; - goto err_out; - } - /* Convert the CPU wide character to a LE Unicode character. */ - ucs[o] = cpu_to_le16(wc); - } + if (!cnt) + break; + if (cnt == -1) + goto err_out; + if (cnt < -1) { + ntfs_log_trace("Eeek. cnt = %i\n", cnt); + errno = EINVAL; + goto err_out; + } + /* Make sure we are not overflowing the NTFS Unicode set. */ + if ((unsigned long)wc >= (unsigned long)(1 << + (8 * sizeof(ntfschar)))) { + errno = EILSEQ; + goto err_out; + } + /* Convert the CPU wide character to a LE Unicode character. */ + ucs[o] = cpu_to_le16(wc); + } #ifdef HAVE_MBSINIT - /* Make sure we are back in the initial state. */ - if (!mbsinit(&mbstate)) { - ntfs_log_trace("Eeek. mbstate not in initial state!\n"); - errno = EILSEQ; - goto err_out; - } + /* Make sure we are back in the initial state. */ + if (!mbsinit(&mbstate)) { + ntfs_log_trace("Eeek. mbstate not in initial state!\n"); + errno = EILSEQ; + goto err_out; + } #endif - /* Now write the NULL character. */ - ucs[o] = cpu_to_le16(L'\0'); - *outs = ucs; - return o; + /* Now write the NULL character. */ + ucs[o] = cpu_to_le16(L'\0'); + *outs = ucs; + return o; err_out: - free(ucs); - return -1; + free(ucs); + return -1; } /** @@ -1020,64 +1038,65 @@ err_out: * * Note, @uc_len must be at least 128kiB in size or bad things will happen! */ -void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len) { - static int uc_run_table[][3] = { /* Start, End, Add */ - {0x0061, 0x007B, -32}, {0x0451, 0x045D, -80}, {0x1F70, 0x1F72, 74}, - {0x00E0, 0x00F7, -32}, {0x045E, 0x0460, -80}, {0x1F72, 0x1F76, 86}, - {0x00F8, 0x00FF, -32}, {0x0561, 0x0587, -48}, {0x1F76, 0x1F78, 100}, - {0x0256, 0x0258, -205}, {0x1F00, 0x1F08, 8}, {0x1F78, 0x1F7A, 128}, - {0x028A, 0x028C, -217}, {0x1F10, 0x1F16, 8}, {0x1F7A, 0x1F7C, 112}, - {0x03AC, 0x03AD, -38}, {0x1F20, 0x1F28, 8}, {0x1F7C, 0x1F7E, 126}, - {0x03AD, 0x03B0, -37}, {0x1F30, 0x1F38, 8}, {0x1FB0, 0x1FB2, 8}, - {0x03B1, 0x03C2, -32}, {0x1F40, 0x1F46, 8}, {0x1FD0, 0x1FD2, 8}, - {0x03C2, 0x03C3, -31}, {0x1F51, 0x1F52, 8}, {0x1FE0, 0x1FE2, 8}, - {0x03C3, 0x03CC, -32}, {0x1F53, 0x1F54, 8}, {0x1FE5, 0x1FE6, 7}, - {0x03CC, 0x03CD, -64}, {0x1F55, 0x1F56, 8}, {0x2170, 0x2180, -16}, - {0x03CD, 0x03CF, -63}, {0x1F57, 0x1F58, 8}, {0x24D0, 0x24EA, -26}, - {0x0430, 0x0450, -32}, {0x1F60, 0x1F68, 8}, {0xFF41, 0xFF5B, -32}, - {0} - }; - static int uc_dup_table[][2] = { /* Start, End */ - {0x0100, 0x012F}, {0x01A0, 0x01A6}, {0x03E2, 0x03EF}, {0x04CB, 0x04CC}, - {0x0132, 0x0137}, {0x01B3, 0x01B7}, {0x0460, 0x0481}, {0x04D0, 0x04EB}, - {0x0139, 0x0149}, {0x01CD, 0x01DD}, {0x0490, 0x04BF}, {0x04EE, 0x04F5}, - {0x014A, 0x0178}, {0x01DE, 0x01EF}, {0x04BF, 0x04BF}, {0x04F8, 0x04F9}, - {0x0179, 0x017E}, {0x01F4, 0x01F5}, {0x04C1, 0x04C4}, {0x1E00, 0x1E95}, - {0x018B, 0x018B}, {0x01FA, 0x0218}, {0x04C7, 0x04C8}, {0x1EA0, 0x1EF9}, - {0} - }; - static int uc_byte_table[][2] = { /* Offset, Value */ - {0x00FF, 0x0178}, {0x01AD, 0x01AC}, {0x01F3, 0x01F1}, {0x0269, 0x0196}, - {0x0183, 0x0182}, {0x01B0, 0x01AF}, {0x0253, 0x0181}, {0x026F, 0x019C}, - {0x0185, 0x0184}, {0x01B9, 0x01B8}, {0x0254, 0x0186}, {0x0272, 0x019D}, - {0x0188, 0x0187}, {0x01BD, 0x01BC}, {0x0259, 0x018F}, {0x0275, 0x019F}, - {0x018C, 0x018B}, {0x01C6, 0x01C4}, {0x025B, 0x0190}, {0x0283, 0x01A9}, - {0x0192, 0x0191}, {0x01C9, 0x01C7}, {0x0260, 0x0193}, {0x0288, 0x01AE}, - {0x0199, 0x0198}, {0x01CC, 0x01CA}, {0x0263, 0x0194}, {0x0292, 0x01B7}, - {0x01A8, 0x01A7}, {0x01DD, 0x018E}, {0x0268, 0x0197}, - {0} - }; - int i, r; - int k, off; +void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len) +{ + static int uc_run_table[][3] = { /* Start, End, Add */ + {0x0061, 0x007B, -32}, {0x0451, 0x045D, -80}, {0x1F70, 0x1F72, 74}, + {0x00E0, 0x00F7, -32}, {0x045E, 0x0460, -80}, {0x1F72, 0x1F76, 86}, + {0x00F8, 0x00FF, -32}, {0x0561, 0x0587, -48}, {0x1F76, 0x1F78, 100}, + {0x0256, 0x0258, -205}, {0x1F00, 0x1F08, 8}, {0x1F78, 0x1F7A, 128}, + {0x028A, 0x028C, -217}, {0x1F10, 0x1F16, 8}, {0x1F7A, 0x1F7C, 112}, + {0x03AC, 0x03AD, -38}, {0x1F20, 0x1F28, 8}, {0x1F7C, 0x1F7E, 126}, + {0x03AD, 0x03B0, -37}, {0x1F30, 0x1F38, 8}, {0x1FB0, 0x1FB2, 8}, + {0x03B1, 0x03C2, -32}, {0x1F40, 0x1F46, 8}, {0x1FD0, 0x1FD2, 8}, + {0x03C2, 0x03C3, -31}, {0x1F51, 0x1F52, 8}, {0x1FE0, 0x1FE2, 8}, + {0x03C3, 0x03CC, -32}, {0x1F53, 0x1F54, 8}, {0x1FE5, 0x1FE6, 7}, + {0x03CC, 0x03CD, -64}, {0x1F55, 0x1F56, 8}, {0x2170, 0x2180, -16}, + {0x03CD, 0x03CF, -63}, {0x1F57, 0x1F58, 8}, {0x24D0, 0x24EA, -26}, + {0x0430, 0x0450, -32}, {0x1F60, 0x1F68, 8}, {0xFF41, 0xFF5B, -32}, + {0} + }; + static int uc_dup_table[][2] = { /* Start, End */ + {0x0100, 0x012F}, {0x01A0, 0x01A6}, {0x03E2, 0x03EF}, {0x04CB, 0x04CC}, + {0x0132, 0x0137}, {0x01B3, 0x01B7}, {0x0460, 0x0481}, {0x04D0, 0x04EB}, + {0x0139, 0x0149}, {0x01CD, 0x01DD}, {0x0490, 0x04BF}, {0x04EE, 0x04F5}, + {0x014A, 0x0178}, {0x01DE, 0x01EF}, {0x04BF, 0x04BF}, {0x04F8, 0x04F9}, + {0x0179, 0x017E}, {0x01F4, 0x01F5}, {0x04C1, 0x04C4}, {0x1E00, 0x1E95}, + {0x018B, 0x018B}, {0x01FA, 0x0218}, {0x04C7, 0x04C8}, {0x1EA0, 0x1EF9}, + {0} + }; + static int uc_byte_table[][2] = { /* Offset, Value */ + {0x00FF, 0x0178}, {0x01AD, 0x01AC}, {0x01F3, 0x01F1}, {0x0269, 0x0196}, + {0x0183, 0x0182}, {0x01B0, 0x01AF}, {0x0253, 0x0181}, {0x026F, 0x019C}, + {0x0185, 0x0184}, {0x01B9, 0x01B8}, {0x0254, 0x0186}, {0x0272, 0x019D}, + {0x0188, 0x0187}, {0x01BD, 0x01BC}, {0x0259, 0x018F}, {0x0275, 0x019F}, + {0x018C, 0x018B}, {0x01C6, 0x01C4}, {0x025B, 0x0190}, {0x0283, 0x01A9}, + {0x0192, 0x0191}, {0x01C9, 0x01C7}, {0x0260, 0x0193}, {0x0288, 0x01AE}, + {0x0199, 0x0198}, {0x01CC, 0x01CA}, {0x0263, 0x0194}, {0x0292, 0x01B7}, + {0x01A8, 0x01A7}, {0x01DD, 0x018E}, {0x0268, 0x0197}, + {0} + }; + int i, r; + int k, off; - memset((char*)uc, 0, uc_len); - uc_len >>= 1; - if (uc_len > 65536) - uc_len = 65536; - for (i = 0; (u32)i < uc_len; i++) - uc[i] = cpu_to_le16(i); - for (r = 0; uc_run_table[r][0]; r++) { - off = uc_run_table[r][2]; - for (i = uc_run_table[r][0]; i < uc_run_table[r][1]; i++) - uc[i] = cpu_to_le16(i + off); - } - for (r = 0; uc_dup_table[r][0]; r++) - for (i = uc_dup_table[r][0]; i < uc_dup_table[r][1]; i += 2) - uc[i + 1] = cpu_to_le16(i); - for (r = 0; uc_byte_table[r][0]; r++) { - k = uc_byte_table[r][1]; - uc[uc_byte_table[r][0]] = cpu_to_le16(k); - } + memset((char*)uc, 0, uc_len); + uc_len >>= 1; + if (uc_len > 65536) + uc_len = 65536; + for (i = 0; (u32)i < uc_len; i++) + uc[i] = cpu_to_le16(i); + for (r = 0; uc_run_table[r][0]; r++) { + off = uc_run_table[r][2]; + for (i = uc_run_table[r][0]; i < uc_run_table[r][1]; i++) + uc[i] = cpu_to_le16(i + off); + } + for (r = 0; uc_dup_table[r][0]; r++) + for (i = uc_dup_table[r][0]; i < uc_dup_table[r][1]; i += 2) + uc[i + 1] = cpu_to_le16(i); + for (r = 0; uc_byte_table[r][0]; r++) { + k = uc_byte_table[r][1]; + uc[uc_byte_table[r][0]] = cpu_to_le16(k); + } } /** @@ -1086,34 +1105,35 @@ void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len) { * @len: length of output buffer in Unicode characters * * Convert the input @s string into the corresponding little endian, - * 2-byte Unicode string. The length of the converted string is less + * 2-byte Unicode string. The length of the converted string is less * or equal to the maximum length allowed by the NTFS format (255). * * If @s is NULL then return AT_UNNAMED. * - * On success the function returns the Unicode string in an allocated + * On success the function returns the Unicode string in an allocated * buffer and the caller is responsible to free it when it's not needed * anymore. * * On error NULL is returned and errno is set to the error code. */ -ntfschar *ntfs_str2ucs(const char *s, int *len) { - ntfschar *ucs = NULL; +ntfschar *ntfs_str2ucs(const char *s, int *len) +{ + ntfschar *ucs = NULL; - if (s && ((*len = ntfs_mbstoucs(s, &ucs)) == -1)) { - ntfs_log_perror("Couldn't convert '%s' to Unicode", s); - return NULL; - } - if (*len > NTFS_MAX_NAME_LEN) { - free(ucs); - errno = ENAMETOOLONG; - return NULL; - } - if (!ucs || !*len) { - ucs = AT_UNNAMED; - *len = 0; - } - return ucs; + if (s && ((*len = ntfs_mbstoucs(s, &ucs)) == -1)) { + ntfs_log_perror("Couldn't convert '%s' to Unicode", s); + return NULL; + } + if (*len > NTFS_MAX_NAME_LEN) { + free(ucs); + errno = ENAMETOOLONG; + return NULL; + } + if (!ucs || !*len) { + ucs = AT_UNNAMED; + *len = 0; + } + return ucs; } /** @@ -1124,9 +1144,10 @@ ntfschar *ntfs_str2ucs(const char *s, int *len) { * * Return value: none. */ -void ntfs_ucsfree(ntfschar *ucs) { - if (ucs && (ucs != AT_UNNAMED)) - free(ucs); +void ntfs_ucsfree(ntfschar *ucs) +{ + if (ucs && (ucs != AT_UNNAMED)) + free(ucs); } /* @@ -1136,31 +1157,32 @@ void ntfs_ucsfree(ntfschar *ucs) { * If there is a bad char, errno is set to EINVAL */ -BOOL ntfs_forbidden_chars(const ntfschar *name, int len) { - BOOL forbidden; - int ch; - int i; - u32 mainset = (1L << ('\"' - 0x20)) - | (1L << ('*' - 0x20)) - | (1L << ('/' - 0x20)) - | (1L << (':' - 0x20)) - | (1L << ('<' - 0x20)) - | (1L << ('>' - 0x20)) - | (1L << ('?' - 0x20)); +BOOL ntfs_forbidden_chars(const ntfschar *name, int len) +{ + BOOL forbidden; + int ch; + int i; + u32 mainset = (1L << ('\"' - 0x20)) + | (1L << ('*' - 0x20)) + | (1L << ('/' - 0x20)) + | (1L << (':' - 0x20)) + | (1L << ('<' - 0x20)) + | (1L << ('>' - 0x20)) + | (1L << ('?' - 0x20)); - forbidden = (len == 0) || (le16_to_cpu(name[len-1]) == ' '); - for (i=0; i= vol->upcase_len) - || ((shortname[i] != longname[i]) - && (shortname[i] != vol->upcase[ch]))) - collapsible = FALSE; - } - return (collapsible); + collapsible = shortlen == longlen; + if (collapsible) + for (i=0; i= vol->upcase_len) + || ((shortname[i] != longname[i]) + && (shortname[i] != vol->upcase[ch]))) + collapsible = FALSE; + } + return (collapsible); } /* @@ -1195,92 +1218,97 @@ BOOL ntfs_collapsible_chars(ntfs_volume *vol, * Use UTF-8 unless specified otherwise. */ -int ntfs_set_char_encoding(const char *locale) { - use_utf8 = 0; - if (!locale || strstr(locale,"utf8") || strstr(locale,"UTF8") - || strstr(locale,"utf-8") || strstr(locale,"UTF-8")) - use_utf8 = 1; - else - if (setlocale(LC_ALL, locale)) - use_utf8 = 0; - else { - ntfs_log_error("Invalid locale, encoding to UTF-8\n"); - use_utf8 = 1; - } - return 0; /* always successful */ +int ntfs_set_char_encoding(const char *locale) +{ + use_utf8 = 0; + if (!locale || strstr(locale,"utf8") || strstr(locale,"UTF8") + || strstr(locale,"utf-8") || strstr(locale,"UTF-8")) + use_utf8 = 1; + else + if (setlocale(LC_ALL, locale)) + use_utf8 = 0; + else { + ntfs_log_error("Invalid locale, encoding to UTF-8\n"); + use_utf8 = 1; + } + return 0; /* always successful */ } #if defined(__APPLE__) || defined(__DARWIN__) int ntfs_macosx_normalize_filenames(int normalize) { #ifdef ENABLE_NFCONV - if (normalize == 0 || normalize == 1) { - nfconvert_utf8 = normalize; - return 0; - } else - return -1; + if(normalize == 0 || normalize == 1) { + nfconvert_utf8 = normalize; + return 0; + } + else + return -1; #else - return -1; + return -1; #endif /* ENABLE_NFCONV */ -} +} int ntfs_macosx_normalize_utf8(const char *utf8_string, char **target, - int composed) { + int composed) { #ifdef ENABLE_NFCONV - /* For this code to compile, the CoreFoundation framework must be fed to the linker. */ - CFStringRef cfSourceString; - CFMutableStringRef cfMutableString; - CFRange rangeToProcess; - CFIndex requiredBufferLength; - char *result = NULL; - int resultLength = -1; + /* For this code to compile, the CoreFoundation framework must be fed to the linker. */ + CFStringRef cfSourceString; + CFMutableStringRef cfMutableString; + CFRange rangeToProcess; + CFIndex requiredBufferLength; + char *result = NULL; + int resultLength = -1; + + /* Convert the UTF-8 string to a CFString. */ + cfSourceString = CFStringCreateWithCString(kCFAllocatorDefault, utf8_string, kCFStringEncodingUTF8); + if(cfSourceString == NULL) { + ntfs_log_error("CFStringCreateWithCString failed!\n"); + return -2; + } + + /* Create a mutable string from cfSourceString that we are free to modify. */ + cfMutableString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, cfSourceString); + CFRelease(cfSourceString); /* End-of-life. */ + if(cfMutableString == NULL) { + ntfs_log_error("CFStringCreateMutableCopy failed!\n"); + return -3; + } + + /* Normalize the mutable string to the desired normalization form. */ + CFStringNormalize(cfMutableString, (composed != 0 ? kCFStringNormalizationFormC : kCFStringNormalizationFormD)); + + /* Store the resulting string in a '\0'-terminated UTF-8 encoded char* buffer. */ + rangeToProcess = CFRangeMake(0, CFStringGetLength(cfMutableString)); + if(CFStringGetBytes(cfMutableString, rangeToProcess, kCFStringEncodingUTF8, 0, false, NULL, 0, &requiredBufferLength) > 0) { + resultLength = sizeof(char)*(requiredBufferLength + 1); + result = ntfs_calloc(resultLength); + + if(result != NULL) { + if(CFStringGetBytes(cfMutableString, rangeToProcess, kCFStringEncodingUTF8, + 0, false, (UInt8*)result, resultLength-1, &requiredBufferLength) <= 0) { + ntfs_log_error("Could not perform UTF-8 conversion of normalized CFMutableString.\n"); + free(result); + result = NULL; + } + } + else + ntfs_log_error("Could not perform a ntfs_calloc of %d bytes for char *result.\n", resultLength); + } + else + ntfs_log_error("Could not perform check for required length of UTF-8 conversion of normalized CFMutableString.\n"); - /* Convert the UTF-8 string to a CFString. */ - cfSourceString = CFStringCreateWithCString(kCFAllocatorDefault, utf8_string, kCFStringEncodingUTF8); - if (cfSourceString == NULL) { - ntfs_log_error("CFStringCreateWithCString failed!\n"); - return -2; - } - - /* Create a mutable string from cfSourceString that we are free to modify. */ - cfMutableString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, cfSourceString); - CFRelease(cfSourceString); /* End-of-life. */ - if (cfMutableString == NULL) { - ntfs_log_error("CFStringCreateMutableCopy failed!\n"); - return -3; - } - - /* Normalize the mutable string to the desired normalization form. */ - CFStringNormalize(cfMutableString, (composed != 0 ? kCFStringNormalizationFormC : kCFStringNormalizationFormD)); - - /* Store the resulting string in a '\0'-terminated UTF-8 encoded char* buffer. */ - rangeToProcess = CFRangeMake(0, CFStringGetLength(cfMutableString)); - if (CFStringGetBytes(cfMutableString, rangeToProcess, kCFStringEncodingUTF8, 0, false, NULL, 0, &requiredBufferLength) > 0) { - resultLength = sizeof(char)*(requiredBufferLength + 1); - result = ntfs_calloc(resultLength); - - if (result != NULL) { - if (CFStringGetBytes(cfMutableString, rangeToProcess, kCFStringEncodingUTF8, - 0, false, (UInt8*)result, resultLength-1, &requiredBufferLength) <= 0) { - ntfs_log_error("Could not perform UTF-8 conversion of normalized CFMutableString.\n"); - free(result); - result = NULL; - } - } else - ntfs_log_error("Could not perform a ntfs_calloc of %d bytes for char *result.\n", resultLength); - } else - ntfs_log_error("Could not perform check for required length of UTF-8 conversion of normalized CFMutableString.\n"); - - - CFRelease(cfMutableString); - - if (result != NULL) { - *target = result; - return resultLength - 1; - } else - return -1; + + CFRelease(cfMutableString); + + if(result != NULL) { + *target = result; + return resultLength - 1; + } + else + return -1; #else - return -1; + return -1; #endif /* ENABLE_NFCONV */ } #endif /* defined(__APPLE__) || defined(__DARWIN__) */ diff --git a/source/libntfs/unistr.h b/source/libntfs/unistr.h index 74ebbd18..115a8650 100644 --- a/source/libntfs/unistr.h +++ b/source/libntfs/unistr.h @@ -27,36 +27,36 @@ #include "layout.h" extern BOOL ntfs_names_are_equal(const ntfschar *s1, size_t s1_len, - const ntfschar *s2, size_t s2_len, const IGNORE_CASE_BOOL ic, - const ntfschar *upcase, const u32 upcase_size); + const ntfschar *s2, size_t s2_len, const IGNORE_CASE_BOOL ic, + const ntfschar *upcase, const u32 upcase_size); extern int ntfs_names_collate(const ntfschar *name1, const u32 name1_len, - const ntfschar *name2, const u32 name2_len, - const int err_val, const IGNORE_CASE_BOOL ic, - const ntfschar *upcase, const u32 upcase_len); + const ntfschar *name2, const u32 name2_len, + const int err_val, const IGNORE_CASE_BOOL ic, + const ntfschar *upcase, const u32 upcase_len); extern int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n); extern int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, - const ntfschar *upcase, const u32 upcase_size); + const ntfschar *upcase, const u32 upcase_size); extern u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen); extern ntfschar *ntfs_ucsndup(const ntfschar *s, u32 maxlen); extern void ntfs_name_upcase(ntfschar *name, u32 name_len, - const ntfschar *upcase, const u32 upcase_len); + const ntfschar *upcase, const u32 upcase_len); extern void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr, - const ntfschar *upcase, const u32 upcase_len); + const ntfschar *upcase, const u32 upcase_len); extern int ntfs_file_values_compare(const FILE_NAME_ATTR *file_name_attr1, - const FILE_NAME_ATTR *file_name_attr2, - const int err_val, const IGNORE_CASE_BOOL ic, - const ntfschar *upcase, const u32 upcase_len); + const FILE_NAME_ATTR *file_name_attr2, + const int err_val, const IGNORE_CASE_BOOL ic, + const ntfschar *upcase, const u32 upcase_len); extern int ntfs_ucstombs(const ntfschar *ins, const int ins_len, char **outs, - int outs_len); + int outs_len); extern int ntfs_mbstoucs(const char *ins, ntfschar **outs); extern void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len); @@ -67,8 +67,8 @@ extern void ntfs_ucsfree(ntfschar *ucs); extern BOOL ntfs_forbidden_chars(const ntfschar *name, int len); extern BOOL ntfs_collapsible_chars(ntfs_volume *vol, - const ntfschar *shortname, int shortlen, - const ntfschar *longname, int longlen); + const ntfschar *shortname, int shortlen, + const ntfschar *longname, int longlen); extern int ntfs_set_char_encoding(const char *locale); @@ -84,7 +84,7 @@ extern int ntfs_set_char_encoding(const char *locale); * normalization form. Since Windows and most other OS:es use the NFC form while Mac OS X * mostly uses NFD, this conversion increases compatibility between Mac applications and * NTFS-3G. - * + * * @param normalize decides whether or not the string functions will do automatic filename * normalization when converting to and from UTF-8. 0 means normalization is disabled, * 1 means it is enabled. @@ -94,7 +94,7 @@ extern int ntfs_macosx_normalize_filenames(int normalize); /** * Mac OS X only. - * + * * Normalizes the input string "utf8_string" to one of the normalization forms NFD or NFC. * The parameter "composed" decides whether output should be in composed, NFC, form * (composed == 1) or decomposed, NFD, form (composed == 0). diff --git a/source/libntfs/volume.c b/source/libntfs/volume.c index 6e1d1f00..74037d02 100644 --- a/source/libntfs/volume.c +++ b/source/libntfs/volume.c @@ -67,51 +67,51 @@ #include "logging.h" #include "misc.h" -const char *ntfs_home = - "Ntfs-3g news, support and information: http://ntfs-3g.org\n"; +const char *ntfs_home = +"Ntfs-3g news, support and information: http://ntfs-3g.org\n"; static const char *invalid_ntfs_msg = - "The device '%s' doesn't seem to have a valid NTFS.\n" - "Maybe the wrong device is used? Or the whole disk instead of a\n" - "partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?\n"; +"The device '%s' doesn't seem to have a valid NTFS.\n" +"Maybe the wrong device is used? Or the whole disk instead of a\n" +"partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?\n"; static const char *corrupt_volume_msg = - "NTFS is either inconsistent, or there is a hardware fault, or it's a\n" - "SoftRAID/FakeRAID hardware. In the first case run chkdsk /f on Windows\n" - "then reboot into Windows twice. The usage of the /f parameter is very\n" - "important! If the device is a SoftRAID/FakeRAID then first activate\n" - "it and mount a different device under the /dev/mapper/ directory, (e.g.\n" - "/dev/mapper/nvidia_eahaabcc1). Please see the 'dmraid' documentation\n" - "for more details.\n"; +"NTFS is either inconsistent, or there is a hardware fault, or it's a\n" +"SoftRAID/FakeRAID hardware. In the first case run chkdsk /f on Windows\n" +"then reboot into Windows twice. The usage of the /f parameter is very\n" +"important! If the device is a SoftRAID/FakeRAID then first activate\n" +"it and mount a different device under the /dev/mapper/ directory, (e.g.\n" +"/dev/mapper/nvidia_eahaabcc1). Please see the 'dmraid' documentation\n" +"for more details.\n"; static const char *hibernated_volume_msg = - "The NTFS partition is hibernated. Please resume and shutdown Windows\n" - "properly, or mount the volume read-only with the 'ro' mount option, or\n" - "mount the volume read-write with the 'remove_hiberfile' mount option.\n" - "For example type on the command line:\n" - "\n" - " mount -t ntfs-3g -o remove_hiberfile %s %s\n" - "\n"; +"The NTFS partition is hibernated. Please resume and shutdown Windows\n" +"properly, or mount the volume read-only with the 'ro' mount option, or\n" +"mount the volume read-write with the 'remove_hiberfile' mount option.\n" +"For example type on the command line:\n" +"\n" +" mount -t ntfs-3g -o remove_hiberfile %s %s\n" +"\n"; static const char *unclean_journal_msg = - "Write access is denied because the disk wasn't safely powered\n" - "off and the 'norecover' mount option was specified.\n"; +"Write access is denied because the disk wasn't safely powered\n" +"off and the 'norecover' mount option was specified.\n"; static const char *opened_volume_msg = - "Mount is denied because the NTFS volume is already exclusively opened.\n" - "The volume may be already mounted, or another software may use it which\n" - "could be identified for example by the help of the 'fuser' command.\n"; +"Mount is denied because the NTFS volume is already exclusively opened.\n" +"The volume may be already mounted, or another software may use it which\n" +"could be identified for example by the help of the 'fuser' command.\n"; static const char *fakeraid_msg = - "Either the device is missing or it's powered down, or you have\n" - "SoftRAID hardware and must use an activated, different device under\n" - "/dev/mapper/, (e.g. /dev/mapper/nvidia_eahaabcc1) to mount NTFS.\n" - "Please see the 'dmraid' documentation for help.\n"; +"Either the device is missing or it's powered down, or you have\n" +"SoftRAID hardware and must use an activated, different device under\n" +"/dev/mapper/, (e.g. /dev/mapper/nvidia_eahaabcc1) to mount NTFS.\n" +"Please see the 'dmraid' documentation for help.\n"; static const char *access_denied_msg = - "Please check '%s' and the ntfs-3g binary permissions,\n" - "and the mounting user ID. More explanation is provided at\n" - "http://ntfs-3g.org/support.html#unprivileged\n"; +"Please check '%s' and the ntfs-3g binary permissions,\n" +"and the mounting user ID. More explanation is provided at\n" +"http://ntfs-3g.org/support.html#unprivileged\n"; /** * ntfs_volume_alloc - Create an NTFS volume object and initialise it @@ -120,31 +120,35 @@ static const char *access_denied_msg = * * Returns: */ -ntfs_volume *ntfs_volume_alloc(void) { - return ntfs_calloc(sizeof(ntfs_volume)); +ntfs_volume *ntfs_volume_alloc(void) +{ + return ntfs_calloc(sizeof(ntfs_volume)); } -static void ntfs_attr_free(ntfs_attr **na) { - if (na && *na) { - ntfs_attr_close(*na); - *na = NULL; - } +static void ntfs_attr_free(ntfs_attr **na) +{ + if (na && *na) { + ntfs_attr_close(*na); + *na = NULL; + } } -static int ntfs_inode_free(ntfs_inode **ni) { - int ret = -1; +static int ntfs_inode_free(ntfs_inode **ni) +{ + int ret = -1; - if (ni && *ni) { - ret = ntfs_inode_close(*ni); - *ni = NULL; - } - - return ret; + if (ni && *ni) { + ret = ntfs_inode_close(*ni); + *ni = NULL; + } + + return ret; } -static void ntfs_error_set(int *err) { - if (!*err) - *err = errno; +static void ntfs_error_set(int *err) +{ + if (!*err) + *err = errno; } /** @@ -155,61 +159,63 @@ static void ntfs_error_set(int *err) { * * Returns: */ -static int __ntfs_volume_release(ntfs_volume *v) { - int err = 0; +static int __ntfs_volume_release(ntfs_volume *v) +{ + int err = 0; - if (ntfs_inode_free(&v->vol_ni)) - ntfs_error_set(&err); - /* - * FIXME: Inodes must be synced before closing - * attributes, otherwise unmount could fail. - */ - if (v->lcnbmp_ni && NInoDirty(v->lcnbmp_ni)) - ntfs_inode_sync(v->lcnbmp_ni); - ntfs_attr_free(&v->lcnbmp_na); - if (ntfs_inode_free(&v->lcnbmp_ni)) - ntfs_error_set(&err); + if (ntfs_inode_free(&v->vol_ni)) + ntfs_error_set(&err); + /* + * FIXME: Inodes must be synced before closing + * attributes, otherwise unmount could fail. + */ + if (v->lcnbmp_ni && NInoDirty(v->lcnbmp_ni)) + ntfs_inode_sync(v->lcnbmp_ni); + ntfs_attr_free(&v->lcnbmp_na); + if (ntfs_inode_free(&v->lcnbmp_ni)) + ntfs_error_set(&err); + + if (v->mft_ni && NInoDirty(v->mft_ni)) + ntfs_inode_sync(v->mft_ni); + ntfs_attr_free(&v->mftbmp_na); + ntfs_attr_free(&v->mft_na); + if (ntfs_inode_free(&v->mft_ni)) + ntfs_error_set(&err); + + if (v->mftmirr_ni && NInoDirty(v->mftmirr_ni)) + ntfs_inode_sync(v->mftmirr_ni); + ntfs_attr_free(&v->mftmirr_na); + if (ntfs_inode_free(&v->mftmirr_ni)) + ntfs_error_set(&err); + + if (v->dev) { + struct ntfs_device *dev = v->dev; - if (v->mft_ni && NInoDirty(v->mft_ni)) - ntfs_inode_sync(v->mft_ni); - ntfs_attr_free(&v->mftbmp_na); - ntfs_attr_free(&v->mft_na); - if (ntfs_inode_free(&v->mft_ni)) - ntfs_error_set(&err); + if (dev->d_ops->sync(dev)) + ntfs_error_set(&err); + if (dev->d_ops->close(dev)) + ntfs_error_set(&err); + } - if (v->mftmirr_ni && NInoDirty(v->mftmirr_ni)) - ntfs_inode_sync(v->mftmirr_ni); - ntfs_attr_free(&v->mftmirr_na); - if (ntfs_inode_free(&v->mftmirr_ni)) - ntfs_error_set(&err); + ntfs_free_lru_caches(v); + free(v->vol_name); + free(v->upcase); + free(v->attrdef); + free(v); - if (v->dev) { - struct ntfs_device *dev = v->dev; - - if (dev->d_ops->sync(dev)) - ntfs_error_set(&err); - if (dev->d_ops->close(dev)) - ntfs_error_set(&err); - } - - ntfs_free_lru_caches(v); - free(v->vol_name); - free(v->upcase); - free(v->attrdef); - free(v); - - errno = err; - return errno ? -1 : 0; + errno = err; + return errno ? -1 : 0; } -static void ntfs_attr_setup_flag(ntfs_inode *ni) { - STANDARD_INFORMATION *si; +static void ntfs_attr_setup_flag(ntfs_inode *ni) +{ + STANDARD_INFORMATION *si; - si = ntfs_attr_readall(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0, NULL); - if (si) { - ni->flags = si->file_attributes; - free(si); - } + si = ntfs_attr_readall(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0, NULL); + if (si) { + ni->flags = si->file_attributes; + free(si); + } } /** @@ -222,172 +228,173 @@ static void ntfs_attr_setup_flag(ntfs_inode *ni) { * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_load(ntfs_volume *vol) { - VCN next_vcn, last_vcn, highest_vcn; - s64 l; - MFT_RECORD *mb = NULL; - ntfs_attr_search_ctx *ctx = NULL; - ATTR_RECORD *a; - int eo; +static int ntfs_mft_load(ntfs_volume *vol) +{ + VCN next_vcn, last_vcn, highest_vcn; + s64 l; + MFT_RECORD *mb = NULL; + ntfs_attr_search_ctx *ctx = NULL; + ATTR_RECORD *a; + int eo; - /* Manually setup an ntfs_inode. */ - vol->mft_ni = ntfs_inode_allocate(vol); - mb = ntfs_malloc(vol->mft_record_size); - if (!vol->mft_ni || !mb) { - ntfs_log_perror("Error allocating memory for $MFT"); - goto error_exit; - } - vol->mft_ni->mft_no = 0; - vol->mft_ni->mrec = mb; - /* Can't use any of the higher level functions yet! */ - l = ntfs_mst_pread(vol->dev, vol->mft_lcn << vol->cluster_size_bits, 1, - vol->mft_record_size, mb); - if (l != 1) { - if (l != -1) - errno = EIO; - ntfs_log_perror("Error reading $MFT"); - goto error_exit; - } + /* Manually setup an ntfs_inode. */ + vol->mft_ni = ntfs_inode_allocate(vol); + mb = ntfs_malloc(vol->mft_record_size); + if (!vol->mft_ni || !mb) { + ntfs_log_perror("Error allocating memory for $MFT"); + goto error_exit; + } + vol->mft_ni->mft_no = 0; + vol->mft_ni->mrec = mb; + /* Can't use any of the higher level functions yet! */ + l = ntfs_mst_pread(vol->dev, vol->mft_lcn << vol->cluster_size_bits, 1, + vol->mft_record_size, mb); + if (l != 1) { + if (l != -1) + errno = EIO; + ntfs_log_perror("Error reading $MFT"); + goto error_exit; + } + + if (ntfs_mft_record_check(vol, 0, mb)) + goto error_exit; + + ctx = ntfs_attr_get_search_ctx(vol->mft_ni, NULL); + if (!ctx) + goto error_exit; - if (ntfs_mft_record_check(vol, 0, mb)) - goto error_exit; - - ctx = ntfs_attr_get_search_ctx(vol->mft_ni, NULL); - if (!ctx) - goto error_exit; - - /* Find the $ATTRIBUTE_LIST attribute in $MFT if present. */ - if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, 0, 0, NULL, 0, - ctx)) { - if (errno != ENOENT) { - ntfs_log_error("$MFT has corrupt attribute list.\n"); - goto io_error_exit; - } - goto mft_has_no_attr_list; - } - NInoSetAttrList(vol->mft_ni); - l = ntfs_get_attribute_value_length(ctx->attr); - if (l <= 0 || l > 0x40000) { - ntfs_log_error("$MFT/$ATTR_LIST invalid length (%lld).\n", - (long long)l); - goto io_error_exit; - } - vol->mft_ni->attr_list_size = l; - vol->mft_ni->attr_list = ntfs_malloc(l); - if (!vol->mft_ni->attr_list) - goto error_exit; - - l = ntfs_get_attribute_value(vol, ctx->attr, vol->mft_ni->attr_list); - if (!l) { - ntfs_log_error("Failed to get value of $MFT/$ATTR_LIST.\n"); - goto io_error_exit; - } - if (l != vol->mft_ni->attr_list_size) { - ntfs_log_error("Partial read of $MFT/$ATTR_LIST (%lld != " - "%u).\n", (long long)l, - vol->mft_ni->attr_list_size); - goto io_error_exit; - } + /* Find the $ATTRIBUTE_LIST attribute in $MFT if present. */ + if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, 0, 0, NULL, 0, + ctx)) { + if (errno != ENOENT) { + ntfs_log_error("$MFT has corrupt attribute list.\n"); + goto io_error_exit; + } + goto mft_has_no_attr_list; + } + NInoSetAttrList(vol->mft_ni); + l = ntfs_get_attribute_value_length(ctx->attr); + if (l <= 0 || l > 0x40000) { + ntfs_log_error("$MFT/$ATTR_LIST invalid length (%lld).\n", + (long long)l); + goto io_error_exit; + } + vol->mft_ni->attr_list_size = l; + vol->mft_ni->attr_list = ntfs_malloc(l); + if (!vol->mft_ni->attr_list) + goto error_exit; + + l = ntfs_get_attribute_value(vol, ctx->attr, vol->mft_ni->attr_list); + if (!l) { + ntfs_log_error("Failed to get value of $MFT/$ATTR_LIST.\n"); + goto io_error_exit; + } + if (l != vol->mft_ni->attr_list_size) { + ntfs_log_error("Partial read of $MFT/$ATTR_LIST (%lld != " + "%u).\n", (long long)l, + vol->mft_ni->attr_list_size); + goto io_error_exit; + } mft_has_no_attr_list: - ntfs_attr_setup_flag(vol->mft_ni); + ntfs_attr_setup_flag(vol->mft_ni); + + /* We now have a fully setup ntfs inode for $MFT in vol->mft_ni. */ + + /* Get an ntfs attribute for $MFT/$DATA and set it up, too. */ + vol->mft_na = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0); + if (!vol->mft_na) { + ntfs_log_perror("Failed to open ntfs attribute"); + goto error_exit; + } + /* Read all extents from the $DATA attribute in $MFT. */ + ntfs_attr_reinit_search_ctx(ctx); + last_vcn = vol->mft_na->allocated_size >> vol->cluster_size_bits; + highest_vcn = next_vcn = 0; + a = NULL; + while (!ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, next_vcn, NULL, 0, + ctx)) { + runlist_element *nrl; - /* We now have a fully setup ntfs inode for $MFT in vol->mft_ni. */ + a = ctx->attr; + /* $MFT must be non-resident. */ + if (!a->non_resident) { + ntfs_log_error("$MFT must be non-resident.\n"); + goto io_error_exit; + } + /* $MFT must be uncompressed and unencrypted. */ + if (a->flags & ATTR_COMPRESSION_MASK || + a->flags & ATTR_IS_ENCRYPTED) { + ntfs_log_error("$MFT must be uncompressed and " + "unencrypted.\n"); + goto io_error_exit; + } + /* + * Decompress the mapping pairs array of this extent and merge + * the result into the existing runlist. No need for locking + * as we have exclusive access to the inode at this time and we + * are a mount in progress task, too. + */ + nrl = ntfs_mapping_pairs_decompress(vol, a, vol->mft_na->rl); + if (!nrl) { + ntfs_log_perror("ntfs_mapping_pairs_decompress() failed"); + goto error_exit; + } + vol->mft_na->rl = nrl; - /* Get an ntfs attribute for $MFT/$DATA and set it up, too. */ - vol->mft_na = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0); - if (!vol->mft_na) { - ntfs_log_perror("Failed to open ntfs attribute"); - goto error_exit; - } - /* Read all extents from the $DATA attribute in $MFT. */ - ntfs_attr_reinit_search_ctx(ctx); - last_vcn = vol->mft_na->allocated_size >> vol->cluster_size_bits; - highest_vcn = next_vcn = 0; - a = NULL; - while (!ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, next_vcn, NULL, 0, - ctx)) { - runlist_element *nrl; + /* Get the lowest vcn for the next extent. */ + highest_vcn = sle64_to_cpu(a->highest_vcn); + next_vcn = highest_vcn + 1; - a = ctx->attr; - /* $MFT must be non-resident. */ - if (!a->non_resident) { - ntfs_log_error("$MFT must be non-resident.\n"); - goto io_error_exit; - } - /* $MFT must be uncompressed and unencrypted. */ - if (a->flags & ATTR_COMPRESSION_MASK || - a->flags & ATTR_IS_ENCRYPTED) { - ntfs_log_error("$MFT must be uncompressed and " - "unencrypted.\n"); - goto io_error_exit; - } - /* - * Decompress the mapping pairs array of this extent and merge - * the result into the existing runlist. No need for locking - * as we have exclusive access to the inode at this time and we - * are a mount in progress task, too. - */ - nrl = ntfs_mapping_pairs_decompress(vol, a, vol->mft_na->rl); - if (!nrl) { - ntfs_log_perror("ntfs_mapping_pairs_decompress() failed"); - goto error_exit; - } - vol->mft_na->rl = nrl; + /* Only one extent or error, which we catch below. */ + if (next_vcn <= 0) + break; - /* Get the lowest vcn for the next extent. */ - highest_vcn = sle64_to_cpu(a->highest_vcn); - next_vcn = highest_vcn + 1; - - /* Only one extent or error, which we catch below. */ - if (next_vcn <= 0) - break; - - /* Avoid endless loops due to corruption. */ - if (next_vcn < sle64_to_cpu(a->lowest_vcn)) { - ntfs_log_error("$MFT has corrupt attribute list.\n"); - goto io_error_exit; - } - } - if (!a) { - ntfs_log_error("$MFT/$DATA attribute not found.\n"); - goto io_error_exit; - } - if (highest_vcn && highest_vcn != last_vcn - 1) { - ntfs_log_error("Failed to load runlist for $MFT/$DATA.\n"); - ntfs_log_error("highest_vcn = 0x%llx, last_vcn - 1 = 0x%llx\n", - (long long)highest_vcn, (long long)last_vcn - 1); - goto io_error_exit; - } - /* Done with the $Mft mft record. */ - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - /* - * The volume is now setup so we can use all read access functions. - */ - vol->mftbmp_na = ntfs_attr_open(vol->mft_ni, AT_BITMAP, AT_UNNAMED, 0); - if (!vol->mftbmp_na) { - ntfs_log_perror("Failed to open $MFT/$BITMAP"); - goto error_exit; - } - return 0; + /* Avoid endless loops due to corruption. */ + if (next_vcn < sle64_to_cpu(a->lowest_vcn)) { + ntfs_log_error("$MFT has corrupt attribute list.\n"); + goto io_error_exit; + } + } + if (!a) { + ntfs_log_error("$MFT/$DATA attribute not found.\n"); + goto io_error_exit; + } + if (highest_vcn && highest_vcn != last_vcn - 1) { + ntfs_log_error("Failed to load runlist for $MFT/$DATA.\n"); + ntfs_log_error("highest_vcn = 0x%llx, last_vcn - 1 = 0x%llx\n", + (long long)highest_vcn, (long long)last_vcn - 1); + goto io_error_exit; + } + /* Done with the $Mft mft record. */ + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; + /* + * The volume is now setup so we can use all read access functions. + */ + vol->mftbmp_na = ntfs_attr_open(vol->mft_ni, AT_BITMAP, AT_UNNAMED, 0); + if (!vol->mftbmp_na) { + ntfs_log_perror("Failed to open $MFT/$BITMAP"); + goto error_exit; + } + return 0; io_error_exit: - errno = EIO; + errno = EIO; error_exit: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - if (vol->mft_na) { - ntfs_attr_close(vol->mft_na); - vol->mft_na = NULL; - } - if (vol->mft_ni) { - ntfs_inode_close(vol->mft_ni); - vol->mft_ni = NULL; - } - errno = eo; - return -1; + eo = errno; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + if (vol->mft_na) { + ntfs_attr_close(vol->mft_na); + vol->mft_na = NULL; + } + if (vol->mft_ni) { + ntfs_inode_close(vol->mft_ni); + vol->mft_ni = NULL; + } + errno = eo; + return -1; } /** @@ -401,38 +408,39 @@ error_exit: * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mftmirr_load(ntfs_volume *vol) { - int err; +static int ntfs_mftmirr_load(ntfs_volume *vol) +{ + int err; - vol->mftmirr_ni = ntfs_inode_open(vol, FILE_MFTMirr); - if (!vol->mftmirr_ni) { - ntfs_log_perror("Failed to open inode $MFTMirr"); - return -1; - } - - vol->mftmirr_na = ntfs_attr_open(vol->mftmirr_ni, AT_DATA, AT_UNNAMED, 0); - if (!vol->mftmirr_na) { - ntfs_log_perror("Failed to open $MFTMirr/$DATA"); - goto error_exit; - } - - if (ntfs_attr_map_runlist(vol->mftmirr_na, 0) < 0) { - ntfs_log_perror("Failed to map runlist of $MFTMirr/$DATA"); - goto error_exit; - } - - return 0; + vol->mftmirr_ni = ntfs_inode_open(vol, FILE_MFTMirr); + if (!vol->mftmirr_ni) { + ntfs_log_perror("Failed to open inode $MFTMirr"); + return -1; + } + + vol->mftmirr_na = ntfs_attr_open(vol->mftmirr_ni, AT_DATA, AT_UNNAMED, 0); + if (!vol->mftmirr_na) { + ntfs_log_perror("Failed to open $MFTMirr/$DATA"); + goto error_exit; + } + + if (ntfs_attr_map_runlist(vol->mftmirr_na, 0) < 0) { + ntfs_log_perror("Failed to map runlist of $MFTMirr/$DATA"); + goto error_exit; + } + + return 0; error_exit: - err = errno; - if (vol->mftmirr_na) { - ntfs_attr_close(vol->mftmirr_na); - vol->mftmirr_na = NULL; - } - ntfs_inode_close(vol->mftmirr_ni); - vol->mftmirr_ni = NULL; - errno = err; - return -1; + err = errno; + if (vol->mftmirr_na) { + ntfs_attr_close(vol->mftmirr_na); + vol->mftmirr_na = NULL; + } + ntfs_inode_close(vol->mftmirr_ni); + vol->mftmirr_ni = NULL; + errno = err; + return -1; } /** @@ -447,147 +455,148 @@ error_exit: * Return the allocated volume structure on success and NULL on error with * errno set to the error code. */ -ntfs_volume *ntfs_volume_startup(struct ntfs_device *dev, unsigned long flags) { - LCN mft_zone_size, mft_lcn; - s64 br; - ntfs_volume *vol; - NTFS_BOOT_SECTOR *bs; - int eo; +ntfs_volume *ntfs_volume_startup(struct ntfs_device *dev, unsigned long flags) +{ + LCN mft_zone_size, mft_lcn; + s64 br; + ntfs_volume *vol; + NTFS_BOOT_SECTOR *bs; + int eo; - if (!dev || !dev->d_ops || !dev->d_name) { - errno = EINVAL; - ntfs_log_perror("%s: dev = %p", __FUNCTION__, dev); - return NULL; - } + if (!dev || !dev->d_ops || !dev->d_name) { + errno = EINVAL; + ntfs_log_perror("%s: dev = %p", __FUNCTION__, dev); + return NULL; + } - bs = ntfs_malloc(sizeof(NTFS_BOOT_SECTOR)); - if (!bs) - return NULL; + bs = ntfs_malloc(sizeof(NTFS_BOOT_SECTOR)); + if (!bs) + return NULL; + + /* Allocate the volume structure. */ + vol = ntfs_volume_alloc(); + if (!vol) + goto error_exit; + + /* Create the default upcase table. */ + vol->upcase_len = 65536; + vol->upcase = ntfs_malloc(vol->upcase_len * sizeof(ntfschar)); + if (!vol->upcase) + goto error_exit; + + ntfs_upcase_table_build(vol->upcase, + vol->upcase_len * sizeof(ntfschar)); + + if (flags & MS_RDONLY) + NVolSetReadOnly(vol); + + /* ...->open needs bracketing to compile with glibc 2.7 */ + if ((dev->d_ops->open)(dev, NVolReadOnly(vol) ? O_RDONLY: O_RDWR)) { + ntfs_log_perror("Error opening '%s'", dev->d_name); + goto error_exit; + } + /* Attach the device to the volume. */ + vol->dev = dev; + + /* Now read the bootsector. */ + br = ntfs_pread(dev, 0, sizeof(NTFS_BOOT_SECTOR), bs); + if (br != sizeof(NTFS_BOOT_SECTOR)) { + if (br != -1) + errno = EINVAL; + if (!br) + ntfs_log_error("Failed to read bootsector (size=0)\n"); + else + ntfs_log_perror("Error reading bootsector"); + goto error_exit; + } + if (!ntfs_boot_sector_is_ntfs(bs)) { + errno = EINVAL; + goto error_exit; + } + if (ntfs_boot_sector_parse(vol, bs) < 0) + goto error_exit; + + free(bs); + bs = NULL; + /* Now set the device block size to the sector size. */ + if (ntfs_device_block_size_set(vol->dev, vol->sector_size)) + ntfs_log_debug("Failed to set the device block size to the " + "sector size. This may affect performance " + "but should be harmless otherwise. Error: " + "%s\n", strerror(errno)); + + /* We now initialize the cluster allocator. */ + vol->full_zones = 0; + mft_zone_size = vol->nr_clusters >> 3; /* 12.5% */ - /* Allocate the volume structure. */ - vol = ntfs_volume_alloc(); - if (!vol) - goto error_exit; + /* Setup the mft zone. */ + vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn; + ntfs_log_debug("mft_zone_pos = 0x%llx\n", (long long)vol->mft_zone_pos); - /* Create the default upcase table. */ - vol->upcase_len = 65536; - vol->upcase = ntfs_malloc(vol->upcase_len * sizeof(ntfschar)); - if (!vol->upcase) - goto error_exit; + /* + * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs + * source) and if the actual mft_lcn is in the expected place or even + * further to the front of the volume, extend the mft_zone to cover the + * beginning of the volume as well. This is in order to protect the + * area reserved for the mft bitmap as well within the mft_zone itself. + * On non-standard volumes we don't protect it as the overhead would be + * higher than the speed increase we would get by doing it. + */ + mft_lcn = (8192 + 2 * vol->cluster_size - 1) / vol->cluster_size; + if (mft_lcn * vol->cluster_size < 16 * 1024) + mft_lcn = (16 * 1024 + vol->cluster_size - 1) / + vol->cluster_size; + if (vol->mft_zone_start <= mft_lcn) + vol->mft_zone_start = 0; + ntfs_log_debug("mft_zone_start = 0x%llx\n", (long long)vol->mft_zone_start); - ntfs_upcase_table_build(vol->upcase, - vol->upcase_len * sizeof(ntfschar)); + /* + * Need to cap the mft zone on non-standard volumes so that it does + * not point outside the boundaries of the volume. We do this by + * halving the zone size until we are inside the volume. + */ + vol->mft_zone_end = vol->mft_lcn + mft_zone_size; + while (vol->mft_zone_end >= vol->nr_clusters) { + mft_zone_size >>= 1; + vol->mft_zone_end = vol->mft_lcn + mft_zone_size; + } + ntfs_log_debug("mft_zone_end = 0x%llx\n", (long long)vol->mft_zone_end); - if (flags & MS_RDONLY) - NVolSetReadOnly(vol); + /* + * Set the current position within each data zone to the start of the + * respective zone. + */ + vol->data1_zone_pos = vol->mft_zone_end; + ntfs_log_debug("data1_zone_pos = %lld\n", (long long)vol->data1_zone_pos); + vol->data2_zone_pos = 0; + ntfs_log_debug("data2_zone_pos = %lld\n", (long long)vol->data2_zone_pos); - /* ...->open needs bracketing to compile with glibc 2.7 */ - if ((dev->d_ops->open)(dev, NVolReadOnly(vol) ? O_RDONLY: O_RDWR)) { - ntfs_log_perror("Error opening '%s'", dev->d_name); - goto error_exit; - } - /* Attach the device to the volume. */ - vol->dev = dev; + /* Set the mft data allocation position to mft record 24. */ + vol->mft_data_pos = 24; - /* Now read the bootsector. */ - br = ntfs_pread(dev, 0, sizeof(NTFS_BOOT_SECTOR), bs); - if (br != sizeof(NTFS_BOOT_SECTOR)) { - if (br != -1) - errno = EINVAL; - if (!br) - ntfs_log_error("Failed to read bootsector (size=0)\n"); - else - ntfs_log_perror("Error reading bootsector"); - goto error_exit; - } - if (!ntfs_boot_sector_is_ntfs(bs)) { - errno = EINVAL; - goto error_exit; - } - if (ntfs_boot_sector_parse(vol, bs) < 0) - goto error_exit; + /* + * The cluster allocator is now fully operational. + */ - free(bs); - bs = NULL; - /* Now set the device block size to the sector size. */ - if (ntfs_device_block_size_set(vol->dev, vol->sector_size)) - ntfs_log_debug("Failed to set the device block size to the " - "sector size. This may affect performance " - "but should be harmless otherwise. Error: " - "%s\n", strerror(errno)); + /* Need to setup $MFT so we can use the library read functions. */ + if (ntfs_mft_load(vol) < 0) { + ntfs_log_perror("Failed to load $MFT"); + goto error_exit; + } - /* We now initialize the cluster allocator. */ - vol->full_zones = 0; - mft_zone_size = vol->nr_clusters >> 3; /* 12.5% */ - - /* Setup the mft zone. */ - vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn; - ntfs_log_debug("mft_zone_pos = 0x%llx\n", (long long)vol->mft_zone_pos); - - /* - * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs - * source) and if the actual mft_lcn is in the expected place or even - * further to the front of the volume, extend the mft_zone to cover the - * beginning of the volume as well. This is in order to protect the - * area reserved for the mft bitmap as well within the mft_zone itself. - * On non-standard volumes we don't protect it as the overhead would be - * higher than the speed increase we would get by doing it. - */ - mft_lcn = (8192 + 2 * vol->cluster_size - 1) / vol->cluster_size; - if (mft_lcn * vol->cluster_size < 16 * 1024) - mft_lcn = (16 * 1024 + vol->cluster_size - 1) / - vol->cluster_size; - if (vol->mft_zone_start <= mft_lcn) - vol->mft_zone_start = 0; - ntfs_log_debug("mft_zone_start = 0x%llx\n", (long long)vol->mft_zone_start); - - /* - * Need to cap the mft zone on non-standard volumes so that it does - * not point outside the boundaries of the volume. We do this by - * halving the zone size until we are inside the volume. - */ - vol->mft_zone_end = vol->mft_lcn + mft_zone_size; - while (vol->mft_zone_end >= vol->nr_clusters) { - mft_zone_size >>= 1; - vol->mft_zone_end = vol->mft_lcn + mft_zone_size; - } - ntfs_log_debug("mft_zone_end = 0x%llx\n", (long long)vol->mft_zone_end); - - /* - * Set the current position within each data zone to the start of the - * respective zone. - */ - vol->data1_zone_pos = vol->mft_zone_end; - ntfs_log_debug("data1_zone_pos = %lld\n", (long long)vol->data1_zone_pos); - vol->data2_zone_pos = 0; - ntfs_log_debug("data2_zone_pos = %lld\n", (long long)vol->data2_zone_pos); - - /* Set the mft data allocation position to mft record 24. */ - vol->mft_data_pos = 24; - - /* - * The cluster allocator is now fully operational. - */ - - /* Need to setup $MFT so we can use the library read functions. */ - if (ntfs_mft_load(vol) < 0) { - ntfs_log_perror("Failed to load $MFT"); - goto error_exit; - } - - /* Need to setup $MFTMirr so we can use the write functions, too. */ - if (ntfs_mftmirr_load(vol) < 0) { - ntfs_log_perror("Failed to load $MFTMirr"); - goto error_exit; - } - return vol; + /* Need to setup $MFTMirr so we can use the write functions, too. */ + if (ntfs_mftmirr_load(vol) < 0) { + ntfs_log_perror("Failed to load $MFTMirr"); + goto error_exit; + } + return vol; error_exit: - eo = errno; - free(bs); - if (vol) - __ntfs_volume_release(vol); - errno = eo; - return NULL; + eo = errno; + free(bs); + if (vol) + __ntfs_volume_release(vol); + errno = eo; + return NULL; } /** @@ -596,38 +605,39 @@ error_exit: * * Return 0 on success and -1 on error with errno set error code. */ -static int ntfs_volume_check_logfile(ntfs_volume *vol) { - ntfs_inode *ni; - ntfs_attr *na = NULL; - RESTART_PAGE_HEADER *rp = NULL; - int err = 0; +static int ntfs_volume_check_logfile(ntfs_volume *vol) +{ + ntfs_inode *ni; + ntfs_attr *na = NULL; + RESTART_PAGE_HEADER *rp = NULL; + int err = 0; - ni = ntfs_inode_open(vol, FILE_LogFile); - if (!ni) { - ntfs_log_perror("Failed to open inode FILE_LogFile"); - errno = EIO; - return -1; - } - - na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); - if (!na) { - ntfs_log_perror("Failed to open $FILE_LogFile/$DATA"); - err = EIO; - goto out; - } - - if (!ntfs_check_logfile(na, &rp) || !ntfs_is_logfile_clean(na, rp)) - err = EOPNOTSUPP; - free(rp); - ntfs_attr_close(na); -out: - if (ntfs_inode_close(ni)) - ntfs_error_set(&err); - if (err) { - errno = err; - return -1; - } - return 0; + ni = ntfs_inode_open(vol, FILE_LogFile); + if (!ni) { + ntfs_log_perror("Failed to open inode FILE_LogFile"); + errno = EIO; + return -1; + } + + na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); + if (!na) { + ntfs_log_perror("Failed to open $FILE_LogFile/$DATA"); + err = EIO; + goto out; + } + + if (!ntfs_check_logfile(na, &rp) || !ntfs_is_logfile_clean(na, rp)) + err = EOPNOTSUPP; + free(rp); + ntfs_attr_close(na); +out: + if (ntfs_inode_close(ni)) + ntfs_error_set(&err); + if (err) { + errno = err; + return -1; + } + return 0; } /** @@ -637,50 +647,51 @@ out: * Return: inode Success, hiberfil.sys is valid * NULL hiberfil.sys doesn't exist or some other error occurred */ -static ntfs_inode *ntfs_hiberfile_open(ntfs_volume *vol) { - u64 inode; - ntfs_inode *ni_root; - ntfs_inode *ni_hibr = NULL; - ntfschar *unicode = NULL; - int unicode_len; - const char *hiberfile = "hiberfil.sys"; +static ntfs_inode *ntfs_hiberfile_open(ntfs_volume *vol) +{ + u64 inode; + ntfs_inode *ni_root; + ntfs_inode *ni_hibr = NULL; + ntfschar *unicode = NULL; + int unicode_len; + const char *hiberfile = "hiberfil.sys"; - if (!vol) { - errno = EINVAL; - return NULL; - } + if (!vol) { + errno = EINVAL; + return NULL; + } - ni_root = ntfs_inode_open(vol, FILE_root); - if (!ni_root) { - ntfs_log_debug("Couldn't open the root directory.\n"); - return NULL; - } + ni_root = ntfs_inode_open(vol, FILE_root); + if (!ni_root) { + ntfs_log_debug("Couldn't open the root directory.\n"); + return NULL; + } - unicode_len = ntfs_mbstoucs(hiberfile, &unicode); - if (unicode_len < 0) { - ntfs_log_perror("Couldn't convert 'hiberfil.sys' to Unicode"); - goto out; - } + unicode_len = ntfs_mbstoucs(hiberfile, &unicode); + if (unicode_len < 0) { + ntfs_log_perror("Couldn't convert 'hiberfil.sys' to Unicode"); + goto out; + } - inode = ntfs_inode_lookup_by_name(ni_root, unicode, unicode_len); - if (inode == (u64)-1) { - ntfs_log_debug("Couldn't find file '%s'.\n", hiberfile); - goto out; - } + inode = ntfs_inode_lookup_by_name(ni_root, unicode, unicode_len); + if (inode == (u64)-1) { + ntfs_log_debug("Couldn't find file '%s'.\n", hiberfile); + goto out; + } - inode = MREF(inode); - ni_hibr = ntfs_inode_open(vol, inode); - if (!ni_hibr) { - ntfs_log_debug("Couldn't open inode %lld.\n", (long long)inode); - goto out; - } + inode = MREF(inode); + ni_hibr = ntfs_inode_open(vol, inode); + if (!ni_hibr) { + ntfs_log_debug("Couldn't open inode %lld.\n", (long long)inode); + goto out; + } out: - if (ntfs_inode_close(ni_root)) { - ntfs_inode_close(ni_hibr); - ni_hibr = NULL; - } - free(unicode); - return ni_hibr; + if (ntfs_inode_close(ni_root)) { + ntfs_inode_close(ni_hibr); + ni_hibr = NULL; + } + free(unicode); + return ni_hibr; } @@ -694,58 +705,59 @@ out: * Return: 0 if Windows isn't hibernated for sure * -1 otherwise and errno is set to the appropriate value */ -int ntfs_volume_check_hiberfile(ntfs_volume *vol, int verbose) { - ntfs_inode *ni; - ntfs_attr *na = NULL; - int bytes_read, err; - char *buf = NULL; +int ntfs_volume_check_hiberfile(ntfs_volume *vol, int verbose) +{ + ntfs_inode *ni; + ntfs_attr *na = NULL; + int bytes_read, err; + char *buf = NULL; - ni = ntfs_hiberfile_open(vol); - if (!ni) { - if (errno == ENOENT) - return 0; - return -1; - } + ni = ntfs_hiberfile_open(vol); + if (!ni) { + if (errno == ENOENT) + return 0; + return -1; + } - buf = ntfs_malloc(NTFS_HIBERFILE_HEADER_SIZE); - if (!buf) - goto out; + buf = ntfs_malloc(NTFS_HIBERFILE_HEADER_SIZE); + if (!buf) + goto out; - na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); - if (!na) { - ntfs_log_perror("Failed to open hiberfil.sys data attribute"); - goto out; - } + na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); + if (!na) { + ntfs_log_perror("Failed to open hiberfil.sys data attribute"); + goto out; + } - bytes_read = ntfs_attr_pread(na, 0, NTFS_HIBERFILE_HEADER_SIZE, buf); - if (bytes_read == -1) { - ntfs_log_perror("Failed to read hiberfil.sys"); - goto out; - } - if (bytes_read < NTFS_HIBERFILE_HEADER_SIZE) { - if (verbose) - ntfs_log_error("Hibernated non-system partition, " - "refused to mount.\n"); - errno = EPERM; - goto out; - } - if (memcmp(buf, "hibr", 4) == 0) { - if (verbose) - ntfs_log_error("Windows is hibernated, refused to mount.\n"); - errno = EPERM; - goto out; - } - /* All right, all header bytes are zero */ - errno = 0; + bytes_read = ntfs_attr_pread(na, 0, NTFS_HIBERFILE_HEADER_SIZE, buf); + if (bytes_read == -1) { + ntfs_log_perror("Failed to read hiberfil.sys"); + goto out; + } + if (bytes_read < NTFS_HIBERFILE_HEADER_SIZE) { + if (verbose) + ntfs_log_error("Hibernated non-system partition, " + "refused to mount.\n"); + errno = EPERM; + goto out; + } + if (memcmp(buf, "hibr", 4) == 0) { + if (verbose) + ntfs_log_error("Windows is hibernated, refused to mount.\n"); + errno = EPERM; + goto out; + } + /* All right, all header bytes are zero */ + errno = 0; out: - if (na) - ntfs_attr_close(na); - free(buf); - err = errno; - if (ntfs_inode_close(ni)) - ntfs_error_set(&err); - errno = err; - return errno ? -1 : 0; + if (na) + ntfs_attr_close(na); + free(buf); + err = errno; + if (ntfs_inode_close(ni)) + ntfs_error_set(&err); + errno = err; + return errno ? -1 : 0; } /** @@ -770,348 +782,348 @@ out: * Return the allocated volume structure on success and NULL on error with * errno set to the error code. */ -ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, unsigned long flags) { - s64 l; - ntfs_volume *vol; - u8 *m = NULL, *m2 = NULL; - ntfs_attr_search_ctx *ctx = NULL; - ntfs_inode *ni; - ntfs_attr *na; - ATTR_RECORD *a; - VOLUME_INFORMATION *vinf; - ntfschar *vname; - int i, j, eo; - u32 u; +ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, unsigned long flags) +{ + s64 l; + ntfs_volume *vol; + u8 *m = NULL, *m2 = NULL; + ntfs_attr_search_ctx *ctx = NULL; + ntfs_inode *ni; + ntfs_attr *na; + ATTR_RECORD *a; + VOLUME_INFORMATION *vinf; + ntfschar *vname; + int i, j, eo; + u32 u; - vol = ntfs_volume_startup(dev, flags); - if (!vol) - return NULL; + vol = ntfs_volume_startup(dev, flags); + if (!vol) + return NULL; - /* Load data from $MFT and $MFTMirr and compare the contents. */ - m = ntfs_malloc(vol->mftmirr_size << vol->mft_record_size_bits); - m2 = ntfs_malloc(vol->mftmirr_size << vol->mft_record_size_bits); - if (!m || !m2) - goto error_exit; + /* Load data from $MFT and $MFTMirr and compare the contents. */ + m = ntfs_malloc(vol->mftmirr_size << vol->mft_record_size_bits); + m2 = ntfs_malloc(vol->mftmirr_size << vol->mft_record_size_bits); + if (!m || !m2) + goto error_exit; - l = ntfs_attr_mst_pread(vol->mft_na, 0, vol->mftmirr_size, - vol->mft_record_size, m); - if (l != vol->mftmirr_size) { - if (l == -1) - ntfs_log_perror("Failed to read $MFT"); - else { - ntfs_log_error("Failed to read $MFT, unexpected length " - "(%lld != %d).\n", (long long)l, - vol->mftmirr_size); - errno = EIO; - } - goto error_exit; - } - l = ntfs_attr_mst_pread(vol->mftmirr_na, 0, vol->mftmirr_size, - vol->mft_record_size, m2); - if (l != vol->mftmirr_size) { - if (l == -1) { - ntfs_log_perror("Failed to read $MFTMirr"); - goto error_exit; - } - vol->mftmirr_size = l; - } - ntfs_log_debug("Comparing $MFTMirr to $MFT...\n"); - for (i = 0; i < vol->mftmirr_size; ++i) { - MFT_RECORD *mrec, *mrec2; - const char *ESTR[12] = { "$MFT", "$MFTMirr", "$LogFile", - "$Volume", "$AttrDef", "root directory", "$Bitmap", - "$Boot", "$BadClus", "$Secure", "$UpCase", "$Extend" - }; - const char *s; + l = ntfs_attr_mst_pread(vol->mft_na, 0, vol->mftmirr_size, + vol->mft_record_size, m); + if (l != vol->mftmirr_size) { + if (l == -1) + ntfs_log_perror("Failed to read $MFT"); + else { + ntfs_log_error("Failed to read $MFT, unexpected length " + "(%lld != %d).\n", (long long)l, + vol->mftmirr_size); + errno = EIO; + } + goto error_exit; + } + l = ntfs_attr_mst_pread(vol->mftmirr_na, 0, vol->mftmirr_size, + vol->mft_record_size, m2); + if (l != vol->mftmirr_size) { + if (l == -1) { + ntfs_log_perror("Failed to read $MFTMirr"); + goto error_exit; + } + vol->mftmirr_size = l; + } + ntfs_log_debug("Comparing $MFTMirr to $MFT...\n"); + for (i = 0; i < vol->mftmirr_size; ++i) { + MFT_RECORD *mrec, *mrec2; + const char *ESTR[12] = { "$MFT", "$MFTMirr", "$LogFile", + "$Volume", "$AttrDef", "root directory", "$Bitmap", + "$Boot", "$BadClus", "$Secure", "$UpCase", "$Extend" }; + const char *s; - if (i < 12) - s = ESTR[i]; - else if (i < 16) - s = "system file"; - else - s = "mft record"; + if (i < 12) + s = ESTR[i]; + else if (i < 16) + s = "system file"; + else + s = "mft record"; - mrec = (MFT_RECORD*)(m + i * vol->mft_record_size); - if (mrec->flags & MFT_RECORD_IN_USE) { - if (ntfs_is_baad_recordp(mrec)) { - ntfs_log_error("$MFT error: Incomplete multi " - "sector transfer detected in " - "'%s'.\n", s); - goto io_error_exit; - } - if (!ntfs_is_mft_recordp(mrec)) { - ntfs_log_error("$MFT error: Invalid mft " - "record for '%s'.\n", s); - goto io_error_exit; - } - } - mrec2 = (MFT_RECORD*)(m2 + i * vol->mft_record_size); - if (mrec2->flags & MFT_RECORD_IN_USE) { - if (ntfs_is_baad_recordp(mrec2)) { - ntfs_log_error("$MFTMirr error: Incomplete " - "multi sector transfer " - "detected in '%s'.\n", s); - goto io_error_exit; - } - if (!ntfs_is_mft_recordp(mrec2)) { - ntfs_log_error("$MFTMirr error: Invalid mft " - "record for '%s'.\n", s); - goto io_error_exit; - } - } - if (memcmp(mrec, mrec2, ntfs_mft_record_get_data_size(mrec))) { - ntfs_log_error("$MFTMirr does not match $MFT (record " - "%d).\n", i); - goto io_error_exit; - } - } + mrec = (MFT_RECORD*)(m + i * vol->mft_record_size); + if (mrec->flags & MFT_RECORD_IN_USE) { + if (ntfs_is_baad_recordp(mrec)) { + ntfs_log_error("$MFT error: Incomplete multi " + "sector transfer detected in " + "'%s'.\n", s); + goto io_error_exit; + } + if (!ntfs_is_mft_recordp(mrec)) { + ntfs_log_error("$MFT error: Invalid mft " + "record for '%s'.\n", s); + goto io_error_exit; + } + } + mrec2 = (MFT_RECORD*)(m2 + i * vol->mft_record_size); + if (mrec2->flags & MFT_RECORD_IN_USE) { + if (ntfs_is_baad_recordp(mrec2)) { + ntfs_log_error("$MFTMirr error: Incomplete " + "multi sector transfer " + "detected in '%s'.\n", s); + goto io_error_exit; + } + if (!ntfs_is_mft_recordp(mrec2)) { + ntfs_log_error("$MFTMirr error: Invalid mft " + "record for '%s'.\n", s); + goto io_error_exit; + } + } + if (memcmp(mrec, mrec2, ntfs_mft_record_get_data_size(mrec))) { + ntfs_log_error("$MFTMirr does not match $MFT (record " + "%d).\n", i); + goto io_error_exit; + } + } - free(m2); - free(m); - m = m2 = NULL; + free(m2); + free(m); + m = m2 = NULL; - /* Now load the bitmap from $Bitmap. */ - ntfs_log_debug("Loading $Bitmap...\n"); - vol->lcnbmp_ni = ntfs_inode_open(vol, FILE_Bitmap); - if (!vol->lcnbmp_ni) { - ntfs_log_perror("Failed to open inode FILE_Bitmap"); - goto error_exit; - } + /* Now load the bitmap from $Bitmap. */ + ntfs_log_debug("Loading $Bitmap...\n"); + vol->lcnbmp_ni = ntfs_inode_open(vol, FILE_Bitmap); + if (!vol->lcnbmp_ni) { + ntfs_log_perror("Failed to open inode FILE_Bitmap"); + goto error_exit; + } + + vol->lcnbmp_na = ntfs_attr_open(vol->lcnbmp_ni, AT_DATA, AT_UNNAMED, 0); + if (!vol->lcnbmp_na) { + ntfs_log_perror("Failed to open ntfs attribute"); + goto error_exit; + } + + if (vol->lcnbmp_na->data_size > vol->lcnbmp_na->allocated_size) { + ntfs_log_error("Corrupt cluster map size (%lld > %lld)\n", + (long long)vol->lcnbmp_na->data_size, + (long long)vol->lcnbmp_na->allocated_size); + goto io_error_exit; + } - vol->lcnbmp_na = ntfs_attr_open(vol->lcnbmp_ni, AT_DATA, AT_UNNAMED, 0); - if (!vol->lcnbmp_na) { - ntfs_log_perror("Failed to open ntfs attribute"); - goto error_exit; - } + /* Now load the upcase table from $UpCase. */ + ntfs_log_debug("Loading $UpCase...\n"); + ni = ntfs_inode_open(vol, FILE_UpCase); + if (!ni) { + ntfs_log_perror("Failed to open inode FILE_UpCase"); + goto error_exit; + } + /* Get an ntfs attribute for $UpCase/$DATA. */ + na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); + if (!na) { + ntfs_log_perror("Failed to open ntfs attribute"); + goto error_exit; + } + /* + * Note: Normally, the upcase table has a length equal to 65536 + * 2-byte Unicode characters but allow for different cases, so no + * checks done. Just check we don't overflow 32-bits worth of Unicode + * characters. + */ + if (na->data_size & ~0x1ffffffffULL) { + ntfs_log_error("Error: Upcase table is too big (max 32-bit " + "allowed).\n"); + errno = EINVAL; + goto error_exit; + } + if (vol->upcase_len != na->data_size >> 1) { + vol->upcase_len = na->data_size >> 1; + /* Throw away default table. */ + free(vol->upcase); + vol->upcase = ntfs_malloc(na->data_size); + if (!vol->upcase) + goto error_exit; + } + /* Read in the $DATA attribute value into the buffer. */ + l = ntfs_attr_pread(na, 0, na->data_size, vol->upcase); + if (l != na->data_size) { + ntfs_log_error("Failed to read $UpCase, unexpected length " + "(%lld != %lld).\n", (long long)l, + (long long)na->data_size); + errno = EIO; + goto error_exit; + } + /* Done with the $UpCase mft record. */ + ntfs_attr_close(na); + if (ntfs_inode_close(ni)) { + ntfs_log_perror("Failed to close $UpCase"); + goto error_exit; + } - if (vol->lcnbmp_na->data_size > vol->lcnbmp_na->allocated_size) { - ntfs_log_error("Corrupt cluster map size (%lld > %lld)\n", - (long long)vol->lcnbmp_na->data_size, - (long long)vol->lcnbmp_na->allocated_size); - goto io_error_exit; - } + /* + * Now load $Volume and set the version information and flags in the + * vol structure accordingly. + */ + ntfs_log_debug("Loading $Volume...\n"); + vol->vol_ni = ntfs_inode_open(vol, FILE_Volume); + if (!vol->vol_ni) { + ntfs_log_perror("Failed to open inode FILE_Volume"); + goto error_exit; + } + /* Get a search context for the $Volume/$VOLUME_INFORMATION lookup. */ + ctx = ntfs_attr_get_search_ctx(vol->vol_ni, NULL); + if (!ctx) + goto error_exit; - /* Now load the upcase table from $UpCase. */ - ntfs_log_debug("Loading $UpCase...\n"); - ni = ntfs_inode_open(vol, FILE_UpCase); - if (!ni) { - ntfs_log_perror("Failed to open inode FILE_UpCase"); - goto error_exit; - } - /* Get an ntfs attribute for $UpCase/$DATA. */ - na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); - if (!na) { - ntfs_log_perror("Failed to open ntfs attribute"); - goto error_exit; - } - /* - * Note: Normally, the upcase table has a length equal to 65536 - * 2-byte Unicode characters but allow for different cases, so no - * checks done. Just check we don't overflow 32-bits worth of Unicode - * characters. - */ - if (na->data_size & ~0x1ffffffffULL) { - ntfs_log_error("Error: Upcase table is too big (max 32-bit " - "allowed).\n"); - errno = EINVAL; - goto error_exit; - } - if (vol->upcase_len != na->data_size >> 1) { - vol->upcase_len = na->data_size >> 1; - /* Throw away default table. */ - free(vol->upcase); - vol->upcase = ntfs_malloc(na->data_size); - if (!vol->upcase) - goto error_exit; - } - /* Read in the $DATA attribute value into the buffer. */ - l = ntfs_attr_pread(na, 0, na->data_size, vol->upcase); - if (l != na->data_size) { - ntfs_log_error("Failed to read $UpCase, unexpected length " - "(%lld != %lld).\n", (long long)l, - (long long)na->data_size); - errno = EIO; - goto error_exit; - } - /* Done with the $UpCase mft record. */ - ntfs_attr_close(na); - if (ntfs_inode_close(ni)) { - ntfs_log_perror("Failed to close $UpCase"); - goto error_exit; - } + /* Find the $VOLUME_INFORMATION attribute. */ + if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL, + 0, ctx)) { + ntfs_log_perror("$VOLUME_INFORMATION attribute not found in " + "$Volume"); + goto error_exit; + } + a = ctx->attr; + /* Has to be resident. */ + if (a->non_resident) { + ntfs_log_error("Attribute $VOLUME_INFORMATION must be " + "resident but it isn't.\n"); + errno = EIO; + goto error_exit; + } + /* Get a pointer to the value of the attribute. */ + vinf = (VOLUME_INFORMATION*)(le16_to_cpu(a->value_offset) + (char*)a); + /* Sanity checks. */ + if ((char*)vinf + le32_to_cpu(a->value_length) > (char*)ctx->mrec + + le32_to_cpu(ctx->mrec->bytes_in_use) || + le16_to_cpu(a->value_offset) + le32_to_cpu( + a->value_length) > le32_to_cpu(a->length)) { + ntfs_log_error("$VOLUME_INFORMATION in $Volume is corrupt.\n"); + errno = EIO; + goto error_exit; + } + /* Setup vol from the volume information attribute value. */ + vol->major_ver = vinf->major_ver; + vol->minor_ver = vinf->minor_ver; + /* Do not use le16_to_cpu() macro here as our VOLUME_FLAGS are + defined using cpu_to_le16() macro and hence are consistent. */ + vol->flags = vinf->flags; + /* + * Reinitialize the search context for the $Volume/$VOLUME_NAME lookup. + */ + ntfs_attr_reinit_search_ctx(ctx); + if (ntfs_attr_lookup(AT_VOLUME_NAME, AT_UNNAMED, 0, 0, 0, NULL, 0, + ctx)) { + if (errno != ENOENT) { + ntfs_log_perror("Failed to lookup of $VOLUME_NAME in " + "$Volume failed"); + goto error_exit; + } + /* + * Attribute not present. This has been seen in the field. + * Treat this the same way as if the attribute was present but + * had zero length. + */ + vol->vol_name = ntfs_malloc(1); + if (!vol->vol_name) + goto error_exit; + vol->vol_name[0] = '\0'; + } else { + a = ctx->attr; + /* Has to be resident. */ + if (a->non_resident) { + ntfs_log_error("$VOLUME_NAME must be resident.\n"); + errno = EIO; + goto error_exit; + } + /* Get a pointer to the value of the attribute. */ + vname = (ntfschar*)(le16_to_cpu(a->value_offset) + (char*)a); + u = le32_to_cpu(a->value_length) / 2; + /* + * Convert Unicode volume name to current locale multibyte + * format. + */ + vol->vol_name = NULL; + if (ntfs_ucstombs(vname, u, &vol->vol_name, 0) == -1) { + ntfs_log_perror("Volume name could not be converted " + "to current locale"); + ntfs_log_debug("Forcing name into ASCII by replacing " + "non-ASCII characters with underscores.\n"); + vol->vol_name = ntfs_malloc(u + 1); + if (!vol->vol_name) + goto error_exit; + + for (j = 0; j < (s32)u; j++) { + ntfschar uc = le16_to_cpu(vname[j]); + if (uc > 0xff) + uc = (ntfschar)'_'; + vol->vol_name[j] = (char)uc; + } + vol->vol_name[u] = '\0'; + } + } + ntfs_attr_put_search_ctx(ctx); + ctx = NULL; + /* Now load the attribute definitions from $AttrDef. */ + ntfs_log_debug("Loading $AttrDef...\n"); + ni = ntfs_inode_open(vol, FILE_AttrDef); + if (!ni) { + ntfs_log_perror("Failed to open $AttrDef"); + goto error_exit; + } + /* Get an ntfs attribute for $AttrDef/$DATA. */ + na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); + if (!na) { + ntfs_log_perror("Failed to open ntfs attribute"); + goto error_exit; + } + /* Check we don't overflow 32-bits. */ + if (na->data_size > 0xffffffffLL) { + ntfs_log_error("Attribute definition table is too big (max " + "32-bit allowed).\n"); + errno = EINVAL; + goto error_exit; + } + vol->attrdef_len = na->data_size; + vol->attrdef = ntfs_malloc(na->data_size); + if (!vol->attrdef) + goto error_exit; + /* Read in the $DATA attribute value into the buffer. */ + l = ntfs_attr_pread(na, 0, na->data_size, vol->attrdef); + if (l != na->data_size) { + ntfs_log_error("Failed to read $AttrDef, unexpected length " + "(%lld != %lld).\n", (long long)l, + (long long)na->data_size); + errno = EIO; + goto error_exit; + } + /* Done with the $AttrDef mft record. */ + ntfs_attr_close(na); + if (ntfs_inode_close(ni)) { + ntfs_log_perror("Failed to close $AttrDef"); + goto error_exit; + } + /* + * Check for dirty logfile and hibernated Windows. + * We care only about read-write mounts. + */ + if (!(flags & MS_RDONLY)) { + if (!(flags & MS_IGNORE_HIBERFILE) && + ntfs_volume_check_hiberfile(vol, 1) < 0) + goto error_exit; + if (ntfs_volume_check_logfile(vol) < 0) { + if (!(flags & MS_RECOVER)) + goto error_exit; + ntfs_log_info("The file system wasn't safely " + "closed on Windows. Fixing.\n"); + if (ntfs_logfile_reset(vol)) + goto error_exit; + } + } - /* - * Now load $Volume and set the version information and flags in the - * vol structure accordingly. - */ - ntfs_log_debug("Loading $Volume...\n"); - vol->vol_ni = ntfs_inode_open(vol, FILE_Volume); - if (!vol->vol_ni) { - ntfs_log_perror("Failed to open inode FILE_Volume"); - goto error_exit; - } - /* Get a search context for the $Volume/$VOLUME_INFORMATION lookup. */ - ctx = ntfs_attr_get_search_ctx(vol->vol_ni, NULL); - if (!ctx) - goto error_exit; - - /* Find the $VOLUME_INFORMATION attribute. */ - if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL, - 0, ctx)) { - ntfs_log_perror("$VOLUME_INFORMATION attribute not found in " - "$Volume"); - goto error_exit; - } - a = ctx->attr; - /* Has to be resident. */ - if (a->non_resident) { - ntfs_log_error("Attribute $VOLUME_INFORMATION must be " - "resident but it isn't.\n"); - errno = EIO; - goto error_exit; - } - /* Get a pointer to the value of the attribute. */ - vinf = (VOLUME_INFORMATION*)(le16_to_cpu(a->value_offset) + (char*)a); - /* Sanity checks. */ - if ((char*)vinf + le32_to_cpu(a->value_length) > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_in_use) || - le16_to_cpu(a->value_offset) + le32_to_cpu( - a->value_length) > le32_to_cpu(a->length)) { - ntfs_log_error("$VOLUME_INFORMATION in $Volume is corrupt.\n"); - errno = EIO; - goto error_exit; - } - /* Setup vol from the volume information attribute value. */ - vol->major_ver = vinf->major_ver; - vol->minor_ver = vinf->minor_ver; - /* Do not use le16_to_cpu() macro here as our VOLUME_FLAGS are - defined using cpu_to_le16() macro and hence are consistent. */ - vol->flags = vinf->flags; - /* - * Reinitialize the search context for the $Volume/$VOLUME_NAME lookup. - */ - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(AT_VOLUME_NAME, AT_UNNAMED, 0, 0, 0, NULL, 0, - ctx)) { - if (errno != ENOENT) { - ntfs_log_perror("Failed to lookup of $VOLUME_NAME in " - "$Volume failed"); - goto error_exit; - } - /* - * Attribute not present. This has been seen in the field. - * Treat this the same way as if the attribute was present but - * had zero length. - */ - vol->vol_name = ntfs_malloc(1); - if (!vol->vol_name) - goto error_exit; - vol->vol_name[0] = '\0'; - } else { - a = ctx->attr; - /* Has to be resident. */ - if (a->non_resident) { - ntfs_log_error("$VOLUME_NAME must be resident.\n"); - errno = EIO; - goto error_exit; - } - /* Get a pointer to the value of the attribute. */ - vname = (ntfschar*)(le16_to_cpu(a->value_offset) + (char*)a); - u = le32_to_cpu(a->value_length) / 2; - /* - * Convert Unicode volume name to current locale multibyte - * format. - */ - vol->vol_name = NULL; - if (ntfs_ucstombs(vname, u, &vol->vol_name, 0) == -1) { - ntfs_log_perror("Volume name could not be converted " - "to current locale"); - ntfs_log_debug("Forcing name into ASCII by replacing " - "non-ASCII characters with underscores.\n"); - vol->vol_name = ntfs_malloc(u + 1); - if (!vol->vol_name) - goto error_exit; - - for (j = 0; j < (s32)u; j++) { - ntfschar uc = le16_to_cpu(vname[j]); - if (uc > 0xff) - uc = (ntfschar)'_'; - vol->vol_name[j] = (char)uc; - } - vol->vol_name[u] = '\0'; - } - } - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - /* Now load the attribute definitions from $AttrDef. */ - ntfs_log_debug("Loading $AttrDef...\n"); - ni = ntfs_inode_open(vol, FILE_AttrDef); - if (!ni) { - ntfs_log_perror("Failed to open $AttrDef"); - goto error_exit; - } - /* Get an ntfs attribute for $AttrDef/$DATA. */ - na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); - if (!na) { - ntfs_log_perror("Failed to open ntfs attribute"); - goto error_exit; - } - /* Check we don't overflow 32-bits. */ - if (na->data_size > 0xffffffffLL) { - ntfs_log_error("Attribute definition table is too big (max " - "32-bit allowed).\n"); - errno = EINVAL; - goto error_exit; - } - vol->attrdef_len = na->data_size; - vol->attrdef = ntfs_malloc(na->data_size); - if (!vol->attrdef) - goto error_exit; - /* Read in the $DATA attribute value into the buffer. */ - l = ntfs_attr_pread(na, 0, na->data_size, vol->attrdef); - if (l != na->data_size) { - ntfs_log_error("Failed to read $AttrDef, unexpected length " - "(%lld != %lld).\n", (long long)l, - (long long)na->data_size); - errno = EIO; - goto error_exit; - } - /* Done with the $AttrDef mft record. */ - ntfs_attr_close(na); - if (ntfs_inode_close(ni)) { - ntfs_log_perror("Failed to close $AttrDef"); - goto error_exit; - } - /* - * Check for dirty logfile and hibernated Windows. - * We care only about read-write mounts. - */ - if (!(flags & MS_RDONLY)) { - if (!(flags & MS_IGNORE_HIBERFILE) && - ntfs_volume_check_hiberfile(vol, 1) < 0) - goto error_exit; - if (ntfs_volume_check_logfile(vol) < 0) { - if (!(flags & MS_RECOVER)) - goto error_exit; - ntfs_log_info("The file system wasn't safely " - "closed on Windows. Fixing.\n"); - if (ntfs_logfile_reset(vol)) - goto error_exit; - } - } - - return vol; + return vol; io_error_exit: - errno = EIO; + errno = EIO; error_exit: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - free(m); - free(m2); - __ntfs_volume_release(vol); - errno = eo; - return NULL; + eo = errno; + if (ctx) + ntfs_attr_put_search_ctx(ctx); + free(m); + free(m2); + __ntfs_volume_release(vol); + errno = eo; + return NULL; } /** @@ -1140,32 +1152,33 @@ error_exit: * soon as the function returns. */ ntfs_volume *ntfs_mount(const char *name __attribute__((unused)), - unsigned long flags __attribute__((unused))) { + unsigned long flags __attribute__((unused))) +{ #ifndef NO_NTFS_DEVICE_DEFAULT_IO_OPS - struct ntfs_device *dev; - ntfs_volume *vol; + struct ntfs_device *dev; + ntfs_volume *vol; - /* Allocate an ntfs_device structure. */ - dev = ntfs_device_alloc(name, 0, &ntfs_device_default_io_ops, NULL); - if (!dev) - return NULL; - /* Call ntfs_device_mount() to do the actual mount. */ - vol = ntfs_device_mount(dev, flags); - if (!vol) { - int eo = errno; - ntfs_device_free(dev); - errno = eo; - } else - ntfs_create_lru_caches(vol); - return vol; + /* Allocate an ntfs_device structure. */ + dev = ntfs_device_alloc(name, 0, &ntfs_device_default_io_ops, NULL); + if (!dev) + return NULL; + /* Call ntfs_device_mount() to do the actual mount. */ + vol = ntfs_device_mount(dev, flags); + if (!vol) { + int eo = errno; + ntfs_device_free(dev); + errno = eo; + } else + ntfs_create_lru_caches(vol); + return vol; #else - /* - * ntfs_mount() makes no sense if NO_NTFS_DEVICE_DEFAULT_IO_OPS is - * defined as there are no device operations available in libntfs in - * this case. - */ - errno = EOPNOTSUPP; - return NULL; + /* + * ntfs_mount() makes no sense if NO_NTFS_DEVICE_DEFAULT_IO_OPS is + * defined as there are no device operations available in libntfs in + * this case. + */ + errno = EOPNOTSUPP; + return NULL; #endif } @@ -1191,18 +1204,19 @@ ntfs_volume *ntfs_mount(const char *name __attribute__((unused)), * function returns success. If it returns an error then nothing has been done * so it is safe to continue using @vol. */ -int ntfs_umount(ntfs_volume *vol, const BOOL force __attribute__((unused))) { - struct ntfs_device *dev; - int ret; +int ntfs_umount(ntfs_volume *vol, const BOOL force __attribute__((unused))) +{ + struct ntfs_device *dev; + int ret; - if (!vol) { - errno = EINVAL; - return -1; - } - dev = vol->dev; - ret = __ntfs_volume_release(vol); - ntfs_device_free(dev); - return ret; + if (!vol) { + errno = EINVAL; + return -1; + } + dev = vol->dev; + ret = __ntfs_volume_release(vol); + ntfs_device_free(dev); + return ret; } #ifdef HAVE_MNTENT_H @@ -1211,10 +1225,11 @@ int ntfs_umount(ntfs_volume *vol, const BOOL force __attribute__((unused))) { /** * realpath - If there is no realpath on the system */ -static char *realpath(const char *path, char *resolved_path) { - strncpy(resolved_path, path, PATH_MAX); - resolved_path[PATH_MAX] = '\0'; - return resolved_path; +static char *realpath(const char *path, char *resolved_path) +{ + strncpy(resolved_path, path, PATH_MAX); + resolved_path[PATH_MAX] = '\0'; + return resolved_path; } #endif @@ -1226,52 +1241,53 @@ static char *realpath(const char *path, char *resolved_path) { * * See description of ntfs_check_if_mounted(), below. */ -static int ntfs_mntent_check(const char *file, unsigned long *mnt_flags) { - struct mntent *mnt; - char *real_file = NULL, *real_fsname = NULL; - FILE *f; - int err = 0; +static int ntfs_mntent_check(const char *file, unsigned long *mnt_flags) +{ + struct mntent *mnt; + char *real_file = NULL, *real_fsname = NULL; + FILE *f; + int err = 0; - real_file = ntfs_malloc(PATH_MAX + 1); - if (!real_file) - return -1; - real_fsname = ntfs_malloc(PATH_MAX + 1); - if (!real_fsname) { - err = errno; - goto exit; - } - if (!realpath(file, real_file)) { - err = errno; - goto exit; - } - if (!(f = setmntent(MOUNTED, "r"))) { - err = errno; - goto exit; - } - while ((mnt = getmntent(f))) { - if (!realpath(mnt->mnt_fsname, real_fsname)) - continue; - if (!strcmp(real_file, real_fsname)) - break; - } - endmntent(f); - if (!mnt) - goto exit; - *mnt_flags = NTFS_MF_MOUNTED; - if (!strcmp(mnt->mnt_dir, "/")) - *mnt_flags |= NTFS_MF_ISROOT; + real_file = ntfs_malloc(PATH_MAX + 1); + if (!real_file) + return -1; + real_fsname = ntfs_malloc(PATH_MAX + 1); + if (!real_fsname) { + err = errno; + goto exit; + } + if (!realpath(file, real_file)) { + err = errno; + goto exit; + } + if (!(f = setmntent(MOUNTED, "r"))) { + err = errno; + goto exit; + } + while ((mnt = getmntent(f))) { + if (!realpath(mnt->mnt_fsname, real_fsname)) + continue; + if (!strcmp(real_file, real_fsname)) + break; + } + endmntent(f); + if (!mnt) + goto exit; + *mnt_flags = NTFS_MF_MOUNTED; + if (!strcmp(mnt->mnt_dir, "/")) + *mnt_flags |= NTFS_MF_ISROOT; #ifdef HAVE_HASMNTOPT - if (hasmntopt(mnt, "ro") && !hasmntopt(mnt, "rw")) - *mnt_flags |= NTFS_MF_READONLY; + if (hasmntopt(mnt, "ro") && !hasmntopt(mnt, "rw")) + *mnt_flags |= NTFS_MF_READONLY; #endif exit: - free(real_file); - free(real_fsname); - if (err) { - errno = err; - return -1; - } - return 0; + free(real_file); + free(real_fsname); + if (err) { + errno = err; + return -1; + } + return 0; } #endif /* HAVE_MNTENT_H */ @@ -1301,12 +1317,13 @@ exit: * On error return -1 with errno set to the error code. */ int ntfs_check_if_mounted(const char *file __attribute__((unused)), - unsigned long *mnt_flags) { - *mnt_flags = 0; + unsigned long *mnt_flags) +{ + *mnt_flags = 0; #ifdef HAVE_MNTENT_H - return ntfs_mntent_check(file, mnt_flags); + return ntfs_mntent_check(file, mnt_flags); #else - return 0; + return 0; #endif } @@ -1326,28 +1343,29 @@ int ntfs_check_if_mounted(const char *file __attribute__((unused)), * EOPNOTSUPP - Unknown NTFS version * EINVAL - Invalid argument */ -int ntfs_version_is_supported(ntfs_volume *vol) { - u8 major, minor; +int ntfs_version_is_supported(ntfs_volume *vol) +{ + u8 major, minor; - if (!vol) { - errno = EINVAL; - return -1; - } + if (!vol) { + errno = EINVAL; + return -1; + } - major = vol->major_ver; - minor = vol->minor_ver; + major = vol->major_ver; + minor = vol->minor_ver; - if (NTFS_V1_1(major, minor) || NTFS_V1_2(major, minor)) - return 0; + if (NTFS_V1_1(major, minor) || NTFS_V1_2(major, minor)) + return 0; - if (NTFS_V2_X(major, minor)) - return 0; + if (NTFS_V2_X(major, minor)) + return 0; - if (NTFS_V3_0(major, minor) || NTFS_V3_1(major, minor)) - return 0; + if (NTFS_V3_0(major, minor) || NTFS_V3_1(major, minor)) + return 0; - errno = EOPNOTSUPP; - return -1; + errno = EOPNOTSUPP; + return -1; } /** @@ -1365,42 +1383,43 @@ int ntfs_version_is_supported(ntfs_volume *vol) { * * On error return -1 with errno set to the error code. */ -int ntfs_logfile_reset(ntfs_volume *vol) { - ntfs_inode *ni; - ntfs_attr *na; - int eo; +int ntfs_logfile_reset(ntfs_volume *vol) +{ + ntfs_inode *ni; + ntfs_attr *na; + int eo; - if (!vol) { - errno = EINVAL; - return -1; - } + if (!vol) { + errno = EINVAL; + return -1; + } - ni = ntfs_inode_open(vol, FILE_LogFile); - if (!ni) { - ntfs_log_perror("Failed to open inode FILE_LogFile"); - return -1; - } + ni = ntfs_inode_open(vol, FILE_LogFile); + if (!ni) { + ntfs_log_perror("Failed to open inode FILE_LogFile"); + return -1; + } - na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); - if (!na) { - eo = errno; - ntfs_log_perror("Failed to open $FILE_LogFile/$DATA"); - goto error_exit; - } + na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0); + if (!na) { + eo = errno; + ntfs_log_perror("Failed to open $FILE_LogFile/$DATA"); + goto error_exit; + } - if (ntfs_empty_logfile(na)) { - eo = errno; - ntfs_attr_close(na); - goto error_exit; - } - - ntfs_attr_close(na); - return ntfs_inode_close(ni); + if (ntfs_empty_logfile(na)) { + eo = errno; + ntfs_attr_close(na); + goto error_exit; + } + + ntfs_attr_close(na); + return ntfs_inode_close(ni); error_exit: - ntfs_inode_close(ni); - errno = eo; - return -1; + ntfs_inode_close(ni); + errno = eo; + return -1; } /** @@ -1413,158 +1432,163 @@ error_exit: * * Return 0 if successful and -1 if not with errno set to the error code. */ -int ntfs_volume_write_flags(ntfs_volume *vol, const u16 flags) { - ATTR_RECORD *a; - VOLUME_INFORMATION *c; - ntfs_attr_search_ctx *ctx; - int ret = -1; /* failure */ +int ntfs_volume_write_flags(ntfs_volume *vol, const u16 flags) +{ + ATTR_RECORD *a; + VOLUME_INFORMATION *c; + ntfs_attr_search_ctx *ctx; + int ret = -1; /* failure */ - if (!vol || !vol->vol_ni) { - errno = EINVAL; - return -1; - } - /* Get a pointer to the volume information attribute. */ - ctx = ntfs_attr_get_search_ctx(vol->vol_ni, NULL); - if (!ctx) - return -1; + if (!vol || !vol->vol_ni) { + errno = EINVAL; + return -1; + } + /* Get a pointer to the volume information attribute. */ + ctx = ntfs_attr_get_search_ctx(vol->vol_ni, NULL); + if (!ctx) + return -1; - if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL, - 0, ctx)) { - ntfs_log_error("Attribute $VOLUME_INFORMATION was not found " - "in $Volume!\n"); - goto err_out; - } - a = ctx->attr; - /* Sanity check. */ - if (a->non_resident) { - ntfs_log_error("Attribute $VOLUME_INFORMATION must be resident " - "but it isn't.\n"); - errno = EIO; - goto err_out; - } - /* Get a pointer to the value of the attribute. */ - c = (VOLUME_INFORMATION*)(le16_to_cpu(a->value_offset) + (char*)a); - /* Sanity checks. */ - if ((char*)c + le32_to_cpu(a->value_length) > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_in_use) || - le16_to_cpu(a->value_offset) + - le32_to_cpu(a->value_length) > le32_to_cpu(a->length)) { - ntfs_log_error("Attribute $VOLUME_INFORMATION in $Volume is " - "corrupt!\n"); - errno = EIO; - goto err_out; - } - /* Set the volume flags. */ - vol->flags = c->flags = flags & VOLUME_FLAGS_MASK; - /* Write them to disk. */ - ntfs_inode_mark_dirty(vol->vol_ni); - if (ntfs_inode_sync(vol->vol_ni)) - goto err_out; + if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL, + 0, ctx)) { + ntfs_log_error("Attribute $VOLUME_INFORMATION was not found " + "in $Volume!\n"); + goto err_out; + } + a = ctx->attr; + /* Sanity check. */ + if (a->non_resident) { + ntfs_log_error("Attribute $VOLUME_INFORMATION must be resident " + "but it isn't.\n"); + errno = EIO; + goto err_out; + } + /* Get a pointer to the value of the attribute. */ + c = (VOLUME_INFORMATION*)(le16_to_cpu(a->value_offset) + (char*)a); + /* Sanity checks. */ + if ((char*)c + le32_to_cpu(a->value_length) > (char*)ctx->mrec + + le32_to_cpu(ctx->mrec->bytes_in_use) || + le16_to_cpu(a->value_offset) + + le32_to_cpu(a->value_length) > le32_to_cpu(a->length)) { + ntfs_log_error("Attribute $VOLUME_INFORMATION in $Volume is " + "corrupt!\n"); + errno = EIO; + goto err_out; + } + /* Set the volume flags. */ + vol->flags = c->flags = flags & VOLUME_FLAGS_MASK; + /* Write them to disk. */ + ntfs_inode_mark_dirty(vol->vol_ni); + if (ntfs_inode_sync(vol->vol_ni)) + goto err_out; - ret = 0; /* success */ + ret = 0; /* success */ err_out: - ntfs_attr_put_search_ctx(ctx); - return ret; + ntfs_attr_put_search_ctx(ctx); + return ret; } -int ntfs_volume_error(int err) { - int ret; +int ntfs_volume_error(int err) +{ + int ret; - switch (err) { - case 0: - ret = NTFS_VOLUME_OK; - break; - case EINVAL: - ret = NTFS_VOLUME_NOT_NTFS; - break; - case EIO: - ret = NTFS_VOLUME_CORRUPT; - break; - case EPERM: - ret = NTFS_VOLUME_HIBERNATED; - break; - case EOPNOTSUPP: - ret = NTFS_VOLUME_UNCLEAN_UNMOUNT; - break; - case EBUSY: - ret = NTFS_VOLUME_LOCKED; - break; - case ENXIO: - ret = NTFS_VOLUME_RAID; - break; - case EACCES: - ret = NTFS_VOLUME_NO_PRIVILEGE; - break; - default: - ret = NTFS_VOLUME_UNKNOWN_REASON; - break; - } - return ret; + switch (err) { + case 0: + ret = NTFS_VOLUME_OK; + break; + case EINVAL: + ret = NTFS_VOLUME_NOT_NTFS; + break; + case EIO: + ret = NTFS_VOLUME_CORRUPT; + break; + case EPERM: + ret = NTFS_VOLUME_HIBERNATED; + break; + case EOPNOTSUPP: + ret = NTFS_VOLUME_UNCLEAN_UNMOUNT; + break; + case EBUSY: + ret = NTFS_VOLUME_LOCKED; + break; + case ENXIO: + ret = NTFS_VOLUME_RAID; + break; + case EACCES: + ret = NTFS_VOLUME_NO_PRIVILEGE; + break; + default: + ret = NTFS_VOLUME_UNKNOWN_REASON; + break; + } + return ret; } -void ntfs_mount_error(const char *volume, const char *mntpoint, int err) { - switch (err) { - case NTFS_VOLUME_NOT_NTFS: - ntfs_log_error(invalid_ntfs_msg, volume); - break; - case NTFS_VOLUME_CORRUPT: - ntfs_log_error("%s", corrupt_volume_msg); - break; - case NTFS_VOLUME_HIBERNATED: - ntfs_log_error(hibernated_volume_msg, volume, mntpoint); - break; - case NTFS_VOLUME_UNCLEAN_UNMOUNT: - ntfs_log_error("%s", unclean_journal_msg); - break; - case NTFS_VOLUME_LOCKED: - ntfs_log_error("%s", opened_volume_msg); - break; - case NTFS_VOLUME_RAID: - ntfs_log_error("%s", fakeraid_msg); - break; - case NTFS_VOLUME_NO_PRIVILEGE: - ntfs_log_error(access_denied_msg, volume); - break; - } +void ntfs_mount_error(const char *volume, const char *mntpoint, int err) +{ + switch (err) { + case NTFS_VOLUME_NOT_NTFS: + ntfs_log_error(invalid_ntfs_msg, volume); + break; + case NTFS_VOLUME_CORRUPT: + ntfs_log_error("%s", corrupt_volume_msg); + break; + case NTFS_VOLUME_HIBERNATED: + ntfs_log_error(hibernated_volume_msg, volume, mntpoint); + break; + case NTFS_VOLUME_UNCLEAN_UNMOUNT: + ntfs_log_error("%s", unclean_journal_msg); + break; + case NTFS_VOLUME_LOCKED: + ntfs_log_error("%s", opened_volume_msg); + break; + case NTFS_VOLUME_RAID: + ntfs_log_error("%s", fakeraid_msg); + break; + case NTFS_VOLUME_NO_PRIVILEGE: + ntfs_log_error(access_denied_msg, volume); + break; + } } -int ntfs_set_locale(void) { - const char *locale; +int ntfs_set_locale(void) +{ + const char *locale; - locale = setlocale(LC_ALL, ""); - if (!locale) { - locale = setlocale(LC_ALL, NULL); - ntfs_log_error("Couldn't set local environment, using default " - "'%s'.\n", locale); - return 1; - } - return 0; + locale = setlocale(LC_ALL, ""); + if (!locale) { + locale = setlocale(LC_ALL, NULL); + ntfs_log_error("Couldn't set local environment, using default " + "'%s'.\n", locale); + return 1; + } + return 0; } /* * Feed the counts of free clusters and free mft records */ -int ntfs_volume_get_free_space(ntfs_volume *vol) { - ntfs_attr *na; - int ret; +int ntfs_volume_get_free_space(ntfs_volume *vol) +{ + ntfs_attr *na; + int ret; - ret = -1; /* default return */ - vol->free_clusters = ntfs_attr_get_free_bits(vol->lcnbmp_na); - if (vol->free_clusters < 0) { - ntfs_log_perror("Failed to read NTFS $Bitmap"); - } else { - na = vol->mftbmp_na; - vol->free_mft_records = ntfs_attr_get_free_bits(na); + ret = -1; /* default return */ + vol->free_clusters = ntfs_attr_get_free_bits(vol->lcnbmp_na); + if (vol->free_clusters < 0) { + ntfs_log_perror("Failed to read NTFS $Bitmap"); + } else { + na = vol->mftbmp_na; + vol->free_mft_records = ntfs_attr_get_free_bits(na); - if (vol->free_mft_records >= 0) - vol->free_mft_records += (na->allocated_size - na->data_size) << 3; + if (vol->free_mft_records >= 0) + vol->free_mft_records += (na->allocated_size - na->data_size) << 3; - if (vol->free_mft_records < 0) - ntfs_log_perror("Failed to calculate free MFT records"); - else - ret = 0; - } - return (ret); + if (vol->free_mft_records < 0) + ntfs_log_perror("Failed to calculate free MFT records"); + else + ret = 0; + } + return (ret); } diff --git a/source/libntfs/volume.h b/source/libntfs/volume.h index 823343ca..a0c71bdf 100644 --- a/source/libntfs/volume.h +++ b/source/libntfs/volume.h @@ -78,27 +78,27 @@ typedef struct _ntfs_volume ntfs_volume; * Flags returned by the ntfs_check_if_mounted() function. */ typedef enum { - NTFS_MF_MOUNTED = 1, /* Device is mounted. */ - NTFS_MF_ISROOT = 2, /* Device is mounted as system root. */ - NTFS_MF_READONLY = 4, /* Device is mounted read-only. */ + NTFS_MF_MOUNTED = 1, /* Device is mounted. */ + NTFS_MF_ISROOT = 2, /* Device is mounted as system root. */ + NTFS_MF_READONLY = 4, /* Device is mounted read-only. */ } ntfs_mount_flags; extern int ntfs_check_if_mounted(const char *file, unsigned long *mnt_flags); typedef enum { - NTFS_VOLUME_OK = 0, - NTFS_VOLUME_SYNTAX_ERROR = 11, - NTFS_VOLUME_NOT_NTFS = 12, - NTFS_VOLUME_CORRUPT = 13, - NTFS_VOLUME_HIBERNATED = 14, - NTFS_VOLUME_UNCLEAN_UNMOUNT = 15, - NTFS_VOLUME_LOCKED = 16, - NTFS_VOLUME_RAID = 17, - NTFS_VOLUME_UNKNOWN_REASON = 18, - NTFS_VOLUME_NO_PRIVILEGE = 19, - NTFS_VOLUME_OUT_OF_MEMORY = 20, - NTFS_VOLUME_FUSE_ERROR = 21, - NTFS_VOLUME_INSECURE = 22 + NTFS_VOLUME_OK = 0, + NTFS_VOLUME_SYNTAX_ERROR = 11, + NTFS_VOLUME_NOT_NTFS = 12, + NTFS_VOLUME_CORRUPT = 13, + NTFS_VOLUME_HIBERNATED = 14, + NTFS_VOLUME_UNCLEAN_UNMOUNT = 15, + NTFS_VOLUME_LOCKED = 16, + NTFS_VOLUME_RAID = 17, + NTFS_VOLUME_UNKNOWN_REASON = 18, + NTFS_VOLUME_NO_PRIVILEGE = 19, + NTFS_VOLUME_OUT_OF_MEMORY = 20, + NTFS_VOLUME_FUSE_ERROR = 21, + NTFS_VOLUME_INSECURE = 22 } ntfs_volume_status; /** @@ -107,9 +107,9 @@ typedef enum { * Defined bits for the state field in the ntfs_volume structure. */ typedef enum { - NV_ReadOnly, /* 1: Volume is read-only. */ - NV_CaseSensitive, /* 1: Volume is mounted case-sensitive. */ - NV_LogFileEmpty, /* 1: $logFile journal is empty. */ + NV_ReadOnly, /* 1: Volume is read-only. */ + NV_CaseSensitive, /* 1: Volume is mounted case-sensitive. */ + NV_LogFileEmpty, /* 1: $logFile journal is empty. */ } ntfs_volume_state_bits; #define test_nvol_flag(nv, flag) test_bit(NV_##flag, (nv)->state) @@ -147,99 +147,99 @@ typedef enum { * struct _ntfs_volume - structure describing an open volume in memory. */ struct _ntfs_volume { - union { - struct ntfs_device *dev; /* NTFS device associated with + union { + struct ntfs_device *dev; /* NTFS device associated with the volume. */ - void *sb; /* For kernel porting compatibility. */ - }; - char *vol_name; /* Name of the volume. */ - unsigned long state; /* NTFS specific flags describing this volume. + void *sb; /* For kernel porting compatibility. */ + }; + char *vol_name; /* Name of the volume. */ + unsigned long state; /* NTFS specific flags describing this volume. See ntfs_volume_state_bits above. */ - ntfs_inode *vol_ni; /* ntfs_inode structure for FILE_Volume. */ - u8 major_ver; /* Ntfs major version of volume. */ - u8 minor_ver; /* Ntfs minor version of volume. */ - u16 flags; /* Bit array of VOLUME_* flags. */ + ntfs_inode *vol_ni; /* ntfs_inode structure for FILE_Volume. */ + u8 major_ver; /* Ntfs major version of volume. */ + u8 minor_ver; /* Ntfs minor version of volume. */ + u16 flags; /* Bit array of VOLUME_* flags. */ - u16 sector_size; /* Byte size of a sector. */ - u8 sector_size_bits; /* Log(2) of the byte size of a sector. */ - u32 cluster_size; /* Byte size of a cluster. */ - u32 mft_record_size; /* Byte size of a mft record. */ - u32 indx_record_size; /* Byte size of a INDX record. */ - u8 cluster_size_bits; /* Log(2) of the byte size of a cluster. */ - u8 mft_record_size_bits;/* Log(2) of the byte size of a mft record. */ - u8 indx_record_size_bits;/* Log(2) of the byte size of a INDX record. */ + u16 sector_size; /* Byte size of a sector. */ + u8 sector_size_bits; /* Log(2) of the byte size of a sector. */ + u32 cluster_size; /* Byte size of a cluster. */ + u32 mft_record_size; /* Byte size of a mft record. */ + u32 indx_record_size; /* Byte size of a INDX record. */ + u8 cluster_size_bits; /* Log(2) of the byte size of a cluster. */ + u8 mft_record_size_bits;/* Log(2) of the byte size of a mft record. */ + u8 indx_record_size_bits;/* Log(2) of the byte size of a INDX record. */ - /* Variables used by the cluster and mft allocators. */ - u8 mft_zone_multiplier; /* Initial mft zone multiplier. */ - u8 full_zones; /* cluster zones which are full */ - s64 mft_data_pos; /* Mft record number at which to allocate the + /* Variables used by the cluster and mft allocators. */ + u8 mft_zone_multiplier; /* Initial mft zone multiplier. */ + u8 full_zones; /* cluster zones which are full */ + s64 mft_data_pos; /* Mft record number at which to allocate the next mft record. */ - LCN mft_zone_start; /* First cluster of the mft zone. */ - LCN mft_zone_end; /* First cluster beyond the mft zone. */ - LCN mft_zone_pos; /* Current position in the mft zone. */ - LCN data1_zone_pos; /* Current position in the first data zone. */ - LCN data2_zone_pos; /* Current position in the second data zone. */ + LCN mft_zone_start; /* First cluster of the mft zone. */ + LCN mft_zone_end; /* First cluster beyond the mft zone. */ + LCN mft_zone_pos; /* Current position in the mft zone. */ + LCN data1_zone_pos; /* Current position in the first data zone. */ + LCN data2_zone_pos; /* Current position in the second data zone. */ - s64 nr_clusters; /* Volume size in clusters, hence also the + s64 nr_clusters; /* Volume size in clusters, hence also the number of bits in lcn_bitmap. */ - ntfs_inode *lcnbmp_ni; /* ntfs_inode structure for FILE_Bitmap. */ - ntfs_attr *lcnbmp_na; /* ntfs_attr structure for the data attribute + ntfs_inode *lcnbmp_ni; /* ntfs_inode structure for FILE_Bitmap. */ + ntfs_attr *lcnbmp_na; /* ntfs_attr structure for the data attribute of FILE_Bitmap. Each bit represents a cluster on the volume, bit 0 representing lcn 0 and so on. A set bit means that the cluster and vice versa. */ - LCN mft_lcn; /* Logical cluster number of the data attribute + LCN mft_lcn; /* Logical cluster number of the data attribute for FILE_MFT. */ - ntfs_inode *mft_ni; /* ntfs_inode structure for FILE_MFT. */ - ntfs_attr *mft_na; /* ntfs_attr structure for the data attribute + ntfs_inode *mft_ni; /* ntfs_inode structure for FILE_MFT. */ + ntfs_attr *mft_na; /* ntfs_attr structure for the data attribute of FILE_MFT. */ - ntfs_attr *mftbmp_na; /* ntfs_attr structure for the bitmap attribute + ntfs_attr *mftbmp_na; /* ntfs_attr structure for the bitmap attribute of FILE_MFT. Each bit represents an mft record in the $DATA attribute, bit 0 representing mft record 0 and so on. A set bit means that the mft record is in use and vice versa. */ - ntfs_inode *secure_ni; /* ntfs_inode structure for FILE $Secure */ - ntfs_index_context *secure_xsii; /* index for using $Secure:$SII */ - ntfs_index_context *secure_xsdh; /* index for using $Secure:$SDH */ - int secure_reentry; /* check for non-rentries */ - unsigned int secure_flags; /* flags, see security.h for values */ + ntfs_inode *secure_ni; /* ntfs_inode structure for FILE $Secure */ + ntfs_index_context *secure_xsii; /* index for using $Secure:$SII */ + ntfs_index_context *secure_xsdh; /* index for using $Secure:$SDH */ + int secure_reentry; /* check for non-rentries */ + unsigned int secure_flags; /* flags, see security.h for values */ - int mftmirr_size; /* Size of the FILE_MFTMirr in mft records. */ - LCN mftmirr_lcn; /* Logical cluster number of the data attribute + int mftmirr_size; /* Size of the FILE_MFTMirr in mft records. */ + LCN mftmirr_lcn; /* Logical cluster number of the data attribute for FILE_MFTMirr. */ - ntfs_inode *mftmirr_ni; /* ntfs_inode structure for FILE_MFTMirr. */ - ntfs_attr *mftmirr_na; /* ntfs_attr structure for the data attribute + ntfs_inode *mftmirr_ni; /* ntfs_inode structure for FILE_MFTMirr. */ + ntfs_attr *mftmirr_na; /* ntfs_attr structure for the data attribute of FILE_MFTMirr. */ - ntfschar *upcase; /* Upper case equivalents of all 65536 2-byte + ntfschar *upcase; /* Upper case equivalents of all 65536 2-byte Unicode characters. Obtained from FILE_UpCase. */ - u32 upcase_len; /* Length in Unicode characters of the upcase + u32 upcase_len; /* Length in Unicode characters of the upcase table. */ - ATTR_DEF *attrdef; /* Attribute definitions. Obtained from + ATTR_DEF *attrdef; /* Attribute definitions. Obtained from FILE_AttrDef. */ - s32 attrdef_len; /* Size of the attribute definition table in + s32 attrdef_len; /* Size of the attribute definition table in bytes. */ - s64 free_clusters; /* Track the number of free clusters which + s64 free_clusters; /* Track the number of free clusters which greatly improves statfs() performance */ - s64 free_mft_records; /* Same for free mft records (see above) */ - BOOL efs_raw; /* volume is mounted for raw access to + s64 free_mft_records; /* Same for free mft records (see above) */ + BOOL efs_raw; /* volume is mounted for raw access to efs-encrypted files */ #if CACHE_INODE_SIZE - struct CACHE_HEADER *xinode_cache; + struct CACHE_HEADER *xinode_cache; #endif #if CACHE_SECURID_SIZE - struct CACHE_HEADER *securid_cache; + struct CACHE_HEADER *securid_cache; #endif #if CACHE_LEGACY_SIZE - struct CACHE_HEADER *legacy_cache; + struct CACHE_HEADER *legacy_cache; #endif }; @@ -249,10 +249,10 @@ extern const char *ntfs_home; extern ntfs_volume *ntfs_volume_alloc(void); extern ntfs_volume *ntfs_volume_startup(struct ntfs_device *dev, - unsigned long flags); + unsigned long flags); extern ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, - unsigned long flags); + unsigned long flags); extern ntfs_volume *ntfs_mount(const char *name, unsigned long flags); extern int ntfs_umount(ntfs_volume *vol, const BOOL force); diff --git a/source/libwbfs/libwbfs.c b/source/libwbfs/libwbfs.c index a2135f45..02886357 100644 --- a/source/libwbfs/libwbfs.c +++ b/source/libwbfs/libwbfs.c @@ -17,342 +17,369 @@ wbfs_t wbfs_iso_file; static int force_mode=0; -void wbfs_set_force_mode(int force) { - force_mode = force; +void wbfs_set_force_mode(int force) +{ + force_mode = force; } -static u8 size_to_shift(u32 size) { - u8 ret = 0; - while (size) { - ret++; - size>>=1; - } - return ret-1; +static u8 size_to_shift(u32 size) +{ + u8 ret = 0; + while(size) + { + ret++; + size>>=1; + } + return ret-1; } #define read_le32_unaligned(x) ((x)[0]|((x)[1]<<8)|((x)[2]<<16)|((x)[3]<<24)) wbfs_t*wbfs_open_hd(rw_sector_callback_t read_hdsector, - rw_sector_callback_t write_hdsector, - void *callback_data, - int hd_sector_size, int num_hd_sector __attribute((unused)), int reset) { - int i=num_hd_sector,ret; - u8 *ptr,*tmp_buffer = wbfs_ioalloc(hd_sector_size); - u8 part_table[16*4]; - ret = read_hdsector(callback_data,0,1,tmp_buffer); - if (ret) - return 0; - //find wbfs partition - wbfs_memcpy(part_table,tmp_buffer+0x1be,16*4); - ptr = part_table; - for (i=0;i<4;i++,ptr+=16) { - u32 part_lba = read_le32_unaligned(ptr+0x8); - wbfs_head_t *head = (wbfs_head_t *)tmp_buffer; - ret = read_hdsector(callback_data,part_lba,1,tmp_buffer); - // verify there is the magic. - if (head->magic == wbfs_htonl(WBFS_MAGIC)) { - wbfs_t*p = wbfs_open_partition(read_hdsector,write_hdsector, - callback_data,hd_sector_size,0,part_lba,reset); - wbfs_iofree(tmp_buffer); - return p; + rw_sector_callback_t write_hdsector, + void *callback_data, + int hd_sector_size, int num_hd_sector __attribute((unused)), int reset) +{ + int i=num_hd_sector,ret; + u8 *ptr,*tmp_buffer = wbfs_ioalloc(hd_sector_size); + u8 part_table[16*4]; + ret = read_hdsector(callback_data,0,1,tmp_buffer); + if(ret) + return 0; + //find wbfs partition + wbfs_memcpy(part_table,tmp_buffer+0x1be,16*4); + ptr = part_table; + for(i=0;i<4;i++,ptr+=16) + { + u32 part_lba = read_le32_unaligned(ptr+0x8); + wbfs_head_t *head = (wbfs_head_t *)tmp_buffer; + ret = read_hdsector(callback_data,part_lba,1,tmp_buffer); + // verify there is the magic. + if (head->magic == wbfs_htonl(WBFS_MAGIC)) + { + wbfs_t*p = wbfs_open_partition(read_hdsector,write_hdsector, + callback_data,hd_sector_size,0,part_lba,reset); + wbfs_iofree(tmp_buffer); + return p; + } } - } - wbfs_iofree(tmp_buffer); - if (reset) { // XXX make a empty hd partition.. - } - return 0; + wbfs_iofree(tmp_buffer); + if(reset)// XXX make a empty hd partition.. + { + } + return 0; } wbfs_t*wbfs_open_partition(rw_sector_callback_t read_hdsector, rw_sector_callback_t write_hdsector, void *callback_data, - int hd_sector_size, int num_hd_sector, u32 part_lba, int reset) { - wbfs_t *p = wbfs_malloc(sizeof(wbfs_t)); + int hd_sector_size, int num_hd_sector, u32 part_lba, int reset) +{ + wbfs_t *p = wbfs_malloc(sizeof(wbfs_t)); + + wbfs_head_t *head = wbfs_ioalloc(hd_sector_size?hd_sector_size:512); - wbfs_head_t *head = wbfs_ioalloc(hd_sector_size?hd_sector_size:512); + //constants, but put here for consistancy + p->wii_sec_sz = 0x8000; + p->wii_sec_sz_s = size_to_shift(0x8000); + p->n_wii_sec = (num_hd_sector/0x8000)*hd_sector_size; + p->n_wii_sec_per_disc = 143432*2;//support for double layers discs.. + p->head = head; + p->part_lba = part_lba; + // init the partition + if (reset) + { + u8 sz_s; + wbfs_memset(head,0,hd_sector_size); + head->magic = wbfs_htonl(WBFS_MAGIC); + head->hd_sec_sz_s = size_to_shift(hd_sector_size); + head->n_hd_sec = wbfs_htonl(num_hd_sector); + // choose minimum wblk_sz that fits this partition size + for(sz_s=6;sz_s<11;sz_s++) + { + // ensure that wbfs_sec_sz is big enough to address every blocks using 16 bits + if(p->n_wii_sec <((1U<<16)*(1<wbfs_sec_sz_s = sz_s+p->wii_sec_sz_s; + }else + read_hdsector(callback_data,p->part_lba,1,head); + if (head->magic != wbfs_htonl(WBFS_MAGIC)) + ERROR("bad magic"); + if(!force_mode && hd_sector_size && head->hd_sec_sz_s != size_to_shift(hd_sector_size)) + ERROR("hd sector size doesn't match"); + if(!force_mode && num_hd_sector && head->n_hd_sec != wbfs_htonl(num_hd_sector)) + ERROR("hd num sector doesn't match"); + p->hd_sec_sz = 1<hd_sec_sz_s; + p->hd_sec_sz_s = head->hd_sec_sz_s; + p->n_hd_sec = wbfs_ntohl(head->n_hd_sec); - //constants, but put here for consistancy - p->wii_sec_sz = 0x8000; - p->wii_sec_sz_s = size_to_shift(0x8000); - p->n_wii_sec = (num_hd_sector/0x8000)*hd_sector_size; - p->n_wii_sec_per_disc = 143432*2;//support for double layers discs.. - p->head = head; - p->part_lba = part_lba; - // init the partition - if (reset) { - u8 sz_s; - wbfs_memset(head,0,hd_sector_size); - head->magic = wbfs_htonl(WBFS_MAGIC); - head->hd_sec_sz_s = size_to_shift(hd_sector_size); - head->n_hd_sec = wbfs_htonl(num_hd_sector); - // choose minimum wblk_sz that fits this partition size - for (sz_s=6;sz_s<11;sz_s++) { - // ensure that wbfs_sec_sz is big enough to address every blocks using 16 bits - if (p->n_wii_sec <((1U<<16)*(1<n_wii_sec = (p->n_hd_sec/p->wii_sec_sz)*(p->hd_sec_sz); + + p->wbfs_sec_sz_s = head->wbfs_sec_sz_s; + p->wbfs_sec_sz = 1<wbfs_sec_sz_s; + p->n_wbfs_sec = p->n_wii_sec >> (p->wbfs_sec_sz_s - p->wii_sec_sz_s); + p->n_wbfs_sec_per_disc = p->n_wii_sec_per_disc >> (p->wbfs_sec_sz_s - p->wii_sec_sz_s); + p->disc_info_sz = ALIGN_LBA(sizeof(wbfs_disc_info_t) + p->n_wbfs_sec_per_disc*2); + + //printf("hd_sector_size %X wii_sector size %X wbfs sector_size %X\n",p->hd_sec_sz,p->wii_sec_sz,p->wbfs_sec_sz); + p->read_hdsector = read_hdsector; + p->write_hdsector = write_hdsector; + p->callback_data = callback_data; + + p->freeblks_lba = (p->wbfs_sec_sz - p->n_wbfs_sec/8)>>p->hd_sec_sz_s; + + if(!reset) + p->freeblks = 0; // will alloc and read only if needed + else + { + // init with all free blocks + p->freeblks = wbfs_ioalloc(ALIGN_LBA(p->n_wbfs_sec/8)); + wbfs_memset(p->freeblks,0xff,p->n_wbfs_sec/8); } - head->wbfs_sec_sz_s = sz_s+p->wii_sec_sz_s; - } else - read_hdsector(callback_data,p->part_lba,1,head); - if (head->magic != wbfs_htonl(WBFS_MAGIC)) - ERROR("bad magic"); - if (!force_mode && hd_sector_size && head->hd_sec_sz_s != size_to_shift(hd_sector_size)) - ERROR("hd sector size doesn't match"); - if (!force_mode && num_hd_sector && head->n_hd_sec != wbfs_htonl(num_hd_sector)) - ERROR("hd num sector doesn't match"); - p->hd_sec_sz = 1<hd_sec_sz_s; - p->hd_sec_sz_s = head->hd_sec_sz_s; - p->n_hd_sec = wbfs_ntohl(head->n_hd_sec); + p->max_disc = (p->freeblks_lba-1)/(p->disc_info_sz>>p->hd_sec_sz_s); + if(p->max_disc > p->hd_sec_sz - sizeof(wbfs_head_t)) + p->max_disc = p->hd_sec_sz - sizeof(wbfs_head_t); - p->n_wii_sec = (p->n_hd_sec/p->wii_sec_sz)*(p->hd_sec_sz); - - p->wbfs_sec_sz_s = head->wbfs_sec_sz_s; - p->wbfs_sec_sz = 1<wbfs_sec_sz_s; - p->n_wbfs_sec = p->n_wii_sec >> (p->wbfs_sec_sz_s - p->wii_sec_sz_s); - p->n_wbfs_sec_per_disc = p->n_wii_sec_per_disc >> (p->wbfs_sec_sz_s - p->wii_sec_sz_s); - p->disc_info_sz = ALIGN_LBA(sizeof(wbfs_disc_info_t) + p->n_wbfs_sec_per_disc*2); - - //printf("hd_sector_size %X wii_sector size %X wbfs sector_size %X\n",p->hd_sec_sz,p->wii_sec_sz,p->wbfs_sec_sz); - p->read_hdsector = read_hdsector; - p->write_hdsector = write_hdsector; - p->callback_data = callback_data; - - p->freeblks_lba = (p->wbfs_sec_sz - p->n_wbfs_sec/8)>>p->hd_sec_sz_s; - - if (!reset) - p->freeblks = 0; // will alloc and read only if needed - else { - // init with all free blocks - p->freeblks = wbfs_ioalloc(ALIGN_LBA(p->n_wbfs_sec/8)); - wbfs_memset(p->freeblks,0xff,p->n_wbfs_sec/8); - } - p->max_disc = (p->freeblks_lba-1)/(p->disc_info_sz>>p->hd_sec_sz_s); - if (p->max_disc > p->hd_sec_sz - sizeof(wbfs_head_t)) - p->max_disc = p->hd_sec_sz - sizeof(wbfs_head_t); - - p->tmp_buffer = wbfs_ioalloc(p->hd_sec_sz); - p->n_disc_open = 0; - return p; + p->tmp_buffer = wbfs_ioalloc(p->hd_sec_sz); + p->n_disc_open = 0; + return p; error: - wbfs_free(p); - wbfs_iofree(head); - return 0; - + wbfs_free(p); + wbfs_iofree(head); + return 0; + } -void wbfs_sync(wbfs_t*p) { - // copy back descriptors - if (p->write_hdsector) { - p->write_hdsector(p->callback_data,p->part_lba+0,1, p->head); - - if (p->freeblks) - p->write_hdsector(p->callback_data,p->part_lba+p->freeblks_lba,ALIGN_LBA(p->n_wbfs_sec/8)>>p->hd_sec_sz_s, p->freeblks); - } +void wbfs_sync(wbfs_t*p) +{ + // copy back descriptors + if(p->write_hdsector){ + p->write_hdsector(p->callback_data,p->part_lba+0,1, p->head); + + if(p->freeblks) + p->write_hdsector(p->callback_data,p->part_lba+p->freeblks_lba,ALIGN_LBA(p->n_wbfs_sec/8)>>p->hd_sec_sz_s, p->freeblks); + } } -void wbfs_close(wbfs_t*p) { - wbfs_sync(p); +void wbfs_close(wbfs_t*p) +{ + wbfs_sync(p); - if (p->n_disc_open) - ERROR("trying to close wbfs while discs still open"); - - wbfs_iofree(p->head); - wbfs_iofree(p->tmp_buffer); - if (p->freeblks) - wbfs_iofree(p->freeblks); - - wbfs_free(p); + if(p->n_disc_open) + ERROR("trying to close wbfs while discs still open"); + wbfs_iofree(p->head); + wbfs_iofree(p->tmp_buffer); + if(p->freeblks) + wbfs_iofree(p->freeblks); + + wbfs_free(p); + error: - return; + return; } -wbfs_disc_t *wbfs_open_disc(wbfs_t* p, u8 *discid) { - u32 i; - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - wbfs_disc_t *d = 0; - for (i=0;imax_disc;i++) { - if (p->head->disc_table[i]) { - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba,1,p->tmp_buffer); - if (wbfs_memcmp(discid,p->tmp_buffer,6)==0) { - d = wbfs_malloc(sizeof(*d)); - if (!d) - ERROR("allocating memory"); - d->p = p; - d->i = i; - d->header = wbfs_ioalloc(p->disc_info_sz); - if (!d->header) - ERROR("allocating memory"); - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba, - disc_info_sz_lba,d->header); - p->n_disc_open ++; +wbfs_disc_t *wbfs_open_disc(wbfs_t* p, u8 *discid) +{ + u32 i; + int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; + wbfs_disc_t *d = 0; + for(i=0;imax_disc;i++) + { + if (p->head->disc_table[i]){ + p->read_hdsector(p->callback_data, + p->part_lba+1+i*disc_info_sz_lba,1,p->tmp_buffer); + if(wbfs_memcmp(discid,p->tmp_buffer,6)==0){ + d = wbfs_malloc(sizeof(*d)); + if(!d) + ERROR("allocating memory"); + d->p = p; + d->i = i; + d->header = wbfs_ioalloc(p->disc_info_sz); + if(!d->header) + ERROR("allocating memory"); + p->read_hdsector(p->callback_data, + p->part_lba+1+i*disc_info_sz_lba, + disc_info_sz_lba,d->header); + p->n_disc_open ++; // for(i=0;in_wbfs_sec_per_disc;i++) // printf("%d,",wbfs_ntohs(d->header->wlba_table[i])); - return d; - } + return d; + } + } } - } - return 0; + return 0; error: - if (d) - wbfs_iofree(d); - return 0; - + if(d) + wbfs_iofree(d); + return 0; + } -void wbfs_close_disc(wbfs_disc_t*d) { - d->p->n_disc_open --; - wbfs_iofree(d->header); - wbfs_free(d); +void wbfs_close_disc(wbfs_disc_t*d) +{ + d->p->n_disc_open --; + wbfs_iofree(d->header); + wbfs_free(d); } // offset is pointing 32bit words to address the whole dvd, although len is in bytes -int wbfs_disc_read(wbfs_disc_t*d,u32 offset, u32 len, u8 *data) { - if (d->p == &wbfs_iso_file) { - return wbfs_iso_file_read(d, offset, data, len); - } - - wbfs_t *p = d->p; - u16 wlba = offset>>(p->wbfs_sec_sz_s-2); - u32 iwlba_shift = p->wbfs_sec_sz_s - p->hd_sec_sz_s; - u32 lba_mask = (p->wbfs_sec_sz-1)>>(p->hd_sec_sz_s); - u32 lba = (offset>>(p->hd_sec_sz_s-2))&lba_mask; - u32 off = offset&((p->hd_sec_sz>>2)-1); - u16 iwlba = wbfs_ntohs(d->header->wlba_table[wlba]); - u32 len_copied; - int err = 0; - u8 *ptr = data; - if (unlikely(iwlba==0)) - return 1; - if (unlikely(off)) { - off*=4; - err = p->read_hdsector(p->callback_data, - p->part_lba + (iwlba<tmp_buffer); - if (err) - return err; - len_copied = p->hd_sec_sz - off; - if (likely(len < len_copied)) - len_copied = len; - wbfs_memcpy(ptr, p->tmp_buffer + off, len_copied); - len -= len_copied; - ptr += len_copied; - lba++; - if (unlikely(lba>lba_mask && len)) { - lba=0; - iwlba = wbfs_ntohs(d->header->wlba_table[++wlba]); - if (unlikely(iwlba==0)) +int wbfs_disc_read(wbfs_disc_t*d,u32 offset, u32 len, u8 *data) +{ + if (d->p == &wbfs_iso_file) { + return wbfs_iso_file_read(d, offset, data, len); + } + + wbfs_t *p = d->p; + u16 wlba = offset>>(p->wbfs_sec_sz_s-2); + u32 iwlba_shift = p->wbfs_sec_sz_s - p->hd_sec_sz_s; + u32 lba_mask = (p->wbfs_sec_sz-1)>>(p->hd_sec_sz_s); + u32 lba = (offset>>(p->hd_sec_sz_s-2))&lba_mask; + u32 off = offset&((p->hd_sec_sz>>2)-1); + u16 iwlba = wbfs_ntohs(d->header->wlba_table[wlba]); + u32 len_copied; + int err = 0; + u8 *ptr = data; + if(unlikely(iwlba==0)) return 1; + if(unlikely(off)){ + off*=4; + err = p->read_hdsector(p->callback_data, + p->part_lba + (iwlba<tmp_buffer); + if(err) + return err; + len_copied = p->hd_sec_sz - off; + if(likely(len < len_copied)) + len_copied = len; + wbfs_memcpy(ptr, p->tmp_buffer + off, len_copied); + len -= len_copied; + ptr += len_copied; + lba++; + if(unlikely(lba>lba_mask && len)){ + lba=0; + iwlba = wbfs_ntohs(d->header->wlba_table[++wlba]); + if(unlikely(iwlba==0)) + return 1; + } } - } - while (likely(len>=p->hd_sec_sz)) { - u32 nlb = len>>(p->hd_sec_sz_s); - - if (unlikely(lba + nlb > p->wbfs_sec_sz)) // dont cross wbfs sectors.. - nlb = p->wbfs_sec_sz-lba; - err = p->read_hdsector(p->callback_data, - p->part_lba + (iwlba<hd_sec_sz_s; - ptr += nlb<hd_sec_sz_s; - lba += nlb; - if (unlikely(lba>lba_mask && len)) { - lba = 0; - iwlba =wbfs_ntohs(d->header->wlba_table[++wlba]); - if (unlikely(iwlba==0)) - return 1; + while(likely(len>=p->hd_sec_sz)) + { + u32 nlb = len>>(p->hd_sec_sz_s); + + if(unlikely(lba + nlb > p->wbfs_sec_sz)) // dont cross wbfs sectors.. + nlb = p->wbfs_sec_sz-lba; + err = p->read_hdsector(p->callback_data, + p->part_lba + (iwlba<hd_sec_sz_s; + ptr += nlb<hd_sec_sz_s; + lba += nlb; + if(unlikely(lba>lba_mask && len)){ + lba = 0; + iwlba =wbfs_ntohs(d->header->wlba_table[++wlba]); + if(unlikely(iwlba==0)) + return 1; + } } - } - if (unlikely(len)) { - err = p->read_hdsector(p->callback_data, - p->part_lba + (iwlba<tmp_buffer); - if (err) - return err; - wbfs_memcpy(ptr, p->tmp_buffer, len); - } - return 0; + if(unlikely(len)){ + err = p->read_hdsector(p->callback_data, + p->part_lba + (iwlba<tmp_buffer); + if(err) + return err; + wbfs_memcpy(ptr, p->tmp_buffer, len); + } + return 0; } // disc listing -u32 wbfs_count_discs(wbfs_t*p) { - u32 i,count=0; - for (i=0;imax_disc;i++) - if (p->head->disc_table[i]) - count++; - return count; - +u32 wbfs_count_discs(wbfs_t*p) +{ + u32 i,count=0; + for(i=0;imax_disc;i++) + if (p->head->disc_table[i]) + count++; + return count; + } -u32 wbfs_sector_used(wbfs_t *p,wbfs_disc_info_t *di) { - u32 tot_blk=0,j; - for (j=0;jn_wbfs_sec_per_disc;j++) - if (wbfs_ntohs(di->wlba_table[j])) - tot_blk++; - return tot_blk; +u32 wbfs_sector_used(wbfs_t *p,wbfs_disc_info_t *di) +{ + u32 tot_blk=0,j; + for(j=0;jn_wbfs_sec_per_disc;j++) + if(wbfs_ntohs(di->wlba_table[j])) + tot_blk++; + return tot_blk; } -u32 wbfs_sector_used2(wbfs_t *p, wbfs_disc_info_t *di, u32 *last_blk) { - u32 tot_blk=0,j; - for (j=0;jn_wbfs_sec_per_disc;j++) - if (wbfs_ntohs(di->wlba_table[j])) { - if (last_blk) *last_blk = j; - tot_blk++; - } - return tot_blk; -} - -u32 wbfs_get_disc_info(wbfs_t*p, u32 index,u8 *header,int header_size,u32 *size) { //size in 32 bit - u32 i,count=0; - if (!p) return 1; - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - - for (i=0;imax_disc;i++) - if (p->head->disc_table[i]) { - if (count++==index) { - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba,1,p->tmp_buffer); - if (header_size > (int)p->hd_sec_sz) - header_size = p->hd_sec_sz; - u32 magic = wbfs_ntohl(*(u32*)(p->tmp_buffer+24)); - if (magic!=0x5D1C9EA3) { - p->head->disc_table[i]=0; - return 1; +u32 wbfs_sector_used2(wbfs_t *p, wbfs_disc_info_t *di, u32 *last_blk) +{ + u32 tot_blk=0,j; + for(j=0;jn_wbfs_sec_per_disc;j++) + if(wbfs_ntohs(di->wlba_table[j])) { + if (last_blk) *last_blk = j; + tot_blk++; } - memcpy(header,p->tmp_buffer,header_size); - if (size) { - u8 *header = wbfs_ioalloc(p->disc_info_sz); - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba,disc_info_sz_lba,header); - u32 sec_used = wbfs_sector_used(p,(wbfs_disc_info_t *)header); - wbfs_iofree(header); - *size = sec_used<<(p->wbfs_sec_sz_s-2); + return tot_blk; +} + +u32 wbfs_get_disc_info(wbfs_t*p, u32 index,u8 *header,int header_size,u32 *size)//size in 32 bit +{ + u32 i,count=0; + if (!p) return 1; + int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; + + for(i=0;imax_disc;i++) + if (p->head->disc_table[i]){ + if(count++==index) + { + p->read_hdsector(p->callback_data, + p->part_lba+1+i*disc_info_sz_lba,1,p->tmp_buffer); + if(header_size > (int)p->hd_sec_sz) + header_size = p->hd_sec_sz; + u32 magic = wbfs_ntohl(*(u32*)(p->tmp_buffer+24)); + if(magic!=0x5D1C9EA3){ + p->head->disc_table[i]=0; + return 1; + } + memcpy(header,p->tmp_buffer,header_size); + if(size) + { + u8 *header = wbfs_ioalloc(p->disc_info_sz); + p->read_hdsector(p->callback_data, + p->part_lba+1+i*disc_info_sz_lba,disc_info_sz_lba,header); + u32 sec_used = wbfs_sector_used(p,(wbfs_disc_info_t *)header); + wbfs_iofree(header); + *size = sec_used<<(p->wbfs_sec_sz_s-2); + } + return 0; + } } - return 0; - } + return 1; +} + +static void load_freeblocks(wbfs_t*p) +{ + if(p->freeblks) + return; + // XXX should handle malloc error.. + p->freeblks = wbfs_ioalloc(ALIGN_LBA(p->n_wbfs_sec/8)); + p->read_hdsector(p->callback_data,p->part_lba+p->freeblks_lba,ALIGN_LBA(p->n_wbfs_sec/8)>>p->hd_sec_sz_s, p->freeblks); + +} +u32 wbfs_count_usedblocks(wbfs_t*p) +{ + u32 i,j,count=0; + load_freeblocks(p); + for(i=0;in_wbfs_sec/(8*4);i++) + { + u32 v = wbfs_ntohl(p->freeblks[i]); + if(v == ~0U) + count+=32; + else if(v!=0) + for(j=0;j<32;j++) + if (v & (1<freeblks) - return; - // XXX should handle malloc error.. - p->freeblks = wbfs_ioalloc(ALIGN_LBA(p->n_wbfs_sec/8)); - p->read_hdsector(p->callback_data,p->part_lba+p->freeblks_lba,ALIGN_LBA(p->n_wbfs_sec/8)>>p->hd_sec_sz_s, p->freeblks); - -} -u32 wbfs_count_usedblocks(wbfs_t*p) { - u32 i,j,count=0; - load_freeblocks(p); - for (i=0;in_wbfs_sec/(8*4);i++) { - u32 v = wbfs_ntohl(p->freeblks[i]); - if (v == ~0U) - count+=32; - else if (v!=0) - for (j=0;j<32;j++) - if (v & (1<n_wbfs_sec/(8*4);i++) { - u32 v = wbfs_ntohl(p->freeblks[i]); - if (v != 0) { - for (j=0;j<32;j++) - if (v & (1<freeblks[i] = wbfs_htonl(v & ~(1<n_wbfs_sec/(8*4);i++) + { + u32 v = wbfs_ntohl(p->freeblks[i]); + if(v != 0) + { + for(j=0;j<32;j++) + if (v & (1<freeblks[i] = wbfs_htonl(v & ~(1<freeblks[i]); - p->freeblks[i] = wbfs_htonl(v | 1<freeblks[i]); + p->freeblks[i] = wbfs_htonl(v | 1<wbfs_sec_sz_s-p->wii_sec_sz_s); - wiidisc_t *d = 0; - u8 *used = 0; - wbfs_disc_info_t *info = 0; - u8* copy_buffer = 0; - int retval = -1; - int num_wbfs_sect_to_copy; - u32 last_used; - used = wbfs_malloc(p->n_wii_sec_per_disc); + void *callback_data,progress_callback_t spinner,partition_selector_t sel,int copy_1_1) +{ + int i,discn; + u32 tot,cur; + u32 wii_sec_per_wbfs_sect = 1<<(p->wbfs_sec_sz_s-p->wii_sec_sz_s); + wiidisc_t *d = 0; + u8 *used = 0; + wbfs_disc_info_t *info = 0; + u8* copy_buffer = 0; + int retval = -1; + int num_wbfs_sect_to_copy; + u32 last_used; + used = wbfs_malloc(p->n_wii_sec_per_disc); - if (!used) - ERROR("unable to alloc memory"); - // copy_1_1 needs disk usage for layers detection - //if(!copy_1_1) - { - d = wd_open_disc(read_src_wii_disc,callback_data); - if (!d) - ERROR("unable to open wii disc"); - wd_build_disc_usage(d,sel,used); - wd_close_disc(d); - d = 0; - } + if(!used) + ERROR("unable to alloc memory"); + // copy_1_1 needs disk usage for layers detection + //if(!copy_1_1) + { + d = wd_open_disc(read_src_wii_disc,callback_data); + if(!d) + ERROR("unable to open wii disc"); + wd_build_disc_usage(d,sel,used); + wd_close_disc(d); + d = 0; + } - for (i=0;imax_disc;i++)// find a free slot. - if (p->head->disc_table[i]==0) - break; - if (i==p->max_disc) - ERROR("no space left on device (table full)"); - p->head->disc_table[i] = 1; - discn = i; - load_freeblocks(p); + for(i=0;imax_disc;i++)// find a free slot. + if(p->head->disc_table[i]==0) + break; + if(i==p->max_disc) + ERROR("no space left on device (table full)"); + p->head->disc_table[i] = 1; + discn = i; + load_freeblocks(p); - // build disc info - info = wbfs_ioalloc(p->disc_info_sz); - read_src_wii_disc(callback_data,0,0x100,info->disc_header_copy); + // build disc info + info = wbfs_ioalloc(p->disc_info_sz); + read_src_wii_disc(callback_data,0,0x100,info->disc_header_copy); - copy_buffer = wbfs_ioalloc(p->wii_sec_sz); - if (!copy_buffer) - ERROR("alloc memory"); - tot=0; - cur=0; - num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; - // count total number of sectors to write - last_used = 0; - for (i=0; i (p->n_wbfs_sec_per_disc / 2) ) { - // dual layer - num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; - } else { - // single layer - num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc / 2; - } - tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; - } - /* - // num of hd sectors to copy could be specified directly - if (copy_1_1 > 1) { - u32 hd_sec_per_wii_sec = p->wii_sec_sz / p->hd_sec_sz; - num_wbfs_sect_to_copy = copy_1_1 / hd_sec_per_wii_sec / wii_sec_per_wbfs_sect; - tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; - }*/ - int ret = 0; - if (spinner) spinner(0,tot); - for (i=0; iwii_sec_sz); + if(!copy_buffer) + ERROR("alloc memory"); + tot=0; + cur=0; + num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; + // count total number of sectors to write + last_used = 0; + for(i=0; i (p->n_wbfs_sec_per_disc / 2) ) { + // dual layer + num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; + } else { + // single layer + num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc / 2; + } + tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; + } + /* + // num of hd sectors to copy could be specified directly + if (copy_1_1 > 1) { + u32 hd_sec_per_wii_sec = p->wii_sec_sz / p->hd_sec_sz; + num_wbfs_sect_to_copy = copy_1_1 / hd_sec_per_wii_sec / wii_sec_per_wbfs_sect; + tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; + }*/ + int ret = 0; + if(spinner) spinner(0,tot); + for(i=0; iwbfs_sec_sz>>2)) + (j*(p->wii_sec_sz>>2)); + bl = alloc_block(p); + if (bl==0xffff) + ERROR("no space left on device (disc full)"); + for(j=0; jwbfs_sec_sz>>2)) + (j*(p->wii_sec_sz>>2)); - ret = read_src_wii_disc(callback_data,offset,p->wii_sec_sz,copy_buffer); - if (ret) { - if (copy_1_1 && i > p->n_wbfs_sec_per_disc / 2) { - // end of dual layer data - if (j > 0) { - info->wlba_table[i] = wbfs_htons(bl); - } - spinner(tot,tot); - break; - } - //ERROR("read error"); - printf("\rWARNING: read (%u) error (%d)\n", offset, ret); - } + ret = read_src_wii_disc(callback_data,offset,p->wii_sec_sz,copy_buffer); + if (ret) { + if (copy_1_1 && i > p->n_wbfs_sec_per_disc / 2) { + // end of dual layer data + if (j > 0) { + info->wlba_table[i] = wbfs_htons(bl); + } + spinner(tot,tot); + break; + } + //ERROR("read error"); + printf("\rWARNING: read (%u) error (%d)\n", offset, ret); + } - //fix the partition table - if (offset == (0x40000>>2)) - wd_fix_partition_table(d, sel, copy_buffer); - p->write_hdsector(p->callback_data, - p->part_lba+bl*(p->wbfs_sec_sz/p->hd_sec_sz) + j*(p->wii_sec_sz/p->hd_sec_sz), - p->wii_sec_sz/p->hd_sec_sz, copy_buffer); - cur++; - if (spinner) - spinner(cur,tot); - } - } - if (ret) break; - info->wlba_table[i] = wbfs_htons(bl); - } - // write disc info - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - p->write_hdsector(p->callback_data,p->part_lba+1+discn*disc_info_sz_lba,disc_info_sz_lba,info); - wbfs_sync(p); - retval = 0; + //fix the partition table + if(offset == (0x40000>>2)) + wd_fix_partition_table(d, sel, copy_buffer); + p->write_hdsector(p->callback_data, + p->part_lba+bl*(p->wbfs_sec_sz/p->hd_sec_sz) + j*(p->wii_sec_sz/p->hd_sec_sz), + p->wii_sec_sz/p->hd_sec_sz, copy_buffer); + cur++; + if(spinner) + spinner(cur,tot); + } + } + if (ret) break; + info->wlba_table[i] = wbfs_htons(bl); + } + // write disc info + int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; + p->write_hdsector(p->callback_data,p->part_lba+1+discn*disc_info_sz_lba,disc_info_sz_lba,info); + wbfs_sync(p); + retval = 0; error: - if (d) - wd_close_disc(d); - if (used) - wbfs_free(used); - if (info) - wbfs_iofree(info); - if (copy_buffer) - wbfs_iofree(copy_buffer); - // init with all free blocks + if(d) + wd_close_disc(d); + if(used) + wbfs_free(used); + if(info) + wbfs_iofree(info); + if(copy_buffer) + wbfs_iofree(copy_buffer); + // init with all free blocks - return retval; + return retval; } -u32 wbfs_rm_disc(wbfs_t*p, u8* discid) { - wbfs_disc_t *d = wbfs_open_disc(p,discid); - int i; - int discn = 0; - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - if (!d) - return 1; - load_freeblocks(p); - discn = d->i; - for ( i=0; i< p->n_wbfs_sec_per_disc; i++) { - u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); - if (iwlba) - free_block(p,iwlba); - } - memset(d->header,0,p->disc_info_sz); - p->write_hdsector(p->callback_data,p->part_lba+1+discn*disc_info_sz_lba,disc_info_sz_lba,d->header); - p->head->disc_table[discn] = 0; - wbfs_close_disc(d); - wbfs_sync(p); - return 0; +u32 wbfs_rm_disc(wbfs_t*p, u8* discid) +{ + wbfs_disc_t *d = wbfs_open_disc(p,discid); + int i; + int discn = 0; + int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; + if(!d) + return 1; + load_freeblocks(p); + discn = d->i; + for( i=0; i< p->n_wbfs_sec_per_disc; i++) + { + u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); + if (iwlba) + free_block(p,iwlba); + } + memset(d->header,0,p->disc_info_sz); + p->write_hdsector(p->callback_data,p->part_lba+1+discn*disc_info_sz_lba,disc_info_sz_lba,d->header); + p->head->disc_table[discn] = 0; + wbfs_close_disc(d); + wbfs_sync(p); + return 0; } -u32 wbfs_ren_disc(wbfs_t*p, u8* discid, u8* newname) { - wbfs_disc_t *d = wbfs_open_disc(p,discid); - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; +u32 wbfs_ren_disc(wbfs_t*p, u8* discid, u8* newname) +{ + wbfs_disc_t *d = wbfs_open_disc(p,discid); + int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - if (!d) - return 1; + if(!d) + return 1; - memset(d->header->disc_header_copy+0x20, 0, 0x40); - strncpy((char *) d->header->disc_header_copy+0x20, (char *) newname, 0x39); + memset(d->header->disc_header_copy+0x20, 0, 0x40); + strncpy((char *) d->header->disc_header_copy+0x20, (char *) newname, 0x39); - p->write_hdsector(p->callback_data,p->part_lba+1+d->i*disc_info_sz_lba,disc_info_sz_lba,d->header); - wbfs_close_disc(d); - return 0; + p->write_hdsector(p->callback_data,p->part_lba+1+d->i*disc_info_sz_lba,disc_info_sz_lba,d->header); + wbfs_close_disc(d); + return 0; } -u32 wbfs_rID_disc(wbfs_t*p, u8* discid, u8* newID) { - wbfs_disc_t *d = wbfs_open_disc(p,discid); - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; +u32 wbfs_rID_disc(wbfs_t*p, u8* discid, u8* newID) +{ + wbfs_disc_t *d = wbfs_open_disc(p,discid); + int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - if (!d) - return 1; + if(!d) + return 1; - memset(d->header->disc_header_copy, 0, 0x10); - strncpy((char *) d->header->disc_header_copy, (char *) newID, 0x9); + memset(d->header->disc_header_copy, 0, 0x10); + strncpy((char *) d->header->disc_header_copy, (char *) newID, 0x9); - p->write_hdsector(p->callback_data,p->part_lba+1+d->i*disc_info_sz_lba,disc_info_sz_lba,d->header); - wbfs_close_disc(d); - return 0; + p->write_hdsector(p->callback_data,p->part_lba+1+d->i*disc_info_sz_lba,disc_info_sz_lba,d->header); + wbfs_close_disc(d); + return 0; } // trim the file-system to its minimum size -u32 wbfs_trim(wbfs_t*p) { - u32 maxbl; - load_freeblocks(p); - maxbl = alloc_block(p); - p->n_hd_sec = maxbl<<(p->wbfs_sec_sz_s-p->hd_sec_sz_s); - p->head->n_hd_sec = wbfs_htonl(p->n_hd_sec); - // make all block full - memset(p->freeblks,0,p->n_wbfs_sec/8); - wbfs_sync(p); - // os layer will truncate the file. - return maxbl; +u32 wbfs_trim(wbfs_t*p) +{ + u32 maxbl; + load_freeblocks(p); + maxbl = alloc_block(p); + p->n_hd_sec = maxbl<<(p->wbfs_sec_sz_s-p->hd_sec_sz_s); + p->head->n_hd_sec = wbfs_htonl(p->n_hd_sec); + // make all block full + memset(p->freeblks,0,p->n_wbfs_sec/8); + wbfs_sync(p); + // os layer will truncate the file. + return maxbl; } // data extraction -u32 wbfs_extract_disc(wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector,void *callback_data,progress_callback_t spinner) { - wbfs_t *p = d->p; - u8* copy_buffer = 0; - int i; - int src_wbs_nlb=p->wbfs_sec_sz/p->hd_sec_sz; - int dst_wbs_nlb=p->wbfs_sec_sz/p->wii_sec_sz; - copy_buffer = wbfs_ioalloc(p->wbfs_sec_sz); - if (!copy_buffer) - ERROR("alloc memory"); +u32 wbfs_extract_disc(wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector,void *callback_data,progress_callback_t spinner) +{ + wbfs_t *p = d->p; + u8* copy_buffer = 0; + int i; + int src_wbs_nlb=p->wbfs_sec_sz/p->hd_sec_sz; + int dst_wbs_nlb=p->wbfs_sec_sz/p->wii_sec_sz; + copy_buffer = wbfs_ioalloc(p->wbfs_sec_sz); + if(!copy_buffer) + ERROR("alloc memory"); - for ( i=0; i< p->n_wbfs_sec_per_disc; i++) { - u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); - if (iwlba) { - - if (spinner) - spinner(i,p->n_wbfs_sec_per_disc); - p->read_hdsector(p->callback_data, p->part_lba + iwlba*src_wbs_nlb, src_wbs_nlb, copy_buffer); - write_dst_wii_sector(callback_data, i*dst_wbs_nlb, dst_wbs_nlb, copy_buffer); + for( i=0; i< p->n_wbfs_sec_per_disc; i++) + { + u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); + if (iwlba) + { + + if(spinner) + spinner(i,p->n_wbfs_sec_per_disc); + p->read_hdsector(p->callback_data, p->part_lba + iwlba*src_wbs_nlb, src_wbs_nlb, copy_buffer); + write_dst_wii_sector(callback_data, i*dst_wbs_nlb, dst_wbs_nlb, copy_buffer); + } } - } - wbfs_iofree(copy_buffer); - return 0; + wbfs_iofree(copy_buffer); + return 0; error: - return 1; + return 1; } float wbfs_estimate_disc ( - wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, - void *callback_data, - partition_selector_t sel) { - u8 *b; - int i; - u32 tot; - u32 wii_sec_per_wbfs_sect = 1 << (p->wbfs_sec_sz_s-p->wii_sec_sz_s); - wiidisc_t *d = 0; - u8 *used = 0; - wbfs_disc_info_t *info = 0; + wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, + void *callback_data, + partition_selector_t sel) +{ + u8 *b; + int i; + u32 tot; + u32 wii_sec_per_wbfs_sect = 1 << (p->wbfs_sec_sz_s-p->wii_sec_sz_s); + wiidisc_t *d = 0; + u8 *used = 0; + wbfs_disc_info_t *info = 0; - tot = 0; + tot = 0; - used = wbfs_malloc(p->n_wii_sec_per_disc); - if (!used) { - ERROR("unable to alloc memory"); - } + used = wbfs_malloc(p->n_wii_sec_per_disc); + if (!used) + { + ERROR("unable to alloc memory"); + } - d = wd_open_disc(read_src_wii_disc, callback_data); - if (!d) { - ERROR("unable to open wii disc"); - } + d = wd_open_disc(read_src_wii_disc, callback_data); + if (!d) + { + ERROR("unable to open wii disc"); + } - wd_build_disc_usage(d,sel,used); - wd_close_disc(d); - d = 0; + wd_build_disc_usage(d,sel,used); + wd_close_disc(d); + d = 0; - info = wbfs_ioalloc(p->disc_info_sz); - b = (u8 *)info; - read_src_wii_disc(callback_data, 0, 0x100, info->disc_header_copy); + info = wbfs_ioalloc(p->disc_info_sz); + b = (u8 *)info; + read_src_wii_disc(callback_data, 0, 0x100, info->disc_header_copy); - //fprintf(stderr, "estimating %c%c%c%c%c%c %s...\n",b[0], b[1], b[2], b[3], b[4], b[5], b + 0x20); + //fprintf(stderr, "estimating %c%c%c%c%c%c %s...\n",b[0], b[1], b[2], b[3], b[4], b[5], b + 0x20); - for (i = 0; i < p->n_wbfs_sec_per_disc; i++) { - if (block_used(used, i, wii_sec_per_wbfs_sect)) { - tot++; - } - } - //memcpy(header, b,0x100); + for (i = 0; i < p->n_wbfs_sec_per_disc; i++) + { + if (block_used(used, i, wii_sec_per_wbfs_sect)) + { + tot++; + } + } + //memcpy(header, b,0x100); error: - if (d) - wd_close_disc(d); + if (d) + wd_close_disc(d); - if (used) - wbfs_free(used); + if (used) + wbfs_free(used); - if (info) - wbfs_iofree(info); + if (info) + wbfs_iofree(info); - return tot * (((p->wbfs_sec_sz*1.0) / p->hd_sec_sz) * 512); + return tot * (((p->wbfs_sec_sz*1.0) / p->hd_sec_sz) * 512); } u32 wbfs_size_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, - void *callback_data,partition_selector_t sel, - u32 *comp_size, u32 *real_size) { - int i; - u32 tot = 0, last = 0; - u32 wii_sec_per_wbfs_sect = 1<<(p->wbfs_sec_sz_s-p->wii_sec_sz_s); - wiidisc_t *d = 0; - u8 *used = 0; - used = wbfs_malloc(p->n_wii_sec_per_disc); - if (!used) - ERROR("unable to alloc memory"); - d = wd_open_disc(read_src_wii_disc,callback_data); - if (!d) - ERROR("unable to open wii disc"); - wd_build_disc_usage(d,sel,used); - wd_close_disc(d); - d = 0; + void *callback_data,partition_selector_t sel, + u32 *comp_size, u32 *real_size) +{ + int i; + u32 tot = 0, last = 0; + u32 wii_sec_per_wbfs_sect = 1<<(p->wbfs_sec_sz_s-p->wii_sec_sz_s); + wiidisc_t *d = 0; + u8 *used = 0; + used = wbfs_malloc(p->n_wii_sec_per_disc); + if(!used) + ERROR("unable to alloc memory"); + d = wd_open_disc(read_src_wii_disc,callback_data); + if(!d) + ERROR("unable to open wii disc"); + wd_build_disc_usage(d,sel,used); + wd_close_disc(d); + d = 0; - // count total number to write for spinner - for (i=0; in_wbfs_sec_per_disc;i++) { - if (block_used(used,i,wii_sec_per_wbfs_sect)) { - tot += wii_sec_per_wbfs_sect; - last = i * wii_sec_per_wbfs_sect; - } - } + // count total number to write for spinner + for(i=0; in_wbfs_sec_per_disc;i++) { + if(block_used(used,i,wii_sec_per_wbfs_sect)) { + tot += wii_sec_per_wbfs_sect; + last = i * wii_sec_per_wbfs_sect; + } + } error: - if (d) - wd_close_disc(d); - if (used) - wbfs_free(used); + if(d) + wd_close_disc(d); + if(used) + wbfs_free(used); - *comp_size = tot; - *real_size = last; - - return 0; + *comp_size = tot; + *real_size = last; + + return 0; } // offset is pointing 32bit words to address the whole dvd, although len is in bytes @@ -714,53 +762,58 @@ error: //int (*read_wiidisc_callback_t)(void*fp,u32 offset,u32 count,void*iobuf); // connect wiidisc to wbfs_disc -int read_wiidisc_wbfsdisc(void*fp,u32 offset,u32 count,void*iobuf) { - return wbfs_disc_read((wbfs_disc_t*)fp, offset, count, iobuf); +int read_wiidisc_wbfsdisc(void*fp,u32 offset,u32 count,void*iobuf) +{ + return wbfs_disc_read((wbfs_disc_t*)fp, offset, count, iobuf); } -int wbfs_extract_file(wbfs_disc_t*d, char *path, void **data) { - wiidisc_t *wd = 0; - int ret = 0; +int wbfs_extract_file(wbfs_disc_t*d, char *path, void **data) +{ + wiidisc_t *wd = 0; + int ret = 0; - wd = wd_open_disc(read_wiidisc_wbfsdisc, d); - if (!wd) { - ERROR("opening wbfs disc"); - return -1; - } - wd->extracted_size = 0; - *data = wd_extract_file(wd, ONLY_GAME_PARTITION, path); - ret = wd->extracted_size; - if (!*data) { - //ERROR("file not found"); - ret = -1; - } - wd_close_disc(wd); -error: - return ret; -} - -int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data) { - if (!d) return -1; - wbfs_t *p = d->p; - int src_wbs_nlb = p->wbfs_sec_sz / p->hd_sec_sz; - int i, ret, last = 0; - for ( i=0; i< p->n_wbfs_sec_per_disc; i++) { - u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); - if (iwlba) { - ret = append_fragment(callback_data, - i * src_wbs_nlb, // offset - p->part_lba + iwlba * src_wbs_nlb, // sector - src_wbs_nlb); // count - if (ret) return ret; // error - last = i; + wd = wd_open_disc(read_wiidisc_wbfsdisc, d); + if (!wd) { + ERROR("opening wbfs disc"); + return -1; } - } - if (last < p->n_wbfs_sec_per_disc / 2) { - last = p->n_wbfs_sec_per_disc / 2; - } - u32 size = last * src_wbs_nlb; - append_fragment(callback_data, size, 0, 0); // set size - return 0; + wd->extracted_size = 0; + *data = wd_extract_file(wd, ONLY_GAME_PARTITION, path); + ret = wd->extracted_size; + if (!*data) { + //ERROR("file not found"); + ret = -1; + } + wd_close_disc(wd); +error: + return ret; +} + +int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data) +{ + if (!d) return -1; + wbfs_t *p = d->p; + int src_wbs_nlb = p->wbfs_sec_sz / p->hd_sec_sz; + int i, ret, last = 0; + for( i=0; i< p->n_wbfs_sec_per_disc; i++) + { + u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); + if (iwlba) + { + ret = append_fragment(callback_data, + i * src_wbs_nlb, // offset + p->part_lba + iwlba * src_wbs_nlb, // sector + src_wbs_nlb); // count + if (ret) return ret; // error + last = i; + } + } + if (last < p->n_wbfs_sec_per_disc / 2) { + last = p->n_wbfs_sec_per_disc / 2; + } + u32 size = last * src_wbs_nlb; + append_fragment(callback_data, size, 0, 0); // set size + return 0; } // wrapper for reading .iso files using wbfs apis @@ -769,36 +822,38 @@ int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *cal #include // offset is pointing 32bit words to address the whole dvd, although len is in bytes -int wbfs_iso_file_read(wbfs_disc_t*d,u32 offset, u8 *data, u32 len) { - if (!d || d->p != &wbfs_iso_file) return -1; - int fd = (int)d->header; - off_t off = ((u64)offset) << 2; - off_t ret_off; - int ret; - ret_off = lseek(fd, off, SEEK_SET); - if (ret_off != off) return -1; - ret = read(fd, data, len); - if (ret != len) return -2; - return 0; +int wbfs_iso_file_read(wbfs_disc_t*d,u32 offset, u8 *data, u32 len) +{ + if (!d || d->p != &wbfs_iso_file) return -1; + int fd = (int)d->header; + off_t off = ((u64)offset) << 2; + off_t ret_off; + int ret; + ret_off = lseek(fd, off, SEEK_SET); + if (ret_off != off) return -1; + ret = read(fd, data, len); + if (ret != len) return -2; + return 0; } -u32 wbfs_disc_sector_used(wbfs_disc_t *d, u32 *num_blk) { - if (d->p == &wbfs_iso_file) { - int fd = (int)d->header; - struct stat st; - if (fstat(fd, &st) == -1) return 0; - if (num_blk) { - *num_blk = (st.st_size >> 9); // in 512 units - } - return st.st_blocks; // in 512 units (can be sparse) - } - u32 last_blk = 0; - u32 ret; - ret = wbfs_sector_used2(d->p, d->header, &last_blk); - if (num_blk) { - *num_blk = last_blk + 1; - } - return ret; +u32 wbfs_disc_sector_used(wbfs_disc_t *d, u32 *num_blk) +{ + if (d->p == &wbfs_iso_file) { + int fd = (int)d->header; + struct stat st; + if (fstat(fd, &st) == -1) return 0; + if (num_blk) { + *num_blk = (st.st_size >> 9); // in 512 units + } + return st.st_blocks; // in 512 units (can be sparse) + } + u32 last_blk = 0; + u32 ret; + ret = wbfs_sector_used2(d->p, d->header, &last_blk); + if (num_blk) { + *num_blk = last_blk + 1; + } + return ret; } diff --git a/source/libwbfs/libwbfs.h b/source/libwbfs/libwbfs.h index 387cfe7a..9c8508f7 100644 --- a/source/libwbfs/libwbfs.h +++ b/source/libwbfs/libwbfs.h @@ -8,15 +8,16 @@ #include "wiidisc.h" #ifdef __cplusplus -extern "C" { + extern "C" { #endif /* __cplusplus */ - typedef u32 be32_t; - typedef u16 be16_t; +typedef u32 be32_t; +typedef u16 be16_t; - - typedef struct wbfs_head { + +typedef struct wbfs_head +{ be32_t magic; // parameters copied in the partition for easy dumping, and bug reports be32_t n_hd_sec; // total number of hd_sec in this partition @@ -24,12 +25,13 @@ extern "C" { u8 wbfs_sec_sz_s; // size of a wbfs sec u8 padding3[2]; u8 disc_table[0]; // size depends on hd sector size - }__attribute((packed)) wbfs_head_t ; +}__attribute((packed)) wbfs_head_t ; - typedef struct wbfs_disc_info { +typedef struct wbfs_disc_info +{ u8 disc_header_copy[0x100]; be16_t wlba_table[0]; - }wbfs_disc_info_t; +}wbfs_disc_info_t; // WBFS first wbfs_sector structure: // @@ -59,11 +61,12 @@ extern "C" { // // callback definition. Return 1 on fatal error (callback is supposed to make retries until no hopes..) - typedef int (*rw_sector_callback_t)(void*fp,u32 lba,u32 count,void*iobuf); - typedef void (*progress_callback_t)(int status,int total); +typedef int (*rw_sector_callback_t)(void*fp,u32 lba,u32 count,void*iobuf); +typedef void (*progress_callback_t)(int status,int total); - typedef struct wbfs_s { +typedef struct wbfs_s +{ wbfs_head_t *head; /* hdsectors, the size of the sector provided by the hosting hard drive */ @@ -72,14 +75,14 @@ extern "C" { u32 n_hd_sec; // the number of hd sector in the wbfs partition /* standard wii sector (0x8000 bytes) */ - u32 wii_sec_sz; + u32 wii_sec_sz; u8 wii_sec_sz_s; u32 n_wii_sec; u32 n_wii_sec_per_disc; - + /* The size of a wbfs sector */ u32 wbfs_sec_sz; - u32 wbfs_sec_sz_s; + u32 wbfs_sec_sz_s; u16 n_wbfs_sec; // this must fit in 16 bit! u16 n_wbfs_sec_per_disc; // size of the lookup table @@ -95,143 +98,144 @@ extern "C" { u16 disc_info_sz; u8 *tmp_buffer; // pre-allocated buffer for unaligned read - + u32 n_disc_open; + +}wbfs_t; - }wbfs_t; - - typedef struct wbfs_disc_s { +typedef struct wbfs_disc_s +{ wbfs_t *p; wbfs_disc_info_t *header; // pointer to wii header int i; // disc index in the wbfs header (disc_table) - }wbfs_disc_t; +}wbfs_disc_t; #define WBFS_MAGIC (('W'<<24)|('B'<<16)|('F'<<8)|('S')) - /*! @brief open a MSDOS partitionned harddrive. This tries to find a wbfs partition into the harddrive - @param read_hdsector,write_hdsector: accessors to a harddrive - @hd_sector_size: size of the hd sector. Can be set to zero if the partition in already initialized - @num_hd_sector: number of sectors in this disc. Can be set to zero if the partition in already initialized - @reset: not implemented, This will format the whole harddrive with one wbfs partition that fits the whole disk. - calls wbfs_error() to have textual meaning of errors - @return NULL in case of error - */ - wbfs_t*wbfs_open_hd(rw_sector_callback_t read_hdsector, - rw_sector_callback_t write_hdsector, - void *callback_data, - int hd_sector_size, int num_hd_sector, int reset); +/*! @brief open a MSDOS partitionned harddrive. This tries to find a wbfs partition into the harddrive + @param read_hdsector,write_hdsector: accessors to a harddrive + @hd_sector_size: size of the hd sector. Can be set to zero if the partition in already initialized + @num_hd_sector: number of sectors in this disc. Can be set to zero if the partition in already initialized + @reset: not implemented, This will format the whole harddrive with one wbfs partition that fits the whole disk. + calls wbfs_error() to have textual meaning of errors + @return NULL in case of error +*/ +wbfs_t*wbfs_open_hd(rw_sector_callback_t read_hdsector, + rw_sector_callback_t write_hdsector, + void *callback_data, + int hd_sector_size, int num_hd_sector, int reset); - /*! @brief open a wbfs partition - @param read_hdsector,write_hdsector: accessors to the partition - @hd_sector_size: size of the hd sector. Can be set to zero if the partition in already initialized - @num_hd_sector: number of sectors in this partition. Can be set to zero if the partition in already initialized - @partition_lba: The partitio offset if you provided accessors to the whole disc. - @reset: initialize the partition with an empty wbfs. - calls wbfs_error() to have textual meaning of errors - @return NULL in case of error - */ - wbfs_t*wbfs_open_partition(rw_sector_callback_t read_hdsector, - rw_sector_callback_t write_hdsector, - void *callback_data, - int hd_sector_size, int num_hd_sector, u32 partition_lba, int reset); +/*! @brief open a wbfs partition + @param read_hdsector,write_hdsector: accessors to the partition + @hd_sector_size: size of the hd sector. Can be set to zero if the partition in already initialized + @num_hd_sector: number of sectors in this partition. Can be set to zero if the partition in already initialized + @partition_lba: The partitio offset if you provided accessors to the whole disc. + @reset: initialize the partition with an empty wbfs. + calls wbfs_error() to have textual meaning of errors + @return NULL in case of error +*/ +wbfs_t*wbfs_open_partition(rw_sector_callback_t read_hdsector, + rw_sector_callback_t write_hdsector, + void *callback_data, + int hd_sector_size, int num_hd_sector, u32 partition_lba, int reset); - /*! @brief close a wbfs partition, and sync the metadatas to the disc */ - void wbfs_close(wbfs_t*); +/*! @brief close a wbfs partition, and sync the metadatas to the disc */ +void wbfs_close(wbfs_t*); - /*! @brief open a disc inside a wbfs partition use a 6 char discid+vendorid - @return NULL if discid is not present - */ - wbfs_disc_t *wbfs_open_disc(wbfs_t* p, u8 *diskid); +/*! @brief open a disc inside a wbfs partition use a 6 char discid+vendorid + @return NULL if discid is not present +*/ +wbfs_disc_t *wbfs_open_disc(wbfs_t* p, u8 *diskid); - /*! @brief close a already open disc inside a wbfs partition */ - void wbfs_close_disc(wbfs_disc_t*d); +/*! @brief close a already open disc inside a wbfs partition */ +void wbfs_close_disc(wbfs_disc_t*d); - u32 wbfs_sector_used(wbfs_t *p,wbfs_disc_info_t *di); - u32 wbfs_sector_used2(wbfs_t *p,wbfs_disc_info_t *di, u32 *last_blk); +u32 wbfs_sector_used(wbfs_t *p,wbfs_disc_info_t *di); +u32 wbfs_sector_used2(wbfs_t *p,wbfs_disc_info_t *di, u32 *last_blk); - /*! @brief accessor to the wii disc - @param d: a pointer to already open disc - @param offset: an offset inside the disc, *points 32bit words*, allowing to access 16GB data - @param len: The length of the data to fetch, in *bytes* - */ +/*! @brief accessor to the wii disc + @param d: a pointer to already open disc + @param offset: an offset inside the disc, *points 32bit words*, allowing to access 16GB data + @param len: The length of the data to fetch, in *bytes* + */ // offset is pointing 32bit words to address the whole dvd, although len is in bytes - int wbfs_disc_read(wbfs_disc_t*d,u32 offset, u32 len, u8 *data); +int wbfs_disc_read(wbfs_disc_t*d,u32 offset, u32 len, u8 *data); - /*! @return the number of discs inside the partition */ - u32 wbfs_count_discs(wbfs_t*p); - /*! get the disc info of ith disc inside the partition. It correspond to the first 0x100 bytes of the wiidvd - http://www.wiibrew.org/wiki/Wiidisc#Header - @param i: index of the disc inside the partition - @param header: pointer to 0x100 bytes to write the header - @size: optional pointer to a 32bit word that will get the size in 32bit words of the DVD taken on the partition. - */ - u32 wbfs_get_disc_info(wbfs_t*p, u32 i,u8 *header,int header_size,u32 *size); +/*! @return the number of discs inside the partition */ +u32 wbfs_count_discs(wbfs_t*p); +/*! get the disc info of ith disc inside the partition. It correspond to the first 0x100 bytes of the wiidvd + http://www.wiibrew.org/wiki/Wiidisc#Header + @param i: index of the disc inside the partition + @param header: pointer to 0x100 bytes to write the header + @size: optional pointer to a 32bit word that will get the size in 32bit words of the DVD taken on the partition. +*/ +u32 wbfs_get_disc_info(wbfs_t*p, u32 i,u8 *header,int header_size,u32 *size); - /*! get the number of used block of the partition. - to be multiplied by p->wbfs_sec_sz (use 64bit multiplication) to have the number in bytes - */ - u32 wbfs_count_usedblocks(wbfs_t*p); +/*! get the number of used block of the partition. + to be multiplied by p->wbfs_sec_sz (use 64bit multiplication) to have the number in bytes +*/ +u32 wbfs_count_usedblocks(wbfs_t*p); - /******************* write access ******************/ +/******************* write access ******************/ - /*! add a wii dvd inside the partition - @param read_src_wii_disc: a callback to access the wii dvd. offsets are in 32bit, len in bytes! - @callback_data: private data passed to the callback - @spinner: a pointer to a function that is regulary called to update a progress bar. - @sel: selects which partitions to copy. - @copy_1_1: makes a 1:1 copy, whenever a game would not use the wii disc format, and some data is hidden outside the filesystem. - */ - u32 wbfs_add_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, void *callback_data, - progress_callback_t spinner,partition_selector_t sel,int copy_1_1); +/*! add a wii dvd inside the partition + @param read_src_wii_disc: a callback to access the wii dvd. offsets are in 32bit, len in bytes! + @callback_data: private data passed to the callback + @spinner: a pointer to a function that is regulary called to update a progress bar. + @sel: selects which partitions to copy. + @copy_1_1: makes a 1:1 copy, whenever a game would not use the wii disc format, and some data is hidden outside the filesystem. + */ +u32 wbfs_add_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, void *callback_data, + progress_callback_t spinner,partition_selector_t sel,int copy_1_1); - /*! remove a wiidvd inside a partition */ - u32 wbfs_rm_disc(wbfs_t*p, u8* discid); +/*! remove a wiidvd inside a partition */ +u32 wbfs_rm_disc(wbfs_t*p, u8* discid); - /*! rename a game */ - u32 wbfs_ren_disc(wbfs_t*p, u8* discid, u8* newname); +/*! rename a game */ +u32 wbfs_ren_disc(wbfs_t*p, u8* discid, u8* newname); - /* change ID of a game*/ - u32 wbfs_rID_disc(wbfs_t*p, u8* discid, u8* newID); - /*! trim the file-system to its minimum size - This allows to use wbfs as a wiidisc container - */ - u32 wbfs_trim(wbfs_t*p); +/* change ID of a game*/ +u32 wbfs_rID_disc(wbfs_t*p, u8* discid, u8* newID); +/*! trim the file-system to its minimum size + This allows to use wbfs as a wiidisc container + */ +u32 wbfs_trim(wbfs_t*p); - /*! extract a disc from the wbfs, unused sectors are just untouched, allowing descent filesystem to only really usefull space to store the disc. - Even if the filesize is 4.7GB, the disc usage will be less. - */ - u32 wbfs_extract_disc(wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector,void *callback_data,progress_callback_t spinner); +/*! extract a disc from the wbfs, unused sectors are just untouched, allowing descent filesystem to only really usefull space to store the disc. +Even if the filesize is 4.7GB, the disc usage will be less. + */ +u32 wbfs_extract_disc(wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector,void *callback_data,progress_callback_t spinner); - /*! extract a file from the wii disc filesystem. - E.G. Allows to extract the opening.bnr to install a game as a system menu channel - */ - int wbfs_extract_file(wbfs_disc_t*d, char *path, void **data); +/*! extract a file from the wii disc filesystem. + E.G. Allows to extract the opening.bnr to install a game as a system menu channel + */ +int wbfs_extract_file(wbfs_disc_t*d, char *path, void **data); // remove some sanity checks - void wbfs_set_force_mode(int force); +void wbfs_set_force_mode(int force); - float wbfs_estimate_disc( - wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, - void *callback_data, - partition_selector_t sel); +float wbfs_estimate_disc( + wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, + void *callback_data, + partition_selector_t sel); // compressed and real size - u32 wbfs_size_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, - void *callback_data,partition_selector_t sel, - u32 *comp_size, u32 *real_size); +u32 wbfs_size_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, + void *callback_data,partition_selector_t sel, + u32 *comp_size, u32 *real_size); - typedef int (*_frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); - int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data); +typedef int (*_frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); +int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data); - extern wbfs_t wbfs_iso_file; - u32 wbfs_disc_sector_used(wbfs_disc_t *d, u32 *num_blk); - int wbfs_iso_file_read(wbfs_disc_t*d,u32 offset, u8 *data, u32 len); +extern wbfs_t wbfs_iso_file; +u32 wbfs_disc_sector_used(wbfs_disc_t *d, u32 *num_blk); +int wbfs_iso_file_read(wbfs_disc_t*d,u32 offset, u8 *data, u32 len); #ifdef __cplusplus -} + } #endif /* __cplusplus */ #endif diff --git a/source/libwbfs/rijndael.c b/source/libwbfs/rijndael.c index caeab48a..baf8c871 100644 --- a/source/libwbfs/rijndael.c +++ b/source/libwbfs/rijndael.c @@ -3,9 +3,9 @@ Written by Mike Scott 21st April 1999 mike@compapp.dcu.ie - Permission for free direct or derivative use is granted subject - to compliance with any conditions that the originators of the - algorithm place on its exploitation. + Permission for free direct or derivative use is granted subject + to compliance with any conditions that the originators of the + algorithm place on its exploitation. */ @@ -44,18 +44,21 @@ u8 fi[24],ri[24]; u32 fkey[120]; u32 rkey[120]; -static u32 pack(u8 *b) { /* pack bytes into a 32-bit Word */ +static u32 pack(u8 *b) +{ /* pack bytes into a 32-bit Word */ return ((u32)b[3]<<24)|((u32)b[2]<<16)|((u32)b[1]<<8)|(u32)b[0]; } -static void unpack(u32 a,u8 *b) { /* unpack bytes from a word */ +static void unpack(u32 a,u8 *b) +{ /* unpack bytes from a word */ b[0]=(u8)a; b[1]=(u8)(a>>8); b[2]=(u8)(a>>16); b[3]=(u8)(a>>24); } -static u8 xtime(u8 a) { +static u8 xtime(u8 a) +{ u8 b; if (a&0x80) b=0x1B; else b=0; @@ -64,29 +67,33 @@ static u8 xtime(u8 a) { return a; } -static u8 bmul(u8 x,u8 y) { /* x.y= AntiLog(Log(x) + Log(y)) */ +static u8 bmul(u8 x,u8 y) +{ /* x.y= AntiLog(Log(x) + Log(y)) */ if (x && y) return ptab[(ltab[x]+ltab[y])%255]; else return 0; } -static u32 SubByte(u32 a) { +static u32 SubByte(u32 a) +{ u8 b[4]; unpack(a,b); b[0]=fbsub[b[0]]; b[1]=fbsub[b[1]]; b[2]=fbsub[b[2]]; b[3]=fbsub[b[3]]; - return pack(b); + return pack(b); } -static u8 product(u32 x,u32 y) { /* dot product of two 4-byte arrays */ +static u8 product(u32 x,u32 y) +{ /* dot product of two 4-byte arrays */ u8 xb[4],yb[4]; unpack(x,xb); - unpack(y,yb); + unpack(y,yb); return bmul(xb[0],yb[0])^bmul(xb[1],yb[1])^bmul(xb[2],yb[2])^bmul(xb[3],yb[3]); } -static u32 InvMixCol(u32 x) { /* matrix Multiplication */ +static u32 InvMixCol(u32 x) +{ /* matrix Multiplication */ u32 y,m; u8 b[4]; @@ -102,96 +109,86 @@ static u32 InvMixCol(u32 x) { /* matrix Multiplication */ return y; } -u8 ByteSub(u8 x) { +u8 ByteSub(u8 x) +{ u8 y=ptab[255-ltab[x]]; /* multiplicative inverse */ - x=y; - x=ROTL(x); - y^=x; - x=ROTL(x); - y^=x; - x=ROTL(x); - y^=x; - x=ROTL(x); - y^=x; - y^=0x63; + x=y; x=ROTL(x); + y^=x; x=ROTL(x); + y^=x; x=ROTL(x); + y^=x; x=ROTL(x); + y^=x; y^=0x63; return y; } -void gentables(void) { /* generate tables */ +void gentables(void) +{ /* generate tables */ int i; u8 y,b[4]; - /* use 3 as primitive root to generate power and log tables */ + /* use 3 as primitive root to generate power and log tables */ ltab[0]=0; - ptab[0]=1; - ltab[1]=0; - ptab[1]=3; - ltab[3]=1; - for (i=2;i<256;i++) { + ptab[0]=1; ltab[1]=0; + ptab[1]=3; ltab[3]=1; + for (i=2;i<256;i++) + { ptab[i]=ptab[i-1]^xtime(ptab[i-1]); ltab[ptab[i]]=i; } - - /* affine transformation:- each bit is xored with itself shifted one bit */ + + /* affine transformation:- each bit is xored with itself shifted one bit */ fbsub[0]=0x63; rbsub[0x63]=0; - for (i=1;i<256;i++) { + for (i=1;i<256;i++) + { y=ByteSub((u8)i); - fbsub[i]=y; - rbsub[y]=i; + fbsub[i]=y; rbsub[y]=i; } - for (i=0,y=1;i<30;i++) { + for (i=0,y=1;i<30;i++) + { rco[i]=y; y=xtime(y); } - /* calculate forward and reverse tables */ - for (i=0;i<256;i++) { + /* calculate forward and reverse tables */ + for (i=0;i<256;i++) + { y=fbsub[i]; - b[3]=y^xtime(y); - b[2]=y; - b[1]=y; - b[0]=xtime(y); + b[3]=y^xtime(y); b[2]=y; + b[1]=y; b[0]=xtime(y); ftable[i]=pack(b); y=rbsub[i]; - b[3]=bmul(InCo[0],y); - b[2]=bmul(InCo[1],y); - b[1]=bmul(InCo[2],y); - b[0]=bmul(InCo[3],y); + b[3]=bmul(InCo[0],y); b[2]=bmul(InCo[1],y); + b[1]=bmul(InCo[2],y); b[0]=bmul(InCo[3],y); rtable[i]=pack(b); } } -void gkey(int nb,int nk,char *key) { /* blocksize=32*nb bits. Key=32*nk bits */ - /* currently nb,bk = 4, 6 or 8 */ - /* key comes as 4*Nk bytes */ - /* Key Scheduler. Create expanded encryption key */ +void gkey(int nb,int nk,char *key) +{ /* blocksize=32*nb bits. Key=32*nk bits */ + /* currently nb,bk = 4, 6 or 8 */ + /* key comes as 4*Nk bytes */ + /* Key Scheduler. Create expanded encryption key */ int i,j,k,m,N; int C1,C2,C3; u32 CipherKey[8]; + + Nb=nb; Nk=nk; - Nb=nb; - Nk=nk; - - /* Nr is number of rounds */ + /* Nr is number of rounds */ if (Nb>=Nk) Nr=6+Nb; else Nr=6+Nk; C1=1; - if (Nb<8) { - C2=2; - C3=3; - } else { - C2=3; - C3=4; - } + if (Nb<8) { C2=2; C3=3; } + else { C2=3; C3=4; } - /* pre-calculate forward and reverse increments */ - for (m=j=0;j>8)])^ ROTL16(ftable[(u8)(x[fi[m+1]]>>16)])^ ROTL24(ftable[x[fi[m+2]]>>24]); } - t=x; - x=y; - y=t; /* swap pointers */ + t=x; x=y; y=t; /* swap pointers */ } - /* Last Round - unroll if possible */ - for (m=j=0;j>8)])^ ROTL16((u32)fbsub[(u8)(x[fi[m+1]]>>16)])^ ROTL24((u32)fbsub[x[fi[m+2]]>>24]); - } - for (i=j=0;i>8)])^ ROTL16(rtable[(u8)(x[ri[m+1]]>>16)])^ ROTL24(rtable[x[ri[m+2]]>>24]); } - t=x; - x=y; - y=t; /* swap pointers */ + t=x; x=y; y=t; /* swap pointers */ } - /* Last Round - unroll if possible */ - for (m=j=0;j>8)])^ ROTL16((u32)rbsub[(u8)(x[ri[m+1]]>>16)])^ ROTL24((u32)rbsub[x[ri[m+2]]>>24]); - } - for (i=j=0;iread(d->fp,offset,len,data); - if (ret) - wbfs_fatal("error reading disc"); - } - if (d->sector_usage_table) { - u32 blockno = offset>>13; - do { - d->sector_usage_table[blockno]=1; - blockno+=1; - if (len>0x8000) - len-=0x8000; - } while (len>0x8000); - } -} - -static void partition_raw_read(wiidisc_t *d,u32 offset, u8 *data, u32 len) { - disc_read(d, d->partition_raw_offset + offset, data, len); -} - -static void partition_read_block(wiidisc_t *d,u32 blockno, u8 *block) { - u8*raw = d->tmp_buffer; - u8 iv[16]; - u32 offset; - if (d->sector_usage_table) - d->sector_usage_table[d->partition_block+blockno]=1; - offset = d->partition_data_offset + ((0x8000>>2) * blockno); - partition_raw_read(d,offset, raw, 0x8000); - - // decrypt data - memcpy(iv, raw + 0x3d0, 16); - aes_set_key(d->disc_key); - aes_decrypt(iv, raw + 0x400,block,0x7c00); -} - -static void partition_read(wiidisc_t *d,u32 offset, u8 *data, u32 len,int fake) { - u8 *block = d->tmp_buffer2; - u32 offset_in_block; - u32 len_in_block; - if (fake && d->sector_usage_table==0) - return; - - while (len) { - offset_in_block = offset % (0x7c00>>2); - len_in_block = 0x7c00 - (offset_in_block<<2); - if (len_in_block > len) - len_in_block = len; - if (!fake) { - partition_read_block(d,offset / (0x7c00>>2), block); - wbfs_memcpy(data, block + (offset_in_block<<2), len_in_block); - } else - d->sector_usage_table[d->partition_block+(offset/(0x7c00>>2))]=1; - data += len_in_block; - offset += len_in_block>>2; - len -= len_in_block; - } -} - - -static u32 do_fst(wiidisc_t *d,u8 *fst, const char *names, u32 i) { - u32 offset; - u32 size; - const char *name; - u32 j; - - name = names + (_be32(fst + 12*i) & 0x00ffffff); - size = _be32(fst + 12*i + 8); - - if (i == 0) { - for (j = 1; j < size && !d->extracted_buffer; ) { - j = do_fst(d,fst, names, j); +static void disc_read(wiidisc_t *d,u32 offset, u8 *data, u32 len) +{ + if(data){ + int ret=0; + if(len==0) + return ; + ret = d->read(d->fp,offset,len,data); + if(ret) + wbfs_fatal("error reading disc"); + } + if(d->sector_usage_table) + { + u32 blockno = offset>>13; + do + { + d->sector_usage_table[blockno]=1; + blockno+=1; + if(len>0x8000) + len-=0x8000; + }while(len>0x8000); } - return size; - } - //printf("name %s\n",name); - - if (fst[12*i]) { - - for (j = i + 1; j < size && !d->extracted_buffer; ) - j = do_fst(d,fst, names, j); - - return size; - } else { - offset = _be32(fst + 12*i + 4); - if (d->extract_pathname && strcasecmp(name, d->extract_pathname)==0) { - d->extracted_buffer = wbfs_ioalloc(size); - d->extracted_size = size; - partition_read(d,offset, d->extracted_buffer, size,0); - } else - partition_read(d,offset, 0, size,1); - return i + 1; - } } -static void do_files(wiidisc_t*d) { - u8 *b = wbfs_ioalloc(0x480); // XXX: determine actual header size - u32 dol_offset; - u32 fst_offset; - u32 fst_size; - u32 apl_offset; - u32 apl_size; - u8 *apl_header = wbfs_ioalloc(0x20); - u8 *fst; - u32 n_files; - partition_read(d,0, b, 0x480,0); - - dol_offset = _be32(b + 0x0420); - fst_offset = _be32(b + 0x0424); - fst_size = _be32(b + 0x0428)<<2; - - apl_offset = 0x2440>>2; - partition_read(d,apl_offset, apl_header, 0x20,0); - apl_size = 0x20 + _be32(apl_header + 0x14) + _be32(apl_header + 0x18); - // fake read dol and partition - partition_read(d,apl_offset, 0, apl_size,1); - partition_read(d,dol_offset, 0, (fst_offset - dol_offset)<<2,1); - - - fst = wbfs_ioalloc(fst_size); - if (fst == 0) - wbfs_fatal("malloc fst"); - partition_read(d,fst_offset, fst, fst_size,0); - n_files = _be32(fst + 8); - - if (d->extract_pathname && *d->extract_pathname == 0) { - // if empty pathname requested return fst - d->extracted_buffer = fst; - d->extracted_size = fst_size; - d->extract_pathname = NULL; - // skip do_fst if only fst requested - n_files = 0; - } - - if (n_files > 1) - do_fst(d,fst, (char *)fst + 12*n_files, 0); - wbfs_iofree(b); - wbfs_iofree(apl_header); - if (fst != d->extracted_buffer) - wbfs_iofree(fst); +static void partition_raw_read(wiidisc_t *d,u32 offset, u8 *data, u32 len) +{ + disc_read(d, d->partition_raw_offset + offset, data, len); } -static void do_partition(wiidisc_t*d) { - u8 *tik = wbfs_ioalloc(0x2a4); - u8 *b = wbfs_ioalloc(0x1c); - u64 tmd_offset; - u32 tmd_size; - u8 *tmd; - u64 cert_offset; - u32 cert_size; - u8 *cert; - u64 h3_offset; +static void partition_read_block(wiidisc_t *d,u32 blockno, u8 *block) +{ + u8*raw = d->tmp_buffer; + u8 iv[16]; + u32 offset; + if(d->sector_usage_table) + d->sector_usage_table[d->partition_block+blockno]=1; + offset = d->partition_data_offset + ((0x8000>>2) * blockno); + partition_raw_read(d,offset, raw, 0x8000); - // read ticket, and read some offsets and sizes - partition_raw_read(d,0, tik, 0x2a4); - partition_raw_read(d,0x2a4>>2, b, 0x1c); - - tmd_size = _be32(b); - tmd_offset = _be32(b + 4); - cert_size = _be32(b + 8); - cert_offset = _be32(b + 0x0c); - h3_offset = _be32(b + 0x10); - d->partition_data_offset = _be32(b + 0x14); - d->partition_block = (d->partition_raw_offset+d->partition_data_offset)>>13; - tmd = wbfs_ioalloc(tmd_size); - if (tmd == 0) - wbfs_fatal("malloc tmd"); - partition_raw_read(d,tmd_offset, tmd, tmd_size); - - cert = wbfs_ioalloc(cert_size); - if (cert == 0) - wbfs_fatal("malloc cert"); - partition_raw_read(d,cert_offset, cert, cert_size); - - - _decrypt_title_key(tik, d->disc_key); - - partition_raw_read(d,h3_offset, 0, 0x18000); - wbfs_iofree(b); - wbfs_iofree(tik); - wbfs_iofree(cert); - wbfs_iofree(tmd); - - do_files(d); - -} -static int test_parition_skip(u32 partition_type,partition_selector_t part_sel) { - switch (part_sel) { - case ALL_PARTITIONS: - return 0; - case REMOVE_UPDATE_PARTITION: - return (partition_type==1); - case ONLY_GAME_PARTITION: - return (partition_type!=0); - default: - return (partition_type!=part_sel); - } -} -static void do_disc(wiidisc_t*d) { - u8 *b = wbfs_ioalloc(0x100); - u64 partition_offset[32]; // XXX: don't know the real maximum - u64 partition_type[32]; // XXX: don't know the real maximum - u32 n_partitions; - u32 magic; - u32 i; - disc_read(d,0, b, 0x100); - magic=_be32(b+24); - if (magic!=0x5D1C9EA3) { - wbfs_error("not a wii disc"); - return ; - } - disc_read(d,0x40000>>2, b, 0x100); - n_partitions = _be32(b); - disc_read(d,_be32(b + 4), b, 0x100); - for (i = 0; i < n_partitions; i++) { - partition_offset[i] = _be32(b + 8 * i); - partition_type[i] = _be32(b + 8 * i+4); - } - for (i = 0; i < n_partitions; i++) { - d->partition_raw_offset = partition_offset[i]; - if (!test_parition_skip(partition_type[i],d->part_sel)) - do_partition(d); - } - wbfs_iofree(b); + // decrypt data + memcpy(iv, raw + 0x3d0, 16); + aes_set_key(d->disc_key); + aes_decrypt(iv, raw + 0x400,block,0x7c00); } -wiidisc_t *wd_open_disc(read_wiidisc_callback_t read,void*fp) { - wiidisc_t *d = wbfs_malloc(sizeof(wiidisc_t)); - if (!d) - return 0; - wbfs_memset(d,0,sizeof(wiidisc_t)); - d->read = read; - d->fp = fp; - d->part_sel = ALL_PARTITIONS; - d->tmp_buffer = wbfs_ioalloc(0x8000); - d->tmp_buffer2 = wbfs_malloc(0x8000); +static void partition_read(wiidisc_t *d,u32 offset, u8 *data, u32 len,int fake) +{ + u8 *block = d->tmp_buffer2; + u32 offset_in_block; + u32 len_in_block; + if(fake && d->sector_usage_table==0) + return; - return d; + while(len) { + offset_in_block = offset % (0x7c00>>2); + len_in_block = 0x7c00 - (offset_in_block<<2); + if (len_in_block > len) + len_in_block = len; + if(!fake){ + partition_read_block(d,offset / (0x7c00>>2), block); + wbfs_memcpy(data, block + (offset_in_block<<2), len_in_block); + }else + d->sector_usage_table[d->partition_block+(offset/(0x7c00>>2))]=1; + data += len_in_block; + offset += len_in_block>>2; + len -= len_in_block; + } } -void wd_close_disc(wiidisc_t *d) { - wbfs_iofree(d->tmp_buffer); - wbfs_free(d->tmp_buffer2); - wbfs_free(d); + + +static u32 do_fst(wiidisc_t *d,u8 *fst, const char *names, u32 i) +{ + u32 offset; + u32 size; + const char *name; + u32 j; + + name = names + (_be32(fst + 12*i) & 0x00ffffff); + size = _be32(fst + 12*i + 8); + + if (i == 0) { + for (j = 1; j < size && !d->extracted_buffer; ){ + j = do_fst(d,fst, names, j); + } + return size; + } + //printf("name %s\n",name); + + if (fst[12*i]) { + + for (j = i + 1; j < size && !d->extracted_buffer; ) + j = do_fst(d,fst, names, j); + + return size; + } else { + offset = _be32(fst + 12*i + 4); + if(d->extract_pathname && strcasecmp(name, d->extract_pathname)==0) + { + d->extracted_buffer = wbfs_ioalloc(size); + d->extracted_size = size; + partition_read(d,offset, d->extracted_buffer, size,0); + }else + partition_read(d,offset, 0, size,1); + return i + 1; + } +} + +static void do_files(wiidisc_t*d) +{ + u8 *b = wbfs_ioalloc(0x480); // XXX: determine actual header size + u32 dol_offset; + u32 fst_offset; + u32 fst_size; + u32 apl_offset; + u32 apl_size; + u8 *apl_header = wbfs_ioalloc(0x20); + u8 *fst; + u32 n_files; + partition_read(d,0, b, 0x480,0); + + dol_offset = _be32(b + 0x0420); + fst_offset = _be32(b + 0x0424); + fst_size = _be32(b + 0x0428)<<2; + + apl_offset = 0x2440>>2; + partition_read(d,apl_offset, apl_header, 0x20,0); + apl_size = 0x20 + _be32(apl_header + 0x14) + _be32(apl_header + 0x18); + // fake read dol and partition + partition_read(d,apl_offset, 0, apl_size,1); + partition_read(d,dol_offset, 0, (fst_offset - dol_offset)<<2,1); + + + fst = wbfs_ioalloc(fst_size); + if (fst == 0) + wbfs_fatal("malloc fst"); + partition_read(d,fst_offset, fst, fst_size,0); + n_files = _be32(fst + 8); + + if (d->extract_pathname && *d->extract_pathname == 0) { + // if empty pathname requested return fst + d->extracted_buffer = fst; + d->extracted_size = fst_size; + d->extract_pathname = NULL; + // skip do_fst if only fst requested + n_files = 0; + } + + if (n_files > 1) + do_fst(d,fst, (char *)fst + 12*n_files, 0); + wbfs_iofree(b); + wbfs_iofree(apl_header); + if (fst != d->extracted_buffer) + wbfs_iofree(fst); +} + +static void do_partition(wiidisc_t*d) +{ + u8 *tik = wbfs_ioalloc(0x2a4); + u8 *b = wbfs_ioalloc(0x1c); + u64 tmd_offset; + u32 tmd_size; + u8 *tmd; + u64 cert_offset; + u32 cert_size; + u8 *cert; + u64 h3_offset; + + // read ticket, and read some offsets and sizes + partition_raw_read(d,0, tik, 0x2a4); + partition_raw_read(d,0x2a4>>2, b, 0x1c); + + tmd_size = _be32(b); + tmd_offset = _be32(b + 4); + cert_size = _be32(b + 8); + cert_offset = _be32(b + 0x0c); + h3_offset = _be32(b + 0x10); + d->partition_data_offset = _be32(b + 0x14); + d->partition_block = (d->partition_raw_offset+d->partition_data_offset)>>13; + tmd = wbfs_ioalloc(tmd_size); + if (tmd == 0) + wbfs_fatal("malloc tmd"); + partition_raw_read(d,tmd_offset, tmd, tmd_size); + + cert = wbfs_ioalloc(cert_size); + if (cert == 0) + wbfs_fatal("malloc cert"); + partition_raw_read(d,cert_offset, cert, cert_size); + + + _decrypt_title_key(tik, d->disc_key); + + partition_raw_read(d,h3_offset, 0, 0x18000); + wbfs_iofree(b); + wbfs_iofree(tik); + wbfs_iofree(cert); + wbfs_iofree(tmd); + + do_files(d); + +} +static int test_parition_skip(u32 partition_type,partition_selector_t part_sel) +{ + switch(part_sel) + { + case ALL_PARTITIONS: + return 0; + case REMOVE_UPDATE_PARTITION: + return (partition_type==1); + case ONLY_GAME_PARTITION: + return (partition_type!=0); + default: + return (partition_type!=part_sel); + } +} +static void do_disc(wiidisc_t*d) +{ + u8 *b = wbfs_ioalloc(0x100); + u64 partition_offset[32]; // XXX: don't know the real maximum + u64 partition_type[32]; // XXX: don't know the real maximum + u32 n_partitions; + u32 magic; + u32 i; + disc_read(d,0, b, 0x100); + magic=_be32(b+24); + if(magic!=0x5D1C9EA3){ + wbfs_error("not a wii disc"); + return ; + } + disc_read(d,0x40000>>2, b, 0x100); + n_partitions = _be32(b); + disc_read(d,_be32(b + 4), b, 0x100); + for (i = 0; i < n_partitions; i++){ + partition_offset[i] = _be32(b + 8 * i); + partition_type[i] = _be32(b + 8 * i+4); + } + for (i = 0; i < n_partitions; i++) { + d->partition_raw_offset = partition_offset[i]; + if(!test_parition_skip(partition_type[i],d->part_sel)) + do_partition(d); + } + wbfs_iofree(b); +} + +wiidisc_t *wd_open_disc(read_wiidisc_callback_t read,void*fp) +{ + wiidisc_t *d = wbfs_malloc(sizeof(wiidisc_t)); + if(!d) + return 0; + wbfs_memset(d,0,sizeof(wiidisc_t)); + d->read = read; + d->fp = fp; + d->part_sel = ALL_PARTITIONS; + d->tmp_buffer = wbfs_ioalloc(0x8000); + d->tmp_buffer2 = wbfs_malloc(0x8000); + + return d; +} +void wd_close_disc(wiidisc_t *d) +{ + wbfs_iofree(d->tmp_buffer); + wbfs_free(d->tmp_buffer2); + wbfs_free(d); } // returns a buffer allocated with wbfs_ioalloc() or NULL if not found of alloc error -// XXX pathname not implemented. files are extracted by their name. +// XXX pathname not implemented. files are extracted by their name. // first file found with that name is returned. -u8 * wd_extract_file(wiidisc_t *d, partition_selector_t partition_type, char *pathname) { - u8 *retval = 0; - d->extract_pathname = pathname; - d->extracted_buffer = 0; - d->part_sel = partition_type; - do_disc(d); - d->extract_pathname = 0; - d->part_sel = ALL_PARTITIONS; - retval = d->extracted_buffer; - d->extracted_buffer = 0; - return retval; +u8 * wd_extract_file(wiidisc_t *d, partition_selector_t partition_type, char *pathname) +{ + u8 *retval = 0; + d->extract_pathname = pathname; + d->extracted_buffer = 0; + d->part_sel = partition_type; + do_disc(d); + d->extract_pathname = 0; + d->part_sel = ALL_PARTITIONS; + retval = d->extracted_buffer; + d->extracted_buffer = 0; + return retval; } -void wd_build_disc_usage(wiidisc_t *d, partition_selector_t selector, u8* usage_table) { - d->sector_usage_table = usage_table; - wbfs_memset(usage_table,0,143432*2); - d->part_sel = selector; - do_disc(d); - d->part_sel = ALL_PARTITIONS; - d->sector_usage_table = 0; +void wd_build_disc_usage(wiidisc_t *d, partition_selector_t selector, u8* usage_table) +{ + d->sector_usage_table = usage_table; + wbfs_memset(usage_table,0,143432*2); + d->part_sel = selector; + do_disc(d); + d->part_sel = ALL_PARTITIONS; + d->sector_usage_table = 0; } -void wd_fix_partition_table(wiidisc_t *d, partition_selector_t selector, u8* partition_table) { - u8 *b = partition_table; - u32 partition_offset; - u32 partition_type; - u32 n_partitions,i,j; - u32 *b32; - if (selector == ALL_PARTITIONS) - return; - n_partitions = _be32(b); - if (_be32(b + 4)-(0x40000>>2) >0x50) - wbfs_fatal("cannot modify this partition table. Please report the bug."); - - b += (_be32(b + 4)-(0x40000>>2))*4; - j=0; - for (i = 0; i < n_partitions; i++) { - partition_offset = _be32(b + 8 * i); - partition_type = _be32(b + 8 * i+4); - if (!test_parition_skip(partition_type,selector)) { - b32 = (u32*)(b + 8 * j); - b32[0] = wbfs_htonl(partition_offset); - b32[1] = wbfs_htonl(partition_type); - j++; +void wd_fix_partition_table(wiidisc_t *d, partition_selector_t selector, u8* partition_table) +{ + u8 *b = partition_table; + u32 partition_offset; + u32 partition_type; + u32 n_partitions,i,j; + u32 *b32; + if(selector == ALL_PARTITIONS) + return; + n_partitions = _be32(b); + if(_be32(b + 4)-(0x40000>>2) >0x50) + wbfs_fatal("cannot modify this partition table. Please report the bug."); + + b += (_be32(b + 4)-(0x40000>>2))*4; + j=0; + for (i = 0; i < n_partitions; i++){ + partition_offset = _be32(b + 8 * i); + partition_type = _be32(b + 8 * i+4); + if(!test_parition_skip(partition_type,selector)) + { + b32 = (u32*)(b + 8 * j); + b32[0] = wbfs_htonl(partition_offset); + b32[1] = wbfs_htonl(partition_type); + j++; + } } - } - b32 = (u32*)(partition_table); - *b32 = wbfs_htonl(j); + b32 = (u32*)(partition_table); + *b32 = wbfs_htonl(j); } diff --git a/source/libwbfs/wiidisc.h b/source/libwbfs/wiidisc.h index 51fb0755..ba285208 100644 --- a/source/libwbfs/wiidisc.h +++ b/source/libwbfs/wiidisc.h @@ -4,47 +4,48 @@ #include "libwbfs_os.h" // this file is provided by the project wanting to compile libwbfs and wiidisc #ifdef __cplusplus -extern "C" { + extern "C" { #endif /* __cplusplus */ #if 0 //removes extra automatic indentation by editors -} + } #endif // callback definition. Return 1 on fatal error (callback is supposed to make retries until no hopes..) // offset points 32bit words, count counts bytes typedef int (*read_wiidisc_callback_t)(void*fp,u32 offset,u32 count,void*iobuf); -typedef enum { - UPDATE_PARTITION_TYPE=0, - GAME_PARTITION_TYPE, - OTHER_PARTITION_TYPE, - // value in between selects partition types of that value - ALL_PARTITIONS=0xffffffff-3, - REMOVE_UPDATE_PARTITION, // keeps game + channel installers - ONLY_GAME_PARTITION, +typedef enum{ + UPDATE_PARTITION_TYPE=0, + GAME_PARTITION_TYPE, + OTHER_PARTITION_TYPE, + // value in between selects partition types of that value + ALL_PARTITIONS=0xffffffff-3, + REMOVE_UPDATE_PARTITION, // keeps game + channel installers + ONLY_GAME_PARTITION, }partition_selector_t; -typedef struct wiidisc_s { - read_wiidisc_callback_t read; - void *fp; - u8 *sector_usage_table; +typedef struct wiidisc_s +{ + read_wiidisc_callback_t read; + void *fp; + u8 *sector_usage_table; - // everything points 32bit words. - u32 disc_raw_offset; - u32 partition_raw_offset; - u32 partition_data_offset; - u32 partition_data_size; - u32 partition_block; + // everything points 32bit words. + u32 disc_raw_offset; + u32 partition_raw_offset; + u32 partition_data_offset; + u32 partition_data_size; + u32 partition_block; + + u8 *tmp_buffer; + u8 *tmp_buffer2; + u8 disc_key[16]; + int dont_decrypt; - u8 *tmp_buffer; - u8 *tmp_buffer2; - u8 disc_key[16]; - int dont_decrypt; + partition_selector_t part_sel; - partition_selector_t part_sel; - - char *extract_pathname; - u8 *extracted_buffer; - int extracted_size; + char *extract_pathname; + u8 *extracted_buffer; + int extracted_size; }wiidisc_t; wiidisc_t *wd_open_disc(read_wiidisc_callback_t read,void*fp); @@ -61,7 +62,7 @@ void wd_fix_partition_table(wiidisc_t *d, partition_selector_t selector, u8* par { #endif #ifdef __cplusplus -} + } #endif /* __cplusplus */ #endif diff --git a/source/libwiigui/gui.h b/source/libwiigui/gui.h index 24ce47a4..83b62db9 100644 --- a/source/libwiigui/gui.h +++ b/source/libwiigui/gui.h @@ -56,47 +56,51 @@ extern FreeTypeGX *fontSystem; typedef void (*UpdateCallback)(void * e); -enum { - ALIGN_LEFT, - ALIGN_RIGHT, - ALIGN_CENTRE, - ALIGN_TOP, - ALIGN_BOTTOM, - ALIGN_MIDDLE +enum +{ + ALIGN_LEFT, + ALIGN_RIGHT, + ALIGN_CENTRE, + ALIGN_TOP, + ALIGN_BOTTOM, + ALIGN_MIDDLE }; #define ALIGN_CENTER ALIGN_CENTRE -enum { - STATE_DEFAULT, - STATE_SELECTED, - STATE_CLICKED, - STATE_HELD, - STATE_DISABLED +enum +{ + STATE_DEFAULT, + STATE_SELECTED, + STATE_CLICKED, + STATE_HELD, + STATE_DISABLED }; -enum { - IMAGE_TEXTURE, - IMAGE_COLOR, - IMAGE_DATA, - IMAGE_COPY +enum +{ + IMAGE_TEXTURE, + IMAGE_COLOR, + IMAGE_DATA, + IMAGE_COPY }; -enum { - TRIGGER_SIMPLE, - TRIGGER_HELD, - TRIGGER_BUTTON_ONLY, - TRIGGER_BUTTON_ONLY_IN_FOCUS +enum +{ + TRIGGER_SIMPLE, + TRIGGER_HELD, + TRIGGER_BUTTON_ONLY, + TRIGGER_BUTTON_ONLY_IN_FOCUS }; typedef struct _paddata { - u16 btns_d; - u16 btns_u; - u16 btns_h; - s8 stickX; - s8 stickY; - s8 substickX; - s8 substickY; - u8 triggerL; - u8 triggerR; + u16 btns_d; + u16 btns_u; + u16 btns_h; + s8 stickX; + s8 stickY; + s8 substickX; + s8 substickY; + u8 triggerL; + u8 triggerR; } PADData; #define EFFECT_SLIDE_TOP 1 @@ -115,1036 +119,1050 @@ typedef struct _paddata { #define MAX_SND_VOICES 16 class GuiSoundDecoder; -class GuiSound { -public: - //!Constructor - //!\param s Pointer to the sound data - //!\param l Length of sound data - //!\param v Sound volume (0-100) - //!\param r RAW PCM Sound, when no decoder is found then try to play as raw-pcm - //!\param a true--> Pointer to the sound data is allocated with new u8[...] - //!\ GuiSound will be destroy the buffer if it no more needed - //!\ false-> sound data buffer has to live just as long as GuiSound - GuiSound(const u8 *s, int l, int v=100, bool r=true, bool a=false); - //!Constructor - //!\param p Path to the sound data - //!\param v Sound volume (0-100) - GuiSound(const char *p, int v=100); - //!Load - stop playing and load the new sound data - //! if load not failed replace the current with new sound data - //! otherwise the current date will not changed - //!\params same as by Constructors - //!\return true ok / false = failed - bool Load(const u8 *s, int l, bool r=false, bool a=false); - bool Load(const char *p); - //!Destructor - ~GuiSound(); +class GuiSound +{ + public: + //!Constructor + //!\param s Pointer to the sound data + //!\param l Length of sound data + //!\param v Sound volume (0-100) + //!\param r RAW PCM Sound, when no decoder is found then try to play as raw-pcm + //!\param a true--> Pointer to the sound data is allocated with new u8[...] + //!\ GuiSound will be destroy the buffer if it no more needed + //!\ false-> sound data buffer has to live just as long as GuiSound + GuiSound(const u8 *s, int l, int v=100, bool r=true, bool a=false); + //!Constructor + //!\param p Path to the sound data + //!\param v Sound volume (0-100) + GuiSound(const char *p, int v=100); + //!Load - stop playing and load the new sound data + //! if load not failed replace the current with new sound data + //! otherwise the current date will not changed + //!\params same as by Constructors + //!\return true ok / false = failed + bool Load(const u8 *s, int l, bool r=false, bool a=false); + bool Load(const char *p); + //!Destructor + ~GuiSound(); + + //!Start sound playback + void Play(); + //!Stop sound playback + void Stop(); + //!Pause sound playback + void Pause(); + //!Resume sound playback + void Resume(); + //!Checks if the sound is currently playing + //!\return true if sound is playing, false otherwise + bool IsPlaying(); + //!Set sound volume + //!\param v Sound volume (0-100) + void SetVolume(int v); + //!Set the sound to loop playback (only applies to OGG) + //!\param l Loop (true to loop) + void SetLoop(bool l); + //!Get the playing time in ms for that moment (only applies to OGG) + protected: + s32 voice; // used asnd-voice + u8 *play_buffer[3]; // trpple-playbuffer + int buffer_nr; // current playbuffer + int buffer_pos; // current idx to write in buffer + bool buffer_ready; // buffer is filled and ready + bool buffer_eof; // no mor datas - will stop playing + bool loop; // play looped + s32 volume; // volume + GuiSoundDecoder *decoder; - //!Start sound playback - void Play(); - //!Stop sound playback - void Stop(); - //!Pause sound playback - void Pause(); - //!Resume sound playback - void Resume(); - //!Checks if the sound is currently playing - //!\return true if sound is playing, false otherwise - bool IsPlaying(); - //!Set sound volume - //!\param v Sound volume (0-100) - void SetVolume(int v); - //!Set the sound to loop playback (only applies to OGG) - //!\param l Loop (true to loop) - void SetLoop(bool l); - //!Get the playing time in ms for that moment (only applies to OGG) -protected: - s32 voice; // used asnd-voice - u8 *play_buffer[3]; // trpple-playbuffer - int buffer_nr; // current playbuffer - int buffer_pos; // current idx to write in buffer - bool buffer_ready; // buffer is filled and ready - bool buffer_eof; // no mor datas - will stop playing - bool loop; // play looped - s32 volume; // volume - GuiSoundDecoder *decoder; - - void DecoderCallback(); - void PlayerCallback(); - friend void *GuiSoundDecoderThread(void *args); - friend void GuiSoundPlayerCallback(s32 Voice); + void DecoderCallback(); + void PlayerCallback(); + friend void *GuiSoundDecoderThread(void *args); + friend void GuiSoundPlayerCallback(s32 Voice); }; //!Menu input trigger management. Determine if action is neccessary based on input data by comparing controller input data to a specific trigger element. -class GuiTrigger { -public: - //!Constructor - GuiTrigger(); - //!Destructor - ~GuiTrigger(); - //!Sets a simple trigger. Requires: element is selected, and trigger button is pressed - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Sets a held trigger. Requires: element is selected, and trigger button is pressed - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Sets a button-only trigger. Requires: Trigger button is pressed - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Sets a button-only trigger. Requires: trigger button is pressed and parent window of element is in focus - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Get X/Y value from Wii Joystick (classic, nunchuk) input - //!\param right Controller stick (left = 0, right = 1) - //!\param axis Controller stick axis (x-axis = 0, y-axis = 1) - //!\return Stick value - s8 WPAD_Stick(u8 right, int axis); - //!Move menu selection left (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved left, false otherwise - bool Left(); - //!Move menu selection right (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved right, false otherwise - bool Right(); - //!Move menu selection up (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved up, false otherwise - bool Up(); - //!Move menu selection down (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved down, false otherwise - bool Down(); +class GuiTrigger +{ + public: + //!Constructor + GuiTrigger(); + //!Destructor + ~GuiTrigger(); + //!Sets a simple trigger. Requires: element is selected, and trigger button is pressed + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns); + //!Sets a held trigger. Requires: element is selected, and trigger button is pressed + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns); + //!Sets a button-only trigger. Requires: Trigger button is pressed + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns); + //!Sets a button-only trigger. Requires: trigger button is pressed and parent window of element is in focus + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns); + //!Get X/Y value from Wii Joystick (classic, nunchuk) input + //!\param right Controller stick (left = 0, right = 1) + //!\param axis Controller stick axis (x-axis = 0, y-axis = 1) + //!\return Stick value + s8 WPAD_Stick(u8 right, int axis); + //!Move menu selection left (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved left, false otherwise + bool Left(); + //!Move menu selection right (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved right, false otherwise + bool Right(); + //!Move menu selection up (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved up, false otherwise + bool Up(); + //!Move menu selection down (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved down, false otherwise + bool Down(); - u8 type; //!< trigger type (TRIGGER_SIMPLE, TRIGGER_HELD, TRIGGER_BUTTON_ONLY, TRIGGER_BUTTON_ONLY_IN_FOCUS) - s32 chan; //!< Trigger controller channel (0-3, -1 for all) - WPADData wpad; //!< Wii controller trigger data - PADData pad; //!< GameCube controller trigger data + u8 type; //!< trigger type (TRIGGER_SIMPLE, TRIGGER_HELD, TRIGGER_BUTTON_ONLY, TRIGGER_BUTTON_ONLY_IN_FOCUS) + s32 chan; //!< Trigger controller channel (0-3, -1 for all) + WPADData wpad; //!< Wii controller trigger data + PADData pad; //!< GameCube controller trigger data }; extern GuiTrigger userInput[4]; //!Primary GUI class. Most other classes inherit from this class. -class GuiElement { -public: - //!Constructor - GuiElement(); - //!Destructor - ~GuiElement(); - //!Set the element's parent - //!\param e Pointer to parent element - void SetParent(GuiElement * e); - //!Gets the element's parent - //!\return Pointer to parent element - GuiElement * GetParent(); - //!Gets the current leftmost coordinate of the element - //!Considers horizontal alignment, x offset, width, and parent element's GetLeft() / GetWidth() values - //!\return left coordinate - int GetLeft(); - //!Gets the current topmost coordinate of the element - //!Considers vertical alignment, y offset, height, and parent element's GetTop() / GetHeight() values - //!\return top coordinate - int GetTop(); - //!Sets the minimum y offset of the element - //!\param y Y offset - void SetMinY(int y); - //!Gets the minimum y offset of the element - //!\return Minimum Y offset - int GetMinY(); - //!Sets the maximum y offset of the element - //!\param y Y offset - void SetMaxY(int y); - //!Gets the maximum y offset of the element - //!\return Maximum Y offset - int GetMaxY(); - //!Sets the minimum x offset of the element - //!\param x X offset - void SetMinX(int x); - //!Gets the minimum x offset of the element - //!\return Minimum X offset - int GetMinX(); - //!Sets the maximum x offset of the element - //!\param x X offset - void SetMaxX(int x); - //!Gets the maximum x offset of the element - //!\return Maximum X offset - int GetMaxX(); - //!Gets the current width of the element. Does not currently consider the scale - //!\return width - int GetWidth(); - //!Gets the height of the element. Does not currently consider the scale - //!\return height - int GetHeight(); - //!Sets the size (width/height) of the element - //!\param w Width of element - //!\param h Height of element - void SetSize(int w, int h); - //!Checks whether or not the element is visible - //!\return true if visible, false otherwise - bool IsVisible(); - //!Checks whether or not the element is selectable - //!\return true if selectable, false otherwise - bool IsSelectable(); - //!Checks whether or not the element is clickable - //!\return true if clickable, false otherwise - bool IsClickable(); - //!Checks whether or not the element is holdable - //!\return true if holdable, false otherwise - bool IsHoldable(); - //!Sets whether or not the element is selectable - //!\param s Selectable - void SetSelectable(bool s); - //!Sets whether or not the element is clickable - //!\param c Clickable - void SetClickable(bool c); - //!Sets whether or not the element is holdable - //!\param c Holdable - void SetHoldable(bool d); - //!Gets the element's current state - //!\return state - int GetState(); - //!Gets the controller channel that last changed the element's state - //!\return Channel number (0-3, -1 = no channel) - int GetStateChan(); - //!Sets the element's alpha value - //!\param a alpha value - void SetAlpha(int a); - //!Gets the element's alpha value - //!Considers alpha, alphaDyn, and the parent element's GetAlpha() value - //!\return alpha - int GetAlpha(); - //!Gets the element's AngleDyn value - //!\return alpha - float GetAngleDyn(); - //!Sets the element's scale - //!\param s scale (1 is 100%) - void SetScale(float s); - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's GetScale() value - virtual float GetScale(); - //!Set a new GuiTrigger for the element - //!\param t Pointer to GuiTrigger - void SetTrigger(GuiTrigger * t); - //!\overload - //!\param i Index of trigger array to set - //!\param t Pointer to GuiTrigger - void SetTrigger(u8 i, GuiTrigger * t); - //!Remove GuiTrigger for the element - //!\param i Index of trigger array to set - void RemoveTrigger(u8 i); - //!Checks whether rumble was requested by the element - //!\return true is rumble was requested, false otherwise - bool Rumble(); - //!Sets whether or not the element is requesting a rumble event - //!\param r true if requesting rumble, false if not - void SetRumble(bool r); - //!Set an effect for the element - //!\param e Effect to enable - //!\param a Amount of the effect (usage varies on effect) - //!\param t Target amount of the effect (usage varies on effect) - void SetEffect(int e, int a, int t=0); - //!This SetEffect is for EFFECT_GOROUND only - //!\param e Effect to enable - //!\param speed is for Circlespeed - //!\param circles Circleamount in degree ike 180 for 1/2 circle or 720 for 2 circles - //!\param r Circle Radius in pixel - //!\param startdegree Degree where to start circling - //!\param anglespeedset Set the speed of Angle rotating make 1 for same speed as Circlespeed - //! or 0.5 for half the speed of the circlingspeed. Turn Anglecircling off by 0 to this param. - //!\param center_x x co-ordinate of the center of circle. - //!\param center_y y co-ordinate of the center of circle. - void SetEffect(int e, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y); - //!Gets the frequency from the above effect - //!\return element frequency - float GetFrequency(); - //!Sets an effect to be enabled on wiimote cursor over - //!\param e Effect to enable - //!\param a Amount of the effect (usage varies on effect) - //!\param t Target amount of the effect (usage varies on effect) - void SetEffectOnOver(int e, int a, int t=0); - //!Shortcut to SetEffectOnOver(EFFECT_SCALE, 4, 110) - void SetEffectGrow(); - //!Stops the current element effect - void StopEffect(); - //!Gets the current element effects - //!\return element effects - int GetEffect(); - //!Gets the current element on over effects - //!\return element on over effects - int GetEffectOnOver(); - //!Checks whether the specified coordinates are within the element's boundaries - //!\param x X coordinate - //!\param y Y coordinate - //!\return true if contained within, false otherwise - bool IsInside(int x, int y); - //!Sets the element's position - //!\param x X coordinate - //!\param y Y coordinate - void SetPosition(int x, int y, int z = 0); - //!Updates the element's effects (dynamic values) - //!Called by Draw(), used for animation purposes - void UpdateEffects(); - //!Sets a function to called after after Update() - //!Callback function can be used to response to changes in the state of the element, and/or update the element's attributes - void SetUpdateCallback(UpdateCallback u); - //!Checks whether the element is in focus - //!\return true if element is in focus, false otherwise - int IsFocused(); - //!Sets the element's visibility - //!\param v Visibility (true = visible) - virtual void SetVisible(bool v); - //!Sets the element's focus - //!\param f Focus (true = in focus) - virtual void SetFocus(int f); - //!Sets the element's state - //!\param s State (STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_DISABLED) - //!\param c Controller channel (0-3, -1 = none) - virtual void SetState(int s, int c = -1); - //!Resets the element's state to STATE_DEFAULT - virtual void ResetState(); - //!Gets whether or not the element is in STATE_SELECTED - //!\return true if selected, false otherwise - virtual int GetSelected(); - //!Sets the element's alignment respective to its parent element - //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) - //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) - virtual void SetAlignment(int hor, int vert); - //!Called constantly to allow the element to respond to the current input data - //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD - virtual void Update(GuiTrigger * t); - //!Called constantly to redraw the element - virtual void Draw(); - virtual void DrawTooltip(); -protected: - void Lock(); - void Unlock(); +class GuiElement +{ + public: + //!Constructor + GuiElement(); + //!Destructor + ~GuiElement(); + //!Set the element's parent + //!\param e Pointer to parent element + void SetParent(GuiElement * e); + //!Gets the element's parent + //!\return Pointer to parent element + GuiElement * GetParent(); + //!Gets the current leftmost coordinate of the element + //!Considers horizontal alignment, x offset, width, and parent element's GetLeft() / GetWidth() values + //!\return left coordinate + int GetLeft(); + //!Gets the current topmost coordinate of the element + //!Considers vertical alignment, y offset, height, and parent element's GetTop() / GetHeight() values + //!\return top coordinate + int GetTop(); + //!Sets the minimum y offset of the element + //!\param y Y offset + void SetMinY(int y); + //!Gets the minimum y offset of the element + //!\return Minimum Y offset + int GetMinY(); + //!Sets the maximum y offset of the element + //!\param y Y offset + void SetMaxY(int y); + //!Gets the maximum y offset of the element + //!\return Maximum Y offset + int GetMaxY(); + //!Sets the minimum x offset of the element + //!\param x X offset + void SetMinX(int x); + //!Gets the minimum x offset of the element + //!\return Minimum X offset + int GetMinX(); + //!Sets the maximum x offset of the element + //!\param x X offset + void SetMaxX(int x); + //!Gets the maximum x offset of the element + //!\return Maximum X offset + int GetMaxX(); + //!Gets the current width of the element. Does not currently consider the scale + //!\return width + int GetWidth(); + //!Gets the height of the element. Does not currently consider the scale + //!\return height + int GetHeight(); + //!Sets the size (width/height) of the element + //!\param w Width of element + //!\param h Height of element + void SetSize(int w, int h); + //!Checks whether or not the element is visible + //!\return true if visible, false otherwise + bool IsVisible(); + //!Checks whether or not the element is selectable + //!\return true if selectable, false otherwise + bool IsSelectable(); + //!Checks whether or not the element is clickable + //!\return true if clickable, false otherwise + bool IsClickable(); + //!Checks whether or not the element is holdable + //!\return true if holdable, false otherwise + bool IsHoldable(); + //!Sets whether or not the element is selectable + //!\param s Selectable + void SetSelectable(bool s); + //!Sets whether or not the element is clickable + //!\param c Clickable + void SetClickable(bool c); + //!Sets whether or not the element is holdable + //!\param c Holdable + void SetHoldable(bool d); + //!Gets the element's current state + //!\return state + int GetState(); + //!Gets the controller channel that last changed the element's state + //!\return Channel number (0-3, -1 = no channel) + int GetStateChan(); + //!Sets the element's alpha value + //!\param a alpha value + void SetAlpha(int a); + //!Gets the element's alpha value + //!Considers alpha, alphaDyn, and the parent element's GetAlpha() value + //!\return alpha + int GetAlpha(); + //!Gets the element's AngleDyn value + //!\return alpha + float GetAngleDyn(); + //!Sets the element's scale + //!\param s scale (1 is 100%) + void SetScale(float s); + //!Gets the element's current scale + //!Considers scale, scaleDyn, and the parent element's GetScale() value + virtual float GetScale(); + //!Set a new GuiTrigger for the element + //!\param t Pointer to GuiTrigger + void SetTrigger(GuiTrigger * t); + //!\overload + //!\param i Index of trigger array to set + //!\param t Pointer to GuiTrigger + void SetTrigger(u8 i, GuiTrigger * t); + //!Remove GuiTrigger for the element + //!\param i Index of trigger array to set + void RemoveTrigger(u8 i); + //!Checks whether rumble was requested by the element + //!\return true is rumble was requested, false otherwise + bool Rumble(); + //!Sets whether or not the element is requesting a rumble event + //!\param r true if requesting rumble, false if not + void SetRumble(bool r); + //!Set an effect for the element + //!\param e Effect to enable + //!\param a Amount of the effect (usage varies on effect) + //!\param t Target amount of the effect (usage varies on effect) + void SetEffect(int e, int a, int t=0); + //!This SetEffect is for EFFECT_GOROUND only + //!\param e Effect to enable + //!\param speed is for Circlespeed + //!\param circles Circleamount in degree ike 180 for 1/2 circle or 720 for 2 circles + //!\param r Circle Radius in pixel + //!\param startdegree Degree where to start circling + //!\param anglespeedset Set the speed of Angle rotating make 1 for same speed as Circlespeed + //! or 0.5 for half the speed of the circlingspeed. Turn Anglecircling off by 0 to this param. + //!\param center_x x co-ordinate of the center of circle. + //!\param center_y y co-ordinate of the center of circle. + void SetEffect(int e, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y); + //!Gets the frequency from the above effect + //!\return element frequency + float GetFrequency(); + //!Sets an effect to be enabled on wiimote cursor over + //!\param e Effect to enable + //!\param a Amount of the effect (usage varies on effect) + //!\param t Target amount of the effect (usage varies on effect) + void SetEffectOnOver(int e, int a, int t=0); + //!Shortcut to SetEffectOnOver(EFFECT_SCALE, 4, 110) + void SetEffectGrow(); + //!Stops the current element effect + void StopEffect(); + //!Gets the current element effects + //!\return element effects + int GetEffect(); + //!Gets the current element on over effects + //!\return element on over effects + int GetEffectOnOver(); + //!Checks whether the specified coordinates are within the element's boundaries + //!\param x X coordinate + //!\param y Y coordinate + //!\return true if contained within, false otherwise + bool IsInside(int x, int y); + //!Sets the element's position + //!\param x X coordinate + //!\param y Y coordinate + void SetPosition(int x, int y, int z = 0); + //!Updates the element's effects (dynamic values) + //!Called by Draw(), used for animation purposes + void UpdateEffects(); + //!Sets a function to called after after Update() + //!Callback function can be used to response to changes in the state of the element, and/or update the element's attributes + void SetUpdateCallback(UpdateCallback u); + //!Checks whether the element is in focus + //!\return true if element is in focus, false otherwise + int IsFocused(); + //!Sets the element's visibility + //!\param v Visibility (true = visible) + virtual void SetVisible(bool v); + //!Sets the element's focus + //!\param f Focus (true = in focus) + virtual void SetFocus(int f); + //!Sets the element's state + //!\param s State (STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_DISABLED) + //!\param c Controller channel (0-3, -1 = none) + virtual void SetState(int s, int c = -1); + //!Resets the element's state to STATE_DEFAULT + virtual void ResetState(); + //!Gets whether or not the element is in STATE_SELECTED + //!\return true if selected, false otherwise + virtual int GetSelected(); + //!Sets the element's alignment respective to its parent element + //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) + //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) + virtual void SetAlignment(int hor, int vert); + //!Called constantly to allow the element to respond to the current input data + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + virtual void Update(GuiTrigger * t); + //!Called constantly to redraw the element + virtual void Draw(); + virtual void DrawTooltip(); + protected: + void Lock(); + void Unlock(); // static mutex_t mutex; - static mutex_t _lock_mutex; - lwp_t _lock_thread; - u16 _lock_count; - lwpq_t _lock_queue; - friend class SimpleLock; + static mutex_t _lock_mutex; + lwp_t _lock_thread; + u16 _lock_count; + lwpq_t _lock_queue; + friend class SimpleLock; - //int position2; //! B Scrollbariable - bool visible; //!< Visibility of the element. If false, Draw() is skipped - int focus; //!< Element focus (-1 = focus disabled, 0 = not focused, 1 = focused) - int dontsetfocus; //! _elements; //!< Contains all elements within the GuiWindow +class GuiWindow : public GuiElement +{ + public: + //!Constructor + GuiWindow(); + //!\overload + //!\param w Width of window + //!\param h Height of window + GuiWindow(int w, int h); + //!Destructor + ~GuiWindow(); + //!Appends a GuiElement to the GuiWindow + //!\param e The GuiElement to append. If it is already in the GuiWindow, it is removed first + void Append(GuiElement* e); + //!Inserts a GuiElement into the GuiWindow at the specified index + //!\param e The GuiElement to insert. If it is already in the GuiWindow, it is removed first + //!\param i Index in which to insert the element + void Insert(GuiElement* e, u32 i); + //!Removes the specified GuiElement from the GuiWindow + //!\param e GuiElement to be removed + void Remove(GuiElement* e); + //!Removes all GuiElements + void RemoveAll(); + //!Returns the GuiElement at the specified index + //!\param index The index of the element + //!\return A pointer to the element at the index, NULL on error (eg: out of bounds) + GuiElement* GetGuiElementAt(u32 index) const; + //!Returns the size of the list of elements + //!\return The size of the current element list + u32 GetSize(); + //!Sets the visibility of the window + //!\param v visibility (true = visible) + void SetVisible(bool v); + //!Resets the window's state to STATE_DEFAULT + void ResetState(); + //!Sets the window's state + //!\param s State + void SetState(int s); + //!Gets the index of the GuiElement inside the window that is currently selected + //!\return index of selected GuiElement + int GetSelected(); + //!Sets the window focus + //!\param f Focus + void SetFocus(int f); + //!Change the focus to the specified element + //!This is intended for the primary GuiWindow only + //!\param e GuiElement that should have focus + void ChangeFocus(GuiElement * e); + //!Changes window focus to the next focusable window or element + //!If no element is in focus, changes focus to the first available element + //!If B or 1 button is pressed, changes focus to the next available element + //!This is intended for the primary GuiWindow only + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + void ToggleFocus(GuiTrigger * t); + //!Moves the selected element to the element to the left or right + //!\param d Direction to move (-1 = left, 1 = right) + void MoveSelectionHor(int d); + //!Moves the selected element to the element above or below + //!\param d Direction to move (-1 = up, 1 = down) + void MoveSelectionVert(int d); + //!Draws all the elements in this GuiWindow + void Draw(); + void DrawTooltip(); + //!Updates the window and all elements contains within + //!Allows the GuiWindow and all elements to respond to the input data specified + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + void Update(GuiTrigger * t); + protected: + std::vector _elements; //!< Contains all elements within the GuiWindow }; //!Converts image data into GX-useable RGBA8. Currently designed for use only with PNG files -class GuiImageData { -public: - //!Constructor - //!Converts the image data to RGBA8 - expects PNG format - //!\param i Image data - GuiImageData(const u8 * i); - GuiImageData(const char * imgPath, const u8 * buffer); - GuiImageData(const u8 * img, int imgSize); - GuiImageData(const char *path, const char *file, const u8 * buffer, bool force_widescreen=false, const u8 * wbuffer=NULL); - //!Destructor - ~GuiImageData(); - //!Gets a pointer to the image data - //!\return pointer to image data - u8 * GetImage(); - //!Gets the image width - //!\return image width - int GetWidth(); - //!Gets the image height - //!\return image height - int GetHeight(); - //!LoadJpeg file - void LoadJpeg(const u8 *img, int imgSize); - //!RawTo4x4RGBA - void RawTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height); - //!Sets the image to grayscale - void SetGrayscale(void); -protected: - u8 * data; //!< Image data - int height; //!< Height of image - int width; //!< Width of image +class GuiImageData +{ + public: + //!Constructor + //!Converts the image data to RGBA8 - expects PNG format + //!\param i Image data + GuiImageData(const u8 * i); + GuiImageData(const char * imgPath, const u8 * buffer); + GuiImageData(const u8 * img, int imgSize); + GuiImageData(const char *path, const char *file, const u8 * buffer, bool force_widescreen=false, const u8 * wbuffer=NULL); + //!Destructor + ~GuiImageData(); + //!Gets a pointer to the image data + //!\return pointer to image data + u8 * GetImage(); + //!Gets the image width + //!\return image width + int GetWidth(); + //!Gets the image height + //!\return image height + int GetHeight(); + //!LoadJpeg file + void LoadJpeg(const u8 *img, int imgSize); + //!RawTo4x4RGBA + void RawTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height); + //!Sets the image to grayscale + void SetGrayscale(void); + protected: + u8 * data; //!< Image data + int height; //!< Height of image + int width; //!< Width of image }; //!Display, manage, and manipulate images in the GUI -class GuiImage : public GuiElement { -public: - //!Constructor - GuiImage(); - //!\overload - //!\param img Pointer to GuiImageData element - GuiImage(GuiImageData * img); - //!\overload - //!Sets up a new image from the image data specified - //!\param img - //!\param w Image width - //!\param h Image height - GuiImage(u8 * img, int w, int h); - //!\overload - //!Creates an image filled with the specified color - //!\param w Image width - //!\param h Image height - //!\param c Image color - GuiImage(int w, int h, GXColor c); - //! Copy Constructor - GuiImage(GuiImage &srcimage); - GuiImage(GuiImage *srcimage); - //! = operator for copying images - GuiImage &operator=(GuiImage &srcimage); - //!Destructor - ~GuiImage(); - //!Sets the image rotation angle for drawing - //!\param a Angle (in degrees) - void SetAngle(float a); - //!Gets the image rotation angle for drawing - float GetAngle(); - //!Sets the number of times to draw the image horizontally - //!\param t Number of times to draw the image - void SetTile(int t); - // true set horizontal scale to 0.8 //added - void SetWidescreen(bool w); - //!Constantly called to draw the image - void Draw(); - //!Gets the image data - //!\return pointer to image data - u8 * GetImage(); - //!Sets up a new image using the GuiImageData object specified - //!\param img Pointer to GuiImageData object - void SetImage(GuiImageData * img); - //!\overload - //!\param img Pointer to image data - //!\param w Width - //!\param h Height - void SetImage(u8 * img, int w, int h); - //!Gets the pixel color at the specified coordinates of the image - //!\param x X coordinate - //!\param y Y coordinate - GXColor GetPixel(int x, int y); - //!Sets the pixel color at the specified coordinates of the image - //!\param x X coordinate - //!\param y Y coordinate - //!\param color Pixel color - void SetPixel(int x, int y, GXColor color); - //!Sets the image to grayscale - void SetGrayscale(void); - //!Set/disable the use of parentelement angle (default true) - void SetParentAngle(bool a); - //!Directly modifies the image data to create a color-striped effect - //!Alters the RGB values by the specified amount - //!\param s Amount to increment/decrement the RGB values in the image - void ColorStripe(int s); - //!Sets a stripe effect on the image, overlaying alpha blended rectangles - //!Does not alter the image data - //!\param s Alpha amount to draw over the image - void SetStripe(int s); - s32 z; - void SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4); - void SetSkew(int *skew /* int skew[8] */ ); - int xx1; - int yy1; - int xx2; - int yy2; - int xx3; - int yy3; - int xx4; - int yy4; - int rxx1; - int ryy1; - int rxx2; - int ryy2; - int rxx3; - int ryy3; - int rxx4; - int ryy4; -protected: - int imgType; //!< Type of image data (IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA) - u8 * image; //!< Poiner to image data. May be shared with GuiImageData data - f32 imageangle; //!< Angle to draw the image - int tile; //!< Number of times to draw (tile) the image horizontally - int stripe; //!< Alpha value (0-255) to apply a stripe effect to the texture - short widescreen; //added - bool parentangle; +class GuiImage : public GuiElement +{ + public: + //!Constructor + GuiImage(); + //!\overload + //!\param img Pointer to GuiImageData element + GuiImage(GuiImageData * img); + //!\overload + //!Sets up a new image from the image data specified + //!\param img + //!\param w Image width + //!\param h Image height + GuiImage(u8 * img, int w, int h); + //!\overload + //!Creates an image filled with the specified color + //!\param w Image width + //!\param h Image height + //!\param c Image color + GuiImage(int w, int h, GXColor c); + //! Copy Constructor + GuiImage(GuiImage &srcimage); + GuiImage(GuiImage *srcimage); + //! = operator for copying images + GuiImage &operator=(GuiImage &srcimage); + //!Destructor + ~GuiImage(); + //!Sets the image rotation angle for drawing + //!\param a Angle (in degrees) + void SetAngle(float a); + //!Gets the image rotation angle for drawing + float GetAngle(); + //!Sets the number of times to draw the image horizontally + //!\param t Number of times to draw the image + void SetTile(int t); + // true set horizontal scale to 0.8 //added + void SetWidescreen(bool w); + //!Constantly called to draw the image + void Draw(); + //!Gets the image data + //!\return pointer to image data + u8 * GetImage(); + //!Sets up a new image using the GuiImageData object specified + //!\param img Pointer to GuiImageData object + void SetImage(GuiImageData * img); + //!\overload + //!\param img Pointer to image data + //!\param w Width + //!\param h Height + void SetImage(u8 * img, int w, int h); + //!Gets the pixel color at the specified coordinates of the image + //!\param x X coordinate + //!\param y Y coordinate + GXColor GetPixel(int x, int y); + //!Sets the pixel color at the specified coordinates of the image + //!\param x X coordinate + //!\param y Y coordinate + //!\param color Pixel color + void SetPixel(int x, int y, GXColor color); + //!Sets the image to grayscale + void SetGrayscale(void); + //!Set/disable the use of parentelement angle (default true) + void SetParentAngle(bool a); + //!Directly modifies the image data to create a color-striped effect + //!Alters the RGB values by the specified amount + //!\param s Amount to increment/decrement the RGB values in the image + void ColorStripe(int s); + //!Sets a stripe effect on the image, overlaying alpha blended rectangles + //!Does not alter the image data + //!\param s Alpha amount to draw over the image + void SetStripe(int s); + s32 z; + void SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4); + void SetSkew(int *skew /* int skew[8] */ ); + int xx1; + int yy1; + int xx2; + int yy2; + int xx3; + int yy3; + int xx4; + int yy4; + int rxx1; + int ryy1; + int rxx2; + int ryy2; + int rxx3; + int ryy3; + int rxx4; + int ryy4; + protected: + int imgType; //!< Type of image data (IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA) + u8 * image; //!< Poiner to image data. May be shared with GuiImageData data + f32 imageangle; //!< Angle to draw the image + int tile; //!< Number of times to draw (tile) the image horizontally + int stripe; //!< Alpha value (0-255) to apply a stripe effect to the texture + short widescreen; //added + bool parentangle; }; //!Display, manage, and manipulate text in the GUI -class GuiText : public GuiElement { -public: - //!Constructor - //!\param t Text - //!\param s Font size - //!\param c Font color - GuiText(const char * t, int s, GXColor c); - //!\overload - //!\Assumes SetPresets() has been called to setup preferred text attributes - //!\param t Text - GuiText(const char * t); - //!Destructor - ~GuiText(); - //!Sets the text of the GuiText element - //!\param t Text - void SetText(const char * t); - void SetTextf(const char *format, ...) __attribute__((format(printf,2,3))); - void SetText(const wchar_t * t); - //!Sets up preset values to be used by GuiText(t) - //!Useful when printing multiple text elements, all with the same attributes set - //!\param sz Font size - //!\param c Font color - //!\param w Maximum width of texture image (for text wrapping) - //!\param wrap Wrapmode when w>0 - //!\param s Font style - //!\param h Text alignment (horizontal) - //!\param v Text alignment (vertical) - static void SetPresets(int sz, GXColor c, int w, int wrap, u16 s, int h, int v); - //!Sets the font size - //!\param s Font size - void SetFontSize(int s); - //!Sets the maximum width of the drawn texture image - //!If the text exceeds this, it is wrapped to the next line - //!\param w Maximum width - //!\param m WrapMode - enum { - WRAP, - DOTTED, - SCROLL, - MARQUEE - }; - void SetMaxWidth(int w, short m=GuiText::WRAP); - //!Sets the font color - //!\param c Font color - void SetColor(GXColor c); - //!Sets the FreeTypeGX style attributes - //!\param s Style attributes - //!\param m Style-Mask attributes - void SetStyle(u16 s, u16 m=0xffff); - //!Sets the text alignment - //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) - //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) - void SetAlignment(int hor, int vert); - //!Sets the font - //!\param f Font - void SetFont(FreeTypeGX *f); - //!Sets a password character - //!\param p char - void SetPassChar(wchar_t p); - //!Get the Horizontal Size of Text - int GetTextWidth(); - // not NULL set horizontal scale to 0.75 //added - void SetWidescreen(bool w); - void SetNumLines(int n);//! these two are used to set the first line and numLine - void SetFirstLine(int n); - int GetNumLines();//! these return the line variables for this text - int GetFirstLine(); - int GetLineHeight(int n);//! returns the height of the #n of lines including spacing if wrap mode is on - int GetTotalLines(); - //!Constantly called to draw the text - void Draw(); -protected: - wchar_t* text; //!< Unicode text value - int size; //!< Font size - int maxWidth; //!< Maximum width of the generated text object (for text wrapping) - short wrapMode; - short scrollPos1; - short scrollPos2; - short scrollOffset; - u32 scrollDelay; - u16 style; //!< FreeTypeGX style attributes - GXColor color; //!< Font color - FreeTypeGX *font; - short widescreen; //added - //!these are default until the text is drawn - int firstLine; //!these are the first line and the number of lines drawn when the text is wrapped - int numLines;//! default is -1 and it means that all lines are drawn - int totalLines; //!this is the total # of lines when in wrap mode - wchar_t passChar; //!this is the password character +class GuiText : public GuiElement +{ + public: + //!Constructor + //!\param t Text + //!\param s Font size + //!\param c Font color + GuiText(const char * t, int s, GXColor c); + //!\overload + //!\Assumes SetPresets() has been called to setup preferred text attributes + //!\param t Text + GuiText(const char * t); + //!Destructor + ~GuiText(); + //!Sets the text of the GuiText element + //!\param t Text + void SetText(const char * t); + void SetTextf(const char *format, ...) __attribute__((format(printf,2,3))); + void SetText(const wchar_t * t); + //!Sets up preset values to be used by GuiText(t) + //!Useful when printing multiple text elements, all with the same attributes set + //!\param sz Font size + //!\param c Font color + //!\param w Maximum width of texture image (for text wrapping) + //!\param wrap Wrapmode when w>0 + //!\param s Font style + //!\param h Text alignment (horizontal) + //!\param v Text alignment (vertical) + static void SetPresets(int sz, GXColor c, int w, int wrap, u16 s, int h, int v); + //!Sets the font size + //!\param s Font size + void SetFontSize(int s); + //!Sets the maximum width of the drawn texture image + //!If the text exceeds this, it is wrapped to the next line + //!\param w Maximum width + //!\param m WrapMode + enum { + WRAP, + DOTTED, + SCROLL, + MARQUEE + }; + void SetMaxWidth(int w, short m=GuiText::WRAP); + //!Sets the font color + //!\param c Font color + void SetColor(GXColor c); + //!Sets the FreeTypeGX style attributes + //!\param s Style attributes + //!\param m Style-Mask attributes + void SetStyle(u16 s, u16 m=0xffff); + //!Sets the text alignment + //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) + //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) + void SetAlignment(int hor, int vert); + //!Sets the font + //!\param f Font + void SetFont(FreeTypeGX *f); + //!Sets a password character + //!\param p char + void SetPassChar(wchar_t p); + //!Get the Horizontal Size of Text + int GetTextWidth(); + // not NULL set horizontal scale to 0.75 //added + void SetWidescreen(bool w); + void SetNumLines(int n);//! these two are used to set the first line and numLine + void SetFirstLine(int n); + int GetNumLines();//! these return the line variables for this text + int GetFirstLine(); + int GetLineHeight(int n);//! returns the height of the #n of lines including spacing if wrap mode is on + int GetTotalLines(); + //!Constantly called to draw the text + void Draw(); + protected: + wchar_t* text; //!< Unicode text value + int size; //!< Font size + int maxWidth; //!< Maximum width of the generated text object (for text wrapping) + short wrapMode; + short scrollPos1; + short scrollPos2; + short scrollOffset; + u32 scrollDelay; + u16 style; //!< FreeTypeGX style attributes + GXColor color; //!< Font color + FreeTypeGX *font; + short widescreen; //added + //!these are default until the text is drawn + int firstLine; //!these are the first line and the number of lines drawn when the text is wrapped + int numLines;//! default is -1 and it means that all lines are drawn + int totalLines; //!this is the total # of lines when in wrap mode + wchar_t passChar; //!this is the password character }; //!Display, manage, and manipulate tooltips in the GUI. -class GuiTooltip : public GuiElement { -public: - //!Constructor - //!\param t Text - GuiTooltip(const char *t, int Alpha=255); +class GuiTooltip : public GuiElement +{ + public: + //!Constructor + //!\param t Text + GuiTooltip(const char *t, int Alpha=255); - //!Destructor - ~ GuiTooltip(); + //!Destructor + ~ GuiTooltip(); - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's GetScale() value - float GetScale(); - //!Sets the text of the GuiTooltip element - //!\param t Text - void SetText(const char * t); - void SetWidescreen(bool w); // timely a dummy - //!Constantly called to draw the GuiButton - void Draw(); + //!Gets the element's current scale + //!Considers scale, scaleDyn, and the parent element's GetScale() value + float GetScale(); + //!Sets the text of the GuiTooltip element + //!\param t Text + void SetText(const char * t); + void SetWidescreen(bool w); // timely a dummy + //!Constantly called to draw the GuiButton + void Draw(); -protected: - GuiImage leftImage; //!< Tooltip left-image - GuiImage tileImage; //!< Tooltip tile-image - GuiImage rightImage; //!< Tooltip right-image - GuiText *text; + protected: + GuiImage leftImage; //!< Tooltip left-image + GuiImage tileImage; //!< Tooltip tile-image + GuiImage rightImage; //!< Tooltip right-image + GuiText *text; }; //!Display, manage, and manipulate buttons in the GUI. Buttons can have images, icons, text, and sound set (all of which are optional) -class GuiButton : public GuiElement { -public: - //!Constructor - //!\param w Width - //!\param h Height - GuiButton(int w, int h); - //!\param img is the button GuiImage. it uses the height & width of this image for the button - //!\param imgOver is the button's over GuiImage - //!\param hor is horizontal alingment of the button - //!\param vert is verticle alignment of the button - //!\param x is xposition of the button - //!\param y is yposition of the button - //!\param trig is a GuiTrigger to assign to this button - //!\param sndOver is a GuiSound used for soundOnOver for this button - //!\param sndClick is a GuiSound used for clickSound of this button - //!\param grow sets effect grow for this button. 1 for yes ;0 for no - GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow); - //!\param same as all the parameters for the above button plus the following - //!\param tt is a GuiTooltip assigned to this button - //!\param ttx and tty are the xPOS and yPOS for this tooltip in relationship to the button - //!\param h_align and v_align are horizontal and verticle alignment for the tooltip in relationship to the button - GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align); - //!Destructor - ~GuiButton(); - //!Sets the button's image - //!\param i Pointer to GuiImage object - void SetImage(GuiImage* i); - //!Sets the button's image on over - //!\param i Pointer to GuiImage object - void SetImageOver(GuiImage* i); - //!Sets the button's image on hold - //!\param i Pointer to GuiImage object - void SetAngle(float a); - void SetImageHold(GuiImage* i); - //!Sets the button's image on click - //!\param i Pointer to GuiImage object - void SetImageClick(GuiImage* i); - //!Sets the button's icon - //!\param i Pointer to GuiImage object - void SetIcon(GuiImage* i); - //!Sets the button's icon on over - //!\param i Pointer to GuiImage object - void SetIconOver(GuiImage* i); - //!Sets the button's icon on hold - //!\param i Pointer to GuiImage object - void SetIconHold(GuiImage* i); - //!Sets the button's icon on click - //!\param i Pointer to GuiImage object - void SetIconClick(GuiImage* i); - //!Sets the button's label - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabel(GuiText* t, int n = 0); - //!Sets the button's label on over (eg: different colored text) - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabelOver(GuiText* t, int n = 0); - //!Sets the button's label on hold - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabelHold(GuiText* t, int n = 0); - //!Sets the button's label on click - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabelClick(GuiText* t, int n = 0); - //!Sets the sound to play on over - //!\param s Pointer to GuiSound object - void SetSoundOver(GuiSound * s); - //!Sets the sound to play on hold - //!\param s Pointer to GuiSound object - void SetSoundHold(GuiSound * s); - //!Sets the sound to play on click - //!\param s Pointer to GuiSound object - void SetSoundClick(GuiSound * s); - //!\param reset the soundover to NULL - void RemoveSoundOver(); - //!\param reset the soundclick to NULL - void RemoveSoundClick(); - //!Constantly called to draw the GuiButtons ToolTip - //!Sets the button's Tooltip on over - //!\param tt Pointer to GuiElement object, x & y Positioning, h & v Align - void SetToolTip(GuiTooltip* tt, int x, int y, int h=ALIGN_RIGHT, int v=ALIGN_TOP); +class GuiButton : public GuiElement +{ + public: + //!Constructor + //!\param w Width + //!\param h Height + GuiButton(int w, int h); + //!\param img is the button GuiImage. it uses the height & width of this image for the button + //!\param imgOver is the button's over GuiImage + //!\param hor is horizontal alingment of the button + //!\param vert is verticle alignment of the button + //!\param x is xposition of the button + //!\param y is yposition of the button + //!\param trig is a GuiTrigger to assign to this button + //!\param sndOver is a GuiSound used for soundOnOver for this button + //!\param sndClick is a GuiSound used for clickSound of this button + //!\param grow sets effect grow for this button. 1 for yes ;0 for no + GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow); + //!\param same as all the parameters for the above button plus the following + //!\param tt is a GuiTooltip assigned to this button + //!\param ttx and tty are the xPOS and yPOS for this tooltip in relationship to the button + //!\param h_align and v_align are horizontal and verticle alignment for the tooltip in relationship to the button + GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align); + //!Destructor + ~GuiButton(); + //!Sets the button's image + //!\param i Pointer to GuiImage object + void SetImage(GuiImage* i); + //!Sets the button's image on over + //!\param i Pointer to GuiImage object + void SetImageOver(GuiImage* i); + //!Sets the button's image on hold + //!\param i Pointer to GuiImage object + void SetAngle(float a); + void SetImageHold(GuiImage* i); + //!Sets the button's image on click + //!\param i Pointer to GuiImage object + void SetImageClick(GuiImage* i); + //!Sets the button's icon + //!\param i Pointer to GuiImage object + void SetIcon(GuiImage* i); + //!Sets the button's icon on over + //!\param i Pointer to GuiImage object + void SetIconOver(GuiImage* i); + //!Sets the button's icon on hold + //!\param i Pointer to GuiImage object + void SetIconHold(GuiImage* i); + //!Sets the button's icon on click + //!\param i Pointer to GuiImage object + void SetIconClick(GuiImage* i); + //!Sets the button's label + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabel(GuiText* t, int n = 0); + //!Sets the button's label on over (eg: different colored text) + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabelOver(GuiText* t, int n = 0); + //!Sets the button's label on hold + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabelHold(GuiText* t, int n = 0); + //!Sets the button's label on click + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabelClick(GuiText* t, int n = 0); + //!Sets the sound to play on over + //!\param s Pointer to GuiSound object + void SetSoundOver(GuiSound * s); + //!Sets the sound to play on hold + //!\param s Pointer to GuiSound object + void SetSoundHold(GuiSound * s); + //!Sets the sound to play on click + //!\param s Pointer to GuiSound object + void SetSoundClick(GuiSound * s); + //!\param reset the soundover to NULL + void RemoveSoundOver(); + //!\param reset the soundclick to NULL + void RemoveSoundClick(); + //!Constantly called to draw the GuiButtons ToolTip + //!Sets the button's Tooltip on over + //!\param tt Pointer to GuiElement object, x & y Positioning, h & v Align + void SetToolTip(GuiTooltip* tt, int x, int y, int h=ALIGN_RIGHT, int v=ALIGN_TOP); - void RemoveToolTip(); - //!Constantly called to draw the GuiButton - void Draw(); - void DrawTooltip(); - //!Constantly called to allow the GuiButton to respond to updated input data - //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD - void Update(GuiTrigger * t); - //!Deactivate/Activate pointing on Games while B scrolling - void ScrollIsOn(int f); - void SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4); - void SetSkew(int *skew /* int skew[8] */ ); -protected: - GuiImage * image; //!< Button image (default) - GuiImage * imageOver; //!< Button image for STATE_SELECTED - GuiImage * imageHold; //!< Button image for STATE_HELD - GuiImage * imageClick; //!< Button image for STATE_CLICKED - GuiImage * icon; //!< Button icon (drawn after button image) - GuiImage * iconOver; //!< Button icon for STATE_SELECTED - GuiImage * iconHold; //!< Button icon for STATE_HELD - GuiImage * iconClick; //!< Button icon for STATE_CLICKED - GuiTooltip *toolTip; - time_t time1, time2;//!< Tooltip timeconstants - GuiText * label[3]; //!< Label(s) to display (default) - GuiText * labelOver[3]; //!< Label(s) to display for STATE_SELECTED - GuiText * labelHold[3]; //!< Label(s) to display for STATE_HELD - GuiText * labelClick[3]; //!< Label(s) to display for STATE_CLICKED - GuiSound * soundOver; //!< Sound to play for STATE_SELECTED - GuiSound * soundHold; //!< Sound to play for STATE_HELD - GuiSound * soundClick; //!< Sound to play for STATE_CLICKED + void RemoveToolTip(); + //!Constantly called to draw the GuiButton + void Draw(); + void DrawTooltip(); + //!Constantly called to allow the GuiButton to respond to updated input data + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + void Update(GuiTrigger * t); + //!Deactivate/Activate pointing on Games while B scrolling + void ScrollIsOn(int f); + void SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4); + void SetSkew(int *skew /* int skew[8] */ ); + protected: + GuiImage * image; //!< Button image (default) + GuiImage * imageOver; //!< Button image for STATE_SELECTED + GuiImage * imageHold; //!< Button image for STATE_HELD + GuiImage * imageClick; //!< Button image for STATE_CLICKED + GuiImage * icon; //!< Button icon (drawn after button image) + GuiImage * iconOver; //!< Button icon for STATE_SELECTED + GuiImage * iconHold; //!< Button icon for STATE_HELD + GuiImage * iconClick; //!< Button icon for STATE_CLICKED + GuiTooltip *toolTip; + time_t time1, time2;//!< Tooltip timeconstants + GuiText * label[3]; //!< Label(s) to display (default) + GuiText * labelOver[3]; //!< Label(s) to display for STATE_SELECTED + GuiText * labelHold[3]; //!< Label(s) to display for STATE_HELD + GuiText * labelClick[3]; //!< Label(s) to display for STATE_CLICKED + GuiSound * soundOver; //!< Sound to play for STATE_SELECTED + GuiSound * soundHold; //!< Sound to play for STATE_HELD + GuiSound * soundClick; //!< Sound to play for STATE_CLICKED }; typedef struct _keytype { - char ch, chShift, chalt, chalt2; + char ch, chShift, chalt, chalt2; } Key; //!On-screen keyboard -class GuiKeyboard : public GuiWindow { -public: - GuiKeyboard(char * t, u32 m, int min, int lang); - ~GuiKeyboard(); - void Update(GuiTrigger * t); - char kbtextstr[256]; -protected: - u32 kbtextmaxlen; - Key keys[4][11]; - int shift; - int caps; - int alt; - int alt2; - GuiText * kbText; - GuiImage * keyTextboxImg; - GuiText * keyCapsText; - GuiImage * keyCapsImg; - GuiImage * keyCapsOverImg; - GuiButton * keyCaps; - GuiText * keyAltText; - GuiImage * keyAltImg; - GuiImage * keyAltOverImg; - GuiButton * keyAlt; - GuiText * keyAlt2Text; - GuiImage * keyAlt2Img; - GuiImage * keyAlt2OverImg; - GuiButton * keyAlt2; - GuiText * keyShiftText; - GuiImage * keyShiftImg; - GuiImage * keyShiftOverImg; - GuiButton * keyShift; - GuiText * keyBackText; - GuiImage * keyBackImg; - GuiImage * keyBackOverImg; - GuiButton * keyBack; - GuiText * keyClearText; - GuiImage * keyClearImg; - GuiImage * keyClearOverImg; - GuiButton * keyClear; - GuiImage * keySpaceImg; - GuiImage * keySpaceOverImg; - GuiButton * keySpace; - GuiButton * keyBtn[4][11]; - GuiImage * keyImg[4][11]; - GuiImage * keyImgOver[4][11]; - GuiText * keyTxt[4][11]; - GuiImageData * keyTextbox; - GuiImageData * key; - GuiImageData * keyOver; - GuiImageData * keyMedium; - GuiImageData * keyMediumOver; - GuiImageData * keyLarge; - GuiImageData * keyLargeOver; - GuiSound * keySoundOver; - GuiSound * keySoundClick; - GuiTrigger * trigA; - GuiTrigger * trigB; +class GuiKeyboard : public GuiWindow +{ + public: + GuiKeyboard(char * t, u32 m, int min, int lang); + ~GuiKeyboard(); + void Update(GuiTrigger * t); + char kbtextstr[256]; + protected: + u32 kbtextmaxlen; + Key keys[4][11]; + int shift; + int caps; + int alt; + int alt2; + GuiText * kbText; + GuiImage * keyTextboxImg; + GuiText * keyCapsText; + GuiImage * keyCapsImg; + GuiImage * keyCapsOverImg; + GuiButton * keyCaps; + GuiText * keyAltText; + GuiImage * keyAltImg; + GuiImage * keyAltOverImg; + GuiButton * keyAlt; + GuiText * keyAlt2Text; + GuiImage * keyAlt2Img; + GuiImage * keyAlt2OverImg; + GuiButton * keyAlt2; + GuiText * keyShiftText; + GuiImage * keyShiftImg; + GuiImage * keyShiftOverImg; + GuiButton * keyShift; + GuiText * keyBackText; + GuiImage * keyBackImg; + GuiImage * keyBackOverImg; + GuiButton * keyBack; + GuiText * keyClearText; + GuiImage * keyClearImg; + GuiImage * keyClearOverImg; + GuiButton * keyClear; + GuiImage * keySpaceImg; + GuiImage * keySpaceOverImg; + GuiButton * keySpace; + GuiButton * keyBtn[4][11]; + GuiImage * keyImg[4][11]; + GuiImage * keyImgOver[4][11]; + GuiText * keyTxt[4][11]; + GuiImageData * keyTextbox; + GuiImageData * key; + GuiImageData * keyOver; + GuiImageData * keyMedium; + GuiImageData * keyMediumOver; + GuiImageData * keyLarge; + GuiImageData * keyLargeOver; + GuiSound * keySoundOver; + GuiSound * keySoundClick; + GuiTrigger * trigA; + GuiTrigger * trigB; }; //!On-screen keyboard -class GuiNumpad : public GuiWindow { -public: - GuiNumpad(char * t, u32 max); - ~GuiNumpad(); - void Update(GuiTrigger * t); - char kbtextstr[256]; -protected: - u32 kbtextmaxlen; - char keys[11]; - GuiText * kbText; - GuiImage * keyTextboxImg; +class GuiNumpad : public GuiWindow +{ + public: + GuiNumpad(char * t, u32 max); + ~GuiNumpad(); + void Update(GuiTrigger * t); + char kbtextstr[256]; + protected: + u32 kbtextmaxlen; + char keys[11]; + GuiText * kbText; + GuiImage * keyTextboxImg; - GuiText * keyBackText; - GuiImage * keyBackImg; - GuiImage * keyBackOverImg; - GuiButton * keyBack; - GuiText * keyClearText; - GuiImage * keyClearImg; - GuiImage * keyClearOverImg; - GuiButton * keyClear; - GuiButton * keyBtn[11]; - GuiImage * keyImg[11]; - GuiImage * keyImgOver[11]; - GuiText * keyTxt[11]; - GuiImageData * keyTextbox; - GuiImageData * keyMedium; - GuiImageData * keyMediumOver; - GuiSound * keySoundOver; - GuiSound * keySoundClick; - GuiTrigger * trigA; - GuiTrigger * trigB; + GuiText * keyBackText; + GuiImage * keyBackImg; + GuiImage * keyBackOverImg; + GuiButton * keyBack; + GuiText * keyClearText; + GuiImage * keyClearImg; + GuiImage * keyClearOverImg; + GuiButton * keyClear; + GuiButton * keyBtn[11]; + GuiImage * keyImg[11]; + GuiImage * keyImgOver[11]; + GuiText * keyTxt[11]; + GuiImageData * keyTextbox; + GuiImageData * keyMedium; + GuiImageData * keyMediumOver; + GuiSound * keySoundOver; + GuiSound * keySoundClick; + GuiTrigger * trigA; + GuiTrigger * trigB; }; typedef struct _optionlist { - int length; - char name[MAX_OPTIONS][60]; - char value[MAX_OPTIONS][30]; + int length; + char name[MAX_OPTIONS][60]; + char value[MAX_OPTIONS][30]; } OptionList; //!Display a list of menu options -class GuiOptionBrowser : public GuiElement { -public: - GuiOptionBrowser(int w, int h, OptionList * l, const u8 *imagebg, int scrollbar); - GuiOptionBrowser(int w, int h, OptionList * l, const char * themePath, const u8 *imagebg, int scrollbar, int start); - ~GuiOptionBrowser(); - void SetCol2Position(int x); - int FindMenuItem(int c, int d); - int GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void TriggerUpdate(); - void Update(GuiTrigger * t); - GuiText * optionVal[PAGESIZE]; -protected: - int selectedItem; - int listOffset; - bool listChanged; - OptionList * options; - int optionIndex[PAGESIZE]; - GuiButton * optionBtn[PAGESIZE]; - GuiText * optionTxt[PAGESIZE]; - GuiImage * optionBg[PAGESIZE]; +class GuiOptionBrowser : public GuiElement +{ + public: + GuiOptionBrowser(int w, int h, OptionList * l, const u8 *imagebg, int scrollbar); + GuiOptionBrowser(int w, int h, OptionList * l, const char * themePath, const u8 *imagebg, int scrollbar, int start); + ~GuiOptionBrowser(); + void SetCol2Position(int x); + int FindMenuItem(int c, int d); + int GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus(int f); + void Draw(); + void TriggerUpdate(); + void Update(GuiTrigger * t); + GuiText * optionVal[PAGESIZE]; + protected: + int selectedItem; + int listOffset; + bool listChanged; + OptionList * options; + int optionIndex[PAGESIZE]; + GuiButton * optionBtn[PAGESIZE]; + GuiText * optionTxt[PAGESIZE]; + GuiImage * optionBg[PAGESIZE]; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgOptionsImg; - GuiImage * bgOptionsOverImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowDownOverImg; - GuiImage * arrowUpImg; - GuiImage * arrowUpOverImg; - GuiImage * scrollbarBoxImg; - GuiImage * scrollbarBoxOverImg; + GuiImage * bgOptionsImg; + GuiImage * bgOptionsOverImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowDownOverImg; + GuiImage * arrowUpImg; + GuiImage * arrowUpOverImg; + GuiImage * scrollbarBoxImg; + GuiImage * scrollbarBoxOverImg; - GuiImageData * bgOptions; - GuiImageData * bgOptionsOver; - GuiImageData * bgOptionsEntry; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowDownOver; - GuiImageData * arrowUp; - GuiImageData * arrowUpOver; - GuiImageData * scrollbarBox; - GuiImageData * scrollbarBoxOver; + GuiImageData * bgOptions; + GuiImageData * bgOptionsOver; + GuiImageData * bgOptionsEntry; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowDownOver; + GuiImageData * arrowUp; + GuiImageData * arrowUpOver; + GuiImageData * scrollbarBox; + GuiImageData * scrollbarBoxOver; - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigB; - GuiTrigger * trigHeldA; + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigB; + GuiTrigger * trigHeldA; }; //!Display a list of files -class GuiFileBrowser : public GuiElement { -public: - GuiFileBrowser(int w, int h); - ~GuiFileBrowser(); - void DisableTriggerUpdate(bool set); - void ResetState(); - void SetFocus(int f); - void Draw(); - void TriggerUpdate(); - void Update(GuiTrigger * t); - GuiButton * fileList[PAGESIZE]; -protected: - int selectedItem; - bool listChanged; - bool triggerdisabled; +class GuiFileBrowser : public GuiElement +{ + public: + GuiFileBrowser(int w, int h); + ~GuiFileBrowser(); + void DisableTriggerUpdate(bool set); + void ResetState(); + void SetFocus(int f); + void Draw(); + void TriggerUpdate(); + void Update(GuiTrigger * t); + GuiButton * fileList[PAGESIZE]; + protected: + int selectedItem; + bool listChanged; + bool triggerdisabled; - GuiText * fileListText[PAGESIZE]; - GuiText * fileListTextOver[PAGESIZE]; - GuiImage * fileListBg[PAGESIZE]; - //GuiImage * fileListArchives[PAGESIZE]; - //GuiImage * fileListDefault[PAGESIZE]; - GuiImage * fileListFolder[PAGESIZE]; - //GuiImage * fileListGFX[PAGESIZE]; - //GuiImage * fileListPLS[PAGESIZE]; - //GuiImage * fileListSFX[PAGESIZE]; - //GuiImage * fileListTXT[PAGESIZE]; - //GuiImage * fileListXML[PAGESIZE]; + GuiText * fileListText[PAGESIZE]; + GuiText * fileListTextOver[PAGESIZE]; + GuiImage * fileListBg[PAGESIZE]; + //GuiImage * fileListArchives[PAGESIZE]; + //GuiImage * fileListDefault[PAGESIZE]; + GuiImage * fileListFolder[PAGESIZE]; + //GuiImage * fileListGFX[PAGESIZE]; + //GuiImage * fileListPLS[PAGESIZE]; + //GuiImage * fileListSFX[PAGESIZE]; + //GuiImage * fileListTXT[PAGESIZE]; + //GuiImage * fileListXML[PAGESIZE]; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgFileSelectionImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowUpImg; - GuiImage * scrollbarBoxImg; + GuiImage * bgFileSelectionImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowUpImg; + GuiImage * scrollbarBoxImg; - GuiImageData * bgFileSelection; - GuiImageData * bgFileSelectionEntry; - //GuiImageData * fileArchives; - //GuiImageData * fileDefault; - GuiImageData * fileFolder; - //GuiImageData * fileGFX; - //GuiImageData * filePLS; - //GuiImageData * fileSFX; - //GuiImageData * fileTXT; - //GuiImageData * fileXML; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowUp; - GuiImageData * scrollbarBox; + GuiImageData * bgFileSelection; + GuiImageData * bgFileSelectionEntry; + //GuiImageData * fileArchives; + //GuiImageData * fileDefault; + GuiImageData * fileFolder; + //GuiImageData * fileGFX; + //GuiImageData * filePLS; + //GuiImageData * fileSFX; + //GuiImageData * fileTXT; + //GuiImageData * fileXML; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowUp; + GuiImageData * scrollbarBox; - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigHeldA; + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigHeldA; }; #endif diff --git a/source/libwiigui/gui_button.cpp b/source/libwiigui/gui_button.cpp index bc2f2d18..40ee15c8 100644 --- a/source/libwiigui/gui_button.cpp +++ b/source/libwiigui/gui_button.cpp @@ -16,446 +16,512 @@ static int scrollison; * Constructor for the GuiButton class. */ -GuiButton::GuiButton(int w, int h) { - width = w; - height = h; - image = NULL; - imageOver = NULL; - imageHold = NULL; - imageClick = NULL; - icon = NULL; - iconOver = NULL; - iconHold = NULL; - iconClick = NULL; - toolTip = NULL; +GuiButton::GuiButton(int w, int h) +{ + width = w; + height = h; + image = NULL; + imageOver = NULL; + imageHold = NULL; + imageClick = NULL; + icon = NULL; + iconOver = NULL; + iconHold = NULL; + iconClick = NULL; + toolTip = NULL; - for (int i=0; i < 3; i++) { - label[i] = NULL; - labelOver[i] = NULL; - labelHold[i] = NULL; - labelClick[i] = NULL; - } + for(int i=0; i < 3; i++) + { + label[i] = NULL; + labelOver[i] = NULL; + labelHold[i] = NULL; + labelClick[i] = NULL; + } - soundOver = NULL; - soundHold = NULL; - soundClick = NULL; - selectable = true; - holdable = false; - clickable = true; - - time1 = time2 = 0; + soundOver = NULL; + soundHold = NULL; + soundClick = NULL; + selectable = true; + holdable = false; + clickable = true; + + time1 = time2 = 0; } -GuiButton::GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow) { - width = img->GetWidth(); - height = img->GetHeight(); - image = img; - image->SetParent(this); - imageOver = imgOver; - if (imageOver) imageOver->SetParent(this); - imageHold = NULL; - imageClick = NULL; - icon = NULL; - iconOver = NULL; - iconHold = NULL; - iconClick = NULL; - toolTip = NULL; - alignmentHor = hor; - alignmentVert = vert; - xoffset = x; - yoffset = y; - trigger[0] = trig; +GuiButton::GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow) +{ + width = img->GetWidth(); + height = img->GetHeight(); + image = img; + image->SetParent(this); + imageOver = imgOver; + if(imageOver) imageOver->SetParent(this); + imageHold = NULL; + imageClick = NULL; + icon = NULL; + iconOver = NULL; + iconHold = NULL; + iconClick = NULL; + toolTip = NULL; + alignmentHor = hor; + alignmentVert = vert; + xoffset = x; + yoffset = y; + trigger[0] = trig; - for (int i=0; i < 3; i++) { - label[i] = NULL; - labelOver[i] = NULL; - labelHold[i] = NULL; - labelClick[i] = NULL; - } + for(int i=0; i < 3; i++) + { + label[i] = NULL; + labelOver[i] = NULL; + labelHold[i] = NULL; + labelClick[i] = NULL; + } - soundOver = sndOver; - soundHold = NULL; - soundClick = sndClick; - selectable = true; - holdable = false; - clickable = true; + soundOver = sndOver; + soundHold = NULL; + soundClick = sndClick; + selectable = true; + holdable = false; + clickable = true; - if (grow==1) { - effectsOver |= EFFECT_SCALE; - effectAmountOver = 4; - effectTargetOver = 110; - } - time1 = time2 = 0; + if (grow==1){ + effectsOver |= EFFECT_SCALE; + effectAmountOver = 4; + effectTargetOver = 110; + } + time1 = time2 = 0; } -GuiButton::GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align) { - width = img->GetWidth(); - height = img->GetHeight(); - image = img; - image->SetParent(this); - imageOver = imgOver; - if (imageOver) imageOver->SetParent(this); - imageHold = NULL; - imageClick = NULL; - icon = NULL; - iconOver = NULL; - iconHold = NULL; - iconClick = NULL; - toolTip = NULL; - alignmentHor = hor; - alignmentVert = vert; - xoffset = x; - yoffset = y; - trigger[0] = trig; +GuiButton::GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align) +{ + width = img->GetWidth(); + height = img->GetHeight(); + image = img; + image->SetParent(this); + imageOver = imgOver; + if(imageOver) imageOver->SetParent(this); + imageHold = NULL; + imageClick = NULL; + icon = NULL; + iconOver = NULL; + iconHold = NULL; + iconClick = NULL; + toolTip = NULL; + alignmentHor = hor; + alignmentVert = vert; + xoffset = x; + yoffset = y; + trigger[0] = trig; - for (int i=0; i < 3; i++) { - label[i] = NULL; - labelOver[i] = NULL; - labelHold[i] = NULL; - labelClick[i] = NULL; - } + for(int i=0; i < 3; i++) + { + label[i] = NULL; + labelOver[i] = NULL; + labelHold[i] = NULL; + labelClick[i] = NULL; + } - soundOver = sndOver; - soundHold = NULL; - soundClick = sndClick; - selectable = true; - holdable = false; - clickable = true; + soundOver = sndOver; + soundHold = NULL; + soundClick = sndClick; + selectable = true; + holdable = false; + clickable = true; - if (grow==1) { - effectsOver |= EFFECT_SCALE; - effectAmountOver = 4; - effectTargetOver = 110; - } + if (grow==1) { + effectsOver |= EFFECT_SCALE; + effectAmountOver = 4; + effectTargetOver = 110; + } - toolTip = tt; - toolTip->SetParent(this); - toolTip->SetAlignment(h_align, v_align); - toolTip->SetPosition(ttx,tty); + toolTip = tt; + toolTip->SetParent(this); + toolTip->SetAlignment(h_align, v_align); + toolTip->SetPosition(ttx,tty); - time1 = time2 = 0; + time1 = time2 = 0; } /** * Destructor for the GuiButton class. */ -GuiButton::~GuiButton() { +GuiButton::~GuiButton() +{ } -void GuiButton::SetImage(GuiImage* img) { - LOCK(this); - image = img; - if (img) img->SetParent(this); +void GuiButton::SetImage(GuiImage* img) +{ + LOCK(this); + image = img; + if(img) img->SetParent(this); } -void GuiButton::SetImageOver(GuiImage* img) { - LOCK(this); - imageOver = img; - if (img) img->SetParent(this); +void GuiButton::SetImageOver(GuiImage* img) +{ + LOCK(this); + imageOver = img; + if(img) img->SetParent(this); } -void GuiButton::SetImageHold(GuiImage* img) { - LOCK(this); - imageHold = img; - if (img) img->SetParent(this); +void GuiButton::SetImageHold(GuiImage* img) +{ + LOCK(this); + imageHold = img; + if(img) img->SetParent(this); } -void GuiButton::SetImageClick(GuiImage* img) { - LOCK(this); - imageClick = img; - if (img) img->SetParent(this); +void GuiButton::SetImageClick(GuiImage* img) +{ + LOCK(this); + imageClick = img; + if(img) img->SetParent(this); } -void GuiButton::SetIcon(GuiImage* img) { - LOCK(this); - icon = img; - if (img) img->SetParent(this); +void GuiButton::SetIcon(GuiImage* img) +{ + LOCK(this); + icon = img; + if(img) img->SetParent(this); } -void GuiButton::SetIconOver(GuiImage* img) { - LOCK(this); - iconOver = img; - if (img) img->SetParent(this); +void GuiButton::SetIconOver(GuiImage* img) +{ + LOCK(this); + iconOver = img; + if(img) img->SetParent(this); } -void GuiButton::SetIconHold(GuiImage* img) { - LOCK(this); - iconHold = img; - if (img) img->SetParent(this); +void GuiButton::SetIconHold(GuiImage* img) +{ + LOCK(this); + iconHold = img; + if(img) img->SetParent(this); } -void GuiButton::SetIconClick(GuiImage* img) { - LOCK(this); - iconClick = img; - if (img) img->SetParent(this); +void GuiButton::SetIconClick(GuiImage* img) +{ + LOCK(this); + iconClick = img; + if(img) img->SetParent(this); } -void GuiButton::SetLabel(GuiText* txt, int n) { - LOCK(this); - label[n] = txt; - if (txt) txt->SetParent(this); +void GuiButton::SetLabel(GuiText* txt, int n) +{ + LOCK(this); + label[n] = txt; + if(txt) txt->SetParent(this); } -void GuiButton::SetLabelOver(GuiText* txt, int n) { - LOCK(this); - labelOver[n] = txt; - if (txt) txt->SetParent(this); +void GuiButton::SetLabelOver(GuiText* txt, int n) +{ + LOCK(this); + labelOver[n] = txt; + if(txt) txt->SetParent(this); } -void GuiButton::SetLabelHold(GuiText* txt, int n) { - LOCK(this); - labelHold[n] = txt; - if (txt) txt->SetParent(this); +void GuiButton::SetLabelHold(GuiText* txt, int n) +{ + LOCK(this); + labelHold[n] = txt; + if(txt) txt->SetParent(this); } -void GuiButton::SetLabelClick(GuiText* txt, int n) { - LOCK(this); - labelClick[n] = txt; - if (txt) txt->SetParent(this); +void GuiButton::SetLabelClick(GuiText* txt, int n) +{ + LOCK(this); + labelClick[n] = txt; + if(txt) txt->SetParent(this); } -void GuiButton::SetSoundOver(GuiSound * snd) { - LOCK(this); - soundOver = snd; +void GuiButton::SetSoundOver(GuiSound * snd) +{ + LOCK(this); + soundOver = snd; } -void GuiButton::SetSoundHold(GuiSound * snd) { - LOCK(this); - soundHold = snd; +void GuiButton::SetSoundHold(GuiSound * snd) +{ + LOCK(this); + soundHold = snd; } -void GuiButton::SetSoundClick(GuiSound * snd) { - LOCK(this); - soundClick = snd; +void GuiButton::SetSoundClick(GuiSound * snd) +{ + LOCK(this); + soundClick = snd; } -void GuiButton::SetToolTip(GuiTooltip* tt, int x, int y, int h_align, int v_align) { - LOCK(this); - if (tt) { - toolTip = tt; - toolTip->SetParent(this); - toolTip->SetAlignment(h_align, v_align); - toolTip->SetPosition(x,y); +void GuiButton::SetToolTip(GuiTooltip* tt, int x, int y, int h_align, int v_align) +{ + LOCK(this); + if(tt) + { + toolTip = tt; + toolTip->SetParent(this); + toolTip->SetAlignment(h_align, v_align); + toolTip->SetPosition(x,y); - } + } } -void GuiButton::RemoveToolTip() { - LOCK(this); - toolTip = NULL; +void GuiButton::RemoveToolTip() +{ + LOCK(this); + toolTip = NULL; } -void GuiButton::RemoveSoundOver() { - LOCK(this); - soundOver = NULL; +void GuiButton::RemoveSoundOver() +{ + LOCK(this); + soundOver = NULL; } -void GuiButton::RemoveSoundClick() { - LOCK(this); - soundClick = NULL; +void GuiButton::RemoveSoundClick() +{ + LOCK(this); + soundClick = NULL; } -void GuiButton::SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4) { - if (image) { - image->xx1 = XX1; - image->yy1 = YY1; - image->xx2 = XX2; - image->yy2 = YY2; - image->xx3 = XX3; - image->yy3 = YY3; - image->xx4 = XX4; - image->yy4 = YY4; - } +void GuiButton::SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4) +{ + if(image) + { + image->xx1 = XX1; + image->yy1 = YY1; + image->xx2 = XX2; + image->yy2 = YY2; + image->xx3 = XX3; + image->yy3 = YY3; + image->xx4 = XX4; + image->yy4 = YY4; + } } -void GuiButton::SetSkew(int *skew) { - if (image) - image->SetSkew(skew); +void GuiButton::SetSkew(int *skew) +{ + if(image) + image->SetSkew(skew); } /** * Draw the button on screen */ -void GuiButton::Draw() { - LOCK(this); - if (!this->IsVisible()) - return; +void GuiButton::Draw() +{ + LOCK(this); + if(!this->IsVisible()) + return; - // draw image - if ((state == STATE_SELECTED || state == STATE_HELD) && imageOver) - imageOver->Draw(); - else if (image) - image->Draw(); - // draw icon - if ((state == STATE_SELECTED || state == STATE_HELD) && iconOver) - iconOver->Draw(); - else if (icon) - icon->Draw(); - // draw text - for (int i=0; i<3; i++) { - if ((state == STATE_SELECTED || state == STATE_HELD) && labelOver[i]) - labelOver[i]->Draw(); - else if (label[i]) - label[i]->Draw(); - } + // draw image + if((state == STATE_SELECTED || state == STATE_HELD) && imageOver) + imageOver->Draw(); + else if(image) + image->Draw(); + // draw icon + if((state == STATE_SELECTED || state == STATE_HELD) && iconOver) + iconOver->Draw(); + else if(icon) + icon->Draw(); + // draw text + for(int i=0; i<3; i++) + { + if((state == STATE_SELECTED || state == STATE_HELD) && labelOver[i]) + labelOver[i]->Draw(); + else if(label[i]) + label[i]->Draw(); + } - this->UpdateEffects(); + this->UpdateEffects(); } -void GuiButton::DrawTooltip() { - LOCK(this); - if (this->IsVisible() && state == STATE_SELECTED && toolTip) { - if (time2 == 0) { - time(&time1); - time2 = time1; - } - if (time1 != 0) // timer läuft - time(&time1); +void GuiButton::DrawTooltip() +{ + LOCK(this); + if(this->IsVisible() && state == STATE_SELECTED && toolTip) + { + if (time2 == 0) + { + time(&time1); + time2 = time1; + } + if(time1 != 0) // timer läuft + time(&time1); - if (time1 == 0 || difftime(time1, time2) >= 2) { - if (time1 != 0) // timer gerade abgelaufen - toolTip->SetEffect(EFFECT_FADE, 20); - time1 = 0; - toolTip->Draw(); - return; + if(time1 == 0 || difftime(time1, time2) >= 2) + { + if(time1 != 0) // timer gerade abgelaufen + toolTip->SetEffect(EFFECT_FADE, 20); + time1 = 0; + toolTip->Draw(); + return; } - } else { - if (time2 != 0 && time1 == 0) // timer abgelaufen, gerade DESELECT - if (toolTip) toolTip->SetEffect(EFFECT_FADE, -20); - time2 = 0; - } - if (toolTip && toolTip->GetEffect()) - toolTip->Draw(); + } + else + { + if(time2 != 0 && time1 == 0) // timer abgelaufen, gerade DESELECT + if(toolTip) toolTip->SetEffect(EFFECT_FADE, -20); + time2 = 0; + } + if(toolTip && toolTip->GetEffect()) + toolTip->Draw(); } -void GuiButton::ScrollIsOn(int f) { - LOCK(this); +void GuiButton::ScrollIsOn(int f) +{ + LOCK(this); scrollison = f; } -void GuiButton::Update(GuiTrigger * t) { - LOCK(this); - if (!this->IsVisible() || state == STATE_CLICKED || state == STATE_DISABLED || !t) - return; - else if (parentElement && parentElement->GetState() == STATE_DISABLED) - return; +void GuiButton::Update(GuiTrigger * t) +{ + LOCK(this); + if(!this->IsVisible() || state == STATE_CLICKED || state == STATE_DISABLED || !t) + return; + else if(parentElement && parentElement->GetState() == STATE_DISABLED) + return; -#ifdef HW_RVL - // cursor - if (t->wpad.ir.valid) { - if (this->IsInside(t->wpad.ir.x, t->wpad.ir.y)) { - if (state == STATE_DEFAULT) { // we weren't on the button before! - if (scrollison == 0) { - this->SetState(STATE_SELECTED, t->chan); - } + #ifdef HW_RVL + // cursor + if(t->wpad.ir.valid) + { + if(this->IsInside(t->wpad.ir.x, t->wpad.ir.y)) + { + if(state == STATE_DEFAULT) // we weren't on the button before! + { + if(scrollison == 0) { + this->SetState(STATE_SELECTED, t->chan); + } - if (this->Rumble() && scrollison == 0) - rumbleRequest[t->chan] = 1; + if(this->Rumble() && scrollison == 0) + rumbleRequest[t->chan] = 1; - if (soundOver && scrollison == 0) - soundOver->Play(); + if(soundOver && scrollison == 0) + soundOver->Play(); - if (effectsOver && !effects && scrollison == 0) { - // initiate effects - effects = effectsOver; - effectAmount = effectAmountOver; - effectTarget = effectTargetOver; - } - } - } else { - if (state == STATE_SELECTED && (stateChan == t->chan || stateChan == -1)) - this->ResetState(); + if(effectsOver && !effects && scrollison == 0) + { + // initiate effects + effects = effectsOver; + effectAmount = effectAmountOver; + effectTarget = effectTargetOver; + } + } + } + else + { + if(state == STATE_SELECTED && (stateChan == t->chan || stateChan == -1)) + this->ResetState(); - if (effectTarget == effectTargetOver && effectAmount == effectAmountOver) { - // initiate effects (in reverse) - effects = effectsOver; - effectAmount = -effectAmountOver; - effectTarget = 100; - } - } - } -#else + if(effectTarget == effectTargetOver && effectAmount == effectAmountOver) + { + // initiate effects (in reverse) + effects = effectsOver; + effectAmount = -effectAmountOver; + effectTarget = 100; + } + } + } + #else + + if(state == STATE_SELECTED && (stateChan == t->chan || stateChan == -1)) + this->ResetState(); - if (state == STATE_SELECTED && (stateChan == t->chan || stateChan == -1)) - this->ResetState(); + if(effectTarget == effectTargetOver && effectAmount == effectAmountOver) + { + // initiate effects (in reverse) + effects = effectsOver; + effectAmount = -effectAmountOver; + effectTarget = 100; + } + + + #endif - if (effectTarget == effectTargetOver && effectAmount == effectAmountOver) { - // initiate effects (in reverse) - effects = effectsOver; - effectAmount = -effectAmountOver; - effectTarget = 100; - } + // button triggers + if(this->IsClickable() && scrollison == 0) + { + s32 wm_btns, wm_btns_trig, cc_btns, cc_btns_trig; + for(int i=0; i<6; i++) + { + if(trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) + { + // higher 16 bits only (wiimote) + wm_btns = t->wpad.btns_d << 16; + wm_btns_trig = trigger[i]->wpad.btns_d << 16; + // lower 16 bits only (classic controller) + cc_btns = t->wpad.btns_d >> 16; + cc_btns_trig = trigger[i]->wpad.btns_d >> 16; -#endif + if( + ((t->wpad.btns_d > 0 && + wm_btns == wm_btns_trig) || + (cc_btns == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC)) || + (t->pad.btns_d == trigger[i]->pad.btns_d && t->pad.btns_d > 0)) + { + if(t->chan == stateChan || stateChan == -1) + { + if(state == STATE_SELECTED) + { + this->SetState(STATE_CLICKED, t->chan); - // button triggers - if (this->IsClickable() && scrollison == 0) { - s32 wm_btns, wm_btns_trig, cc_btns, cc_btns_trig; - for (int i=0; i<6; i++) { - if (trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) { - // higher 16 bits only (wiimote) - wm_btns = t->wpad.btns_d << 16; - wm_btns_trig = trigger[i]->wpad.btns_d << 16; + if(soundClick) + soundClick->Play(); + } + else if(trigger[i]->type == TRIGGER_BUTTON_ONLY) + { + this->SetState(STATE_CLICKED, t->chan); + if(soundClick) + soundClick->Play(); + } + else if(trigger[i]->type == TRIGGER_BUTTON_ONLY_IN_FOCUS && + parentElement->IsFocused()) + { + this->SetState(STATE_CLICKED, t->chan); + if(soundClick) + soundClick->Play(); + } + } + } + } + } + } - // lower 16 bits only (classic controller) - cc_btns = t->wpad.btns_d >> 16; - cc_btns_trig = trigger[i]->wpad.btns_d >> 16; + if(this->IsHoldable()) + { + bool held = false; + s32 wm_btns, wm_btns_h, wm_btns_trig, cc_btns, cc_btns_h, cc_btns_trig; - if ( - ((t->wpad.btns_d > 0 && - wm_btns == wm_btns_trig) || - (cc_btns == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC)) || - (t->pad.btns_d == trigger[i]->pad.btns_d && t->pad.btns_d > 0)) { - if (t->chan == stateChan || stateChan == -1) { - if (state == STATE_SELECTED) { - this->SetState(STATE_CLICKED, t->chan); + for(int i=0; i<6; i++) + { + if(trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) + { + // higher 16 bits only (wiimote) + wm_btns = t->wpad.btns_d << 16; + wm_btns_h = t->wpad.btns_h << 16; + wm_btns_trig = trigger[i]->wpad.btns_h << 16; - if (soundClick) - soundClick->Play(); - } else if (trigger[i]->type == TRIGGER_BUTTON_ONLY) { - this->SetState(STATE_CLICKED, t->chan); - if (soundClick) - soundClick->Play(); - } else if (trigger[i]->type == TRIGGER_BUTTON_ONLY_IN_FOCUS && - parentElement->IsFocused()) { - this->SetState(STATE_CLICKED, t->chan); - if (soundClick) - soundClick->Play(); - } - } - } - } - } - } + // lower 16 bits only (classic controller) + cc_btns = t->wpad.btns_d >> 16; + cc_btns_h = t->wpad.btns_h >> 16; + cc_btns_trig = trigger[i]->wpad.btns_h >> 16; - if (this->IsHoldable()) { - bool held = false; - s32 wm_btns, wm_btns_h, wm_btns_trig, cc_btns, cc_btns_h, cc_btns_trig; + if( + ((t->wpad.btns_d > 0 && + wm_btns == wm_btns_trig) || + (cc_btns == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC)) || + (t->pad.btns_d == trigger[i]->pad.btns_h && t->pad.btns_d > 0)) + { + if(trigger[i]->type == TRIGGER_HELD && state == STATE_SELECTED && + (t->chan == stateChan || stateChan == -1)) + this->SetState(STATE_CLICKED, t->chan); + } - for (int i=0; i<6; i++) { - if (trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) { - // higher 16 bits only (wiimote) - wm_btns = t->wpad.btns_d << 16; - wm_btns_h = t->wpad.btns_h << 16; - wm_btns_trig = trigger[i]->wpad.btns_h << 16; + if( + ((t->wpad.btns_h > 0 && + wm_btns_h == wm_btns_trig) || + (cc_btns_h == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC)) || + (t->pad.btns_h == trigger[i]->pad.btns_h && t->pad.btns_h > 0)) + { + if(trigger[i]->type == TRIGGER_HELD) + held = true; + } - // lower 16 bits only (classic controller) - cc_btns = t->wpad.btns_d >> 16; - cc_btns_h = t->wpad.btns_h >> 16; - cc_btns_trig = trigger[i]->wpad.btns_h >> 16; + if(!held && state == STATE_HELD && stateChan == t->chan) + { + this->ResetState(); + } + else if(held && state == STATE_CLICKED && stateChan == t->chan) + { + this->SetState(STATE_HELD, t->chan); + } + } + } + } - if ( - ((t->wpad.btns_d > 0 && - wm_btns == wm_btns_trig) || - (cc_btns == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC)) || - (t->pad.btns_d == trigger[i]->pad.btns_h && t->pad.btns_d > 0)) { - if (trigger[i]->type == TRIGGER_HELD && state == STATE_SELECTED && - (t->chan == stateChan || stateChan == -1)) - this->SetState(STATE_CLICKED, t->chan); - } - - if ( - ((t->wpad.btns_h > 0 && - wm_btns_h == wm_btns_trig) || - (cc_btns_h == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC)) || - (t->pad.btns_h == trigger[i]->pad.btns_h && t->pad.btns_h > 0)) { - if (trigger[i]->type == TRIGGER_HELD) - held = true; - } - - if (!held && state == STATE_HELD && stateChan == t->chan) { - this->ResetState(); - } else if (held && state == STATE_CLICKED && stateChan == t->chan) { - this->SetState(STATE_HELD, t->chan); - } - } - } - } - - if (updateCB) - updateCB(this); + if(updateCB) + updateCB(this); } diff --git a/source/libwiigui/gui_customoptionbrowser.cpp b/source/libwiigui/gui_customoptionbrowser.cpp index e6883b22..5d9f0111 100644 --- a/source/libwiigui/gui_customoptionbrowser.cpp +++ b/source/libwiigui/gui_customoptionbrowser.cpp @@ -18,337 +18,374 @@ #define GAMESELECTSIZE 30 #define OPTION_LIST_PADDING PAGESIZE -customOptionList::customOptionList(int Size) { - name = value = NULL; - size = 0; - SetSize(Size==0 ? PAGESIZE : Size); - length = Size; - changed = false; +customOptionList::customOptionList(int Size) +{ + name = value = NULL; + size = 0; + SetSize(Size==0 ? PAGESIZE : Size); + length = Size; + changed = false; } -customOptionList::~customOptionList() { - for (int i = 0; i < size; i++) { - free(name[i]); - free(value[i]); - } - delete [] name; - delete [] value; +customOptionList::~customOptionList() +{ + for (int i = 0; i < size; i++) + { + free(name[i]); + free(value[i]); + } + delete [] name; + delete [] value; } -void customOptionList::SetLength(int Length) { //set number of lines - if (Length < 0 || Length == length) return; +void customOptionList::SetLength(int Length) //set number of lines +{ + if(Length < 0 || Length == length) return; + + if(Length > size) + SetSize(Length + OPTION_LIST_PADDING); + if(Length < length) + { + for (int i = Length; i < length; i++) + { + free(name[i]); // clear unused + name[i] = NULL; + free(value[i]); + value[i] = NULL; + } + } + length = Length; + changed = true; +} +void customOptionList::SetSize(int Size) //set number of lines +{ + if(Size < 0 || Size == size) return; + + if(Size > size) + { + char **newName = new char *[Size]; + char **newValue = new char *[Size]; + int i; + for (i = 0; i < size; i++) + { + newName[i] = name[i]; // copy + newValue[i] = value[i]; + } + for (; i < Size; i++) + { + newName[i] = NULL; // fill rest with NULL + newValue[i] = NULL; + } + delete [] name; + name = newName; // set new + delete [] value; + value = newValue; + size = Size; + } +} +void customOptionList::SetName(int i, const char *format, ...) +{ + if(i >= length) SetLength(i+1); - if (Length > size) - SetSize(Length + OPTION_LIST_PADDING); - if (Length < length) { - for (int i = Length; i < length; i++) { - free(name[i]); // clear unused - name[i] = NULL; - free(value[i]); - value[i] = NULL; - } - } - length = Length; - changed = true; + if(i >= 0 && i < length) + { + if(name[i]) free(name[i]); + name[i] = 0; + va_list va; + va_start(va, format); + vasprintf(&name[i], format, va); + va_end(va); + changed = true; + } } -void customOptionList::SetSize(int Size) { //set number of lines - if (Size < 0 || Size == size) return; +void customOptionList::SetValue(int i, const char *format, ...) +{ + if(i >= length) SetLength(i+1); - if (Size > size) { - char **newName = new char *[Size]; - char **newValue = new char *[Size]; - int i; - for (i = 0; i < size; i++) { - newName[i] = name[i]; // copy - newValue[i] = value[i]; - } - for (; i < Size; i++) { - newName[i] = NULL; // fill rest with NULL - newValue[i] = NULL; - } - delete [] name; - name = newName; // set new - delete [] value; - value = newValue; - size = Size; - } + if(i >= 0 && i < length) + { + char *tmp=0; + va_list va; + va_start(va, format); + vasprintf(&tmp, format, va); + va_end(va); + + if(tmp) + { + if(value[i] && !strcmp(tmp, value[i])) + free(tmp); + else + { + free(value[i]); + value[i] = tmp; + changed = true; + } + } + } } -void customOptionList::SetName(int i, const char *format, ...) { - if (i >= length) SetLength(i+1); - - if (i >= 0 && i < length) { - if (name[i]) free(name[i]); - name[i] = 0; - va_list va; - va_start(va, format); - vasprintf(&name[i], format, va); - va_end(va); - changed = true; - } -} -void customOptionList::SetValue(int i, const char *format, ...) { - if (i >= length) SetLength(i+1); - - if (i >= 0 && i < length) { - char *tmp=0; - va_list va; - va_start(va, format); - vasprintf(&tmp, format, va); - va_end(va); - - if (tmp) { - if (value[i] && !strcmp(tmp, value[i])) - free(tmp); - else { - free(value[i]); - value[i] = tmp; - changed = true; - } - } - } -} -void customOptionList::Clear(bool OnlyValue/*=false*/) { - for (int i = 0; i < size; i++) { - if (!OnlyValue) { - free(name[i]); - name[i] = NULL; - } - free(value[i]); - value[i] = NULL; - } - changed = true; +void customOptionList::Clear(bool OnlyValue/*=false*/) +{ + for (int i = 0; i < size; i++) + { + if(!OnlyValue) + { + free(name[i]); + name[i] = NULL; + } + free(value[i]); + value[i] = NULL; + } + changed = true; } /** * Constructor for the GuiCustomOptionBrowser class. */ -GuiCustomOptionBrowser::GuiCustomOptionBrowser(int w, int h, customOptionList * l, const char *themePath, const char *custombg, const u8 *imagebg, int scrollon,int col2) { - width = w; - height = h; - options = l; - size = PAGESIZE; - scrollbaron = scrollon; - selectable = true; - listOffset = this->FindMenuItem(-1, 1); - selectedItem = 0; - focus = 1; // allow focus - coL2 = col2; - char imgPath[100]; +GuiCustomOptionBrowser::GuiCustomOptionBrowser(int w, int h, customOptionList * l, const char *themePath, const char *custombg, const u8 *imagebg, int scrollon,int col2) +{ + width = w; + height = h; + options = l; + size = PAGESIZE; + scrollbaron = scrollon; + selectable = true; + listOffset = this->FindMenuItem(-1, 1); + selectedItem = 0; + focus = 1; // allow focus + coL2 = col2; + char imgPath[100]; - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigHeldA = new GuiTrigger; + trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); + btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - snprintf(imgPath, sizeof(imgPath), "%s%s", themePath, custombg); - bgOptions = new GuiImageData(imgPath, imagebg); + snprintf(imgPath, sizeof(imgPath), "%s%s", themePath, custombg); + bgOptions = new GuiImageData(imgPath, imagebg); - bgOptionsImg = new GuiImage(bgOptions); - bgOptionsImg->SetParent(this); - bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + bgOptionsImg = new GuiImage(bgOptions); + bgOptionsImg->SetParent(this); + bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); - bgOptionsEntry = new GuiImageData(imgPath, bg_options_entry_png); + snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); + bgOptionsEntry = new GuiImageData(imgPath, bg_options_entry_png); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", themePath); - scrollbar = new GuiImageData(imgPath, scrollbar_png); - scrollbarImg = new GuiImage(scrollbar); - scrollbarImg->SetParent(this); - scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarImg->SetPosition(0, 4); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", themePath); + scrollbar = new GuiImageData(imgPath, scrollbar_png); + scrollbarImg = new GuiImage(scrollbar); + scrollbarImg->SetParent(this); + scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + scrollbarImg->SetPosition(0, 4); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", themePath); - arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownOverImg = new GuiImage(arrowDownOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); - arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpOverImg = new GuiImage(arrowUpOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); - scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); - scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", themePath); + arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownImg = new GuiImage(arrowDown); + arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownOverImg = new GuiImage(arrowDownOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); + arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpImg = new GuiImage(arrowUp); + arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpOverImg = new GuiImage(arrowUpOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); + scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); + scrollbarBoxImg = new GuiImage(scrollbarBox); + scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); + scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetImageOver(arrowUpOverImg); - arrowUpBtn->SetImageHold(arrowUpOverImg); - arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - arrowUpBtn->SetPosition(width/2-18+7,-18); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetTrigger(trigA); - arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); + arrowUpBtn->SetParent(this); + arrowUpBtn->SetImage(arrowUpImg); + arrowUpBtn->SetImageOver(arrowUpOverImg); + arrowUpBtn->SetImageHold(arrowUpOverImg); + arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + arrowUpBtn->SetPosition(width/2-18+7,-18); + arrowUpBtn->SetSelectable(false); + arrowUpBtn->SetTrigger(trigA); + arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowUpBtn->SetSoundClick(btnSoundClick); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetImageOver(arrowDownOverImg); - arrowDownBtn->SetImageHold(arrowDownOverImg); - arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(width/2-18+7,18); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetTrigger(trigA); - arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowDownBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); + arrowDownBtn->SetParent(this); + arrowDownBtn->SetImage(arrowDownImg); + arrowDownBtn->SetImageOver(arrowDownOverImg); + arrowDownBtn->SetImageHold(arrowDownOverImg); + arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + arrowDownBtn->SetPosition(width/2-18+7,18); + arrowDownBtn->SetSelectable(false); + arrowDownBtn->SetTrigger(trigA); + arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowDownBtn->SetSoundClick(btnSoundClick); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); - scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); - scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); - scrollbarBoxBtn->SetMinY(0); - scrollbarBoxBtn->SetMaxY(height-30); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); + scrollbarBoxBtn->SetParent(this); + scrollbarBoxBtn->SetImage(scrollbarBoxImg); + scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); + scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); + scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + scrollbarBoxBtn->SetSelectable(false); + scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); + scrollbarBoxBtn->SetMinY(0); + scrollbarBoxBtn->SetMaxY(height-30); + scrollbarBoxBtn->SetHoldable(true); + scrollbarBoxBtn->SetTrigger(trigHeldA); - optionIndex = new int[size]; - optionVal = new GuiText * [size]; - optionValOver = new GuiText * [size]; - optionBtn = new GuiButton * [size]; - optionTxt = new GuiText * [size]; - optionBg = new GuiImage * [size]; + optionIndex = new int[size]; + optionVal = new GuiText * [size]; + optionValOver = new GuiText * [size]; + optionBtn = new GuiButton * [size]; + optionTxt = new GuiText * [size]; + optionBg = new GuiImage * [size]; - for (int i=0; i < size; i++) { - optionTxt[i] = new GuiText(options->GetName(i), 20, THEME.settingstext); - optionTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionTxt[i]->SetPosition(24,0); - optionTxt[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), GuiText::DOTTED); + for(int i=0; i < size; i++) + { + optionTxt[i] = new GuiText(options->GetName(i), 20, THEME.settingstext); + optionTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + optionTxt[i]->SetPosition(24,0); + optionTxt[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), GuiText::DOTTED); - optionBg[i] = new GuiImage(bgOptionsEntry); + optionBg[i] = new GuiImage(bgOptionsEntry); - optionVal[i] = new GuiText(NULL, 20, THEME.settingstext); - optionVal[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + optionVal[i] = new GuiText(NULL, 20, THEME.settingstext); + optionVal[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionValOver[i] = new GuiText(NULL, 20, THEME.settingstext); - optionValOver[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + optionValOver[i] = new GuiText(NULL, 20, THEME.settingstext); + optionValOver[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionBtn[i] = new GuiButton(width-28,GAMESELECTSIZE); - optionBtn[i]->SetParent(this); - optionBtn[i]->SetLabel(optionTxt[i], 0); - optionBtn[i]->SetLabel(optionVal[i], 1); - optionBtn[i]->SetLabelOver(optionValOver[i], 1); - optionBtn[i]->SetImageOver(optionBg[i]); - optionBtn[i]->SetPosition(10,GAMESELECTSIZE*i+4); - optionBtn[i]->SetRumble(false); - optionBtn[i]->SetTrigger(trigA); - optionBtn[i]->SetSoundClick(btnSoundClick); + optionBtn[i] = new GuiButton(width-28,GAMESELECTSIZE); + optionBtn[i]->SetParent(this); + optionBtn[i]->SetLabel(optionTxt[i], 0); + optionBtn[i]->SetLabel(optionVal[i], 1); + optionBtn[i]->SetLabelOver(optionValOver[i], 1); + optionBtn[i]->SetImageOver(optionBg[i]); + optionBtn[i]->SetPosition(10,GAMESELECTSIZE*i+4); + optionBtn[i]->SetRumble(false); + optionBtn[i]->SetTrigger(trigA); + optionBtn[i]->SetSoundClick(btnSoundClick); - } - UpdateListEntries(); + } + UpdateListEntries(); } /** * Destructor for the GuiCustomOptionBrowser class. */ -GuiCustomOptionBrowser::~GuiCustomOptionBrowser() { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; - delete scrollbarImg; - delete arrowDownImg; - delete arrowDownOverImg; - delete arrowUpImg; - delete arrowUpOverImg; - delete scrollbarBoxImg; - delete scrollbarBoxOverImg; - delete scrollbar; - delete arrowDown; - delete arrowDownOver; - delete arrowUp; - delete arrowUpOver; - delete scrollbarBox; - delete scrollbarBoxOver; +GuiCustomOptionBrowser::~GuiCustomOptionBrowser() +{ + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; + delete scrollbarImg; + delete arrowDownImg; + delete arrowDownOverImg; + delete arrowUpImg; + delete arrowUpOverImg; + delete scrollbarBoxImg; + delete scrollbarBoxOverImg; + delete scrollbar; + delete arrowDown; + delete arrowDownOver; + delete arrowUp; + delete arrowUpOver; + delete scrollbarBox; + delete scrollbarBoxOver; - delete bgOptionsImg; - delete bgOptions; - delete bgOptionsEntry; + delete bgOptionsImg; + delete bgOptions; + delete bgOptionsEntry; - delete trigA; - delete trigHeldA; - delete btnSoundClick; + delete trigA; + delete trigHeldA; + delete btnSoundClick; - for (int i = 0; i < size; i++) { - delete optionTxt[i]; - delete optionVal[i]; - delete optionValOver[i]; - delete optionBg[i]; - delete optionBtn[i]; - } - delete [] optionIndex; - delete [] optionVal; - delete [] optionValOver; - delete [] optionBtn; - delete [] optionTxt; - delete [] optionBg; + for(int i = 0; i < size; i++) + { + delete optionTxt[i]; + delete optionVal[i]; + delete optionValOver[i]; + delete optionBg[i]; + delete optionBtn[i]; + } + delete [] optionIndex; + delete [] optionVal; + delete [] optionValOver; + delete [] optionBtn; + delete [] optionTxt; + delete [] optionBg; } -void GuiCustomOptionBrowser::SetFocus(int f) { - LOCK(this); - focus = f; +void GuiCustomOptionBrowser::SetFocus(int f) +{ + LOCK(this); + focus = f; - for (int i = 0; i < size; i++) - optionBtn[i]->ResetState(); + for(int i = 0; i < size; i++) + optionBtn[i]->ResetState(); - if (f == 1) - optionBtn[selectedItem]->SetState(STATE_SELECTED); + if(f == 1) + optionBtn[selectedItem]->SetState(STATE_SELECTED); } -void GuiCustomOptionBrowser::ResetState() { - LOCK(this); - if (state != STATE_DISABLED) { - state = STATE_DEFAULT; - stateChan = -1; - } +void GuiCustomOptionBrowser::ResetState() +{ + LOCK(this); + if(state != STATE_DISABLED) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for (int i = 0; i < size; i++) { - optionBtn[i]->ResetState(); - } + for(int i = 0; i < size; i++) + { + optionBtn[i]->ResetState(); + } } -int GuiCustomOptionBrowser::GetClickedOption() { - int found = -1; - for (int i = 0; i < size; i++) { - if (optionBtn[i]->GetState() == STATE_CLICKED) { - optionBtn[i]->SetState(STATE_SELECTED); - found = optionIndex[i]; - break; - } - } - return found; +int GuiCustomOptionBrowser::GetClickedOption() +{ + int found = -1; + for(int i = 0; i < size; i++) + { + if(optionBtn[i]->GetState() == STATE_CLICKED) + { + optionBtn[i]->SetState(STATE_SELECTED); + found = optionIndex[i]; + break; + } + } + return found; } -int GuiCustomOptionBrowser::GetSelectedOption() { - int found = -1; - for (int i = 0; i < size; i++) { - if (optionBtn[i]->GetState() == STATE_SELECTED) { - found = optionIndex[i]; - break; - } - } - return found; +int GuiCustomOptionBrowser::GetSelectedOption() +{ + int found = -1; + for(int i = 0; i < size; i++) + { + if(optionBtn[i]->GetState() == STATE_SELECTED) + { + found = optionIndex[i]; + break; + } + } + return found; } -void GuiCustomOptionBrowser::SetClickable(bool enable) { - for (int i = 0; i < size; i++) { - optionBtn[i]->SetClickable(enable); - } +void GuiCustomOptionBrowser::SetClickable(bool enable) +{ + for(int i = 0; i < size; i++) + { + optionBtn[i]->SetClickable(enable); + } } -void GuiCustomOptionBrowser::SetScrollbar(int enable) { - scrollbaron = enable; +void GuiCustomOptionBrowser::SetScrollbar(int enable) +{ + scrollbaron = enable; } -void GuiCustomOptionBrowser::SetOffset(int optionnumber) { - listOffset = optionnumber; - selectedItem = optionnumber; +void GuiCustomOptionBrowser::SetOffset(int optionnumber) +{ + listOffset = optionnumber; + selectedItem = optionnumber; } /**************************************************************************** @@ -357,247 +394,294 @@ void GuiCustomOptionBrowser::SetOffset(int optionnumber) { * Help function to find the next visible menu item on the list ***************************************************************************/ -int GuiCustomOptionBrowser::FindMenuItem(int currentItem, int direction) { - int nextItem = currentItem + direction; +int GuiCustomOptionBrowser::FindMenuItem(int currentItem, int direction) +{ + int nextItem = currentItem + direction; - if (nextItem < 0 || nextItem >= options->GetLength()) - return -1; + if(nextItem < 0 || nextItem >= options->GetLength()) + return -1; - if (strlen(options->GetName(nextItem)) > 0) - return nextItem; - else - return FindMenuItem(nextItem, direction); + if(strlen(options->GetName(nextItem)) > 0) + return nextItem; + else + return FindMenuItem(nextItem, direction); } /** * Draw the button on screen */ -void GuiCustomOptionBrowser::Draw() { - LOCK(this); - if (!this->IsVisible()) - return; +void GuiCustomOptionBrowser::Draw() +{ + LOCK(this); + if(!this->IsVisible()) + return; - bgOptionsImg->Draw(); + bgOptionsImg->Draw(); - int next = listOffset; + int next = listOffset; - for (int i=0; i < size; i++) { - if (next >= 0) { - optionBtn[i]->Draw(); - next = this->FindMenuItem(next, 1); - } else - break; - } + for(int i=0; i < size; i++) + { + if(next >= 0) + { + optionBtn[i]->Draw(); + next = this->FindMenuItem(next, 1); + } + else + break; + } - if (scrollbaron == 1) { - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); - } - this->UpdateEffects(); + if(scrollbaron == 1) { + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); + } + this->UpdateEffects(); } -void GuiCustomOptionBrowser::UpdateListEntries() { - scrollbaron = options->GetLength() > size; - if (listOffset<0) listOffset = this->FindMenuItem(-1, 1); - int next = listOffset; +void GuiCustomOptionBrowser::UpdateListEntries() +{ + scrollbaron = options->GetLength() > size; + if(listOffset<0) listOffset = this->FindMenuItem(-1, 1); + int next = listOffset; - int maxNameWidth = 0; - for (int i=0; i < size; i++) { - if (next >= 0) { - if (optionBtn[i]->GetState() == STATE_DISABLED) { - optionBtn[i]->SetVisible(true); - optionBtn[i]->SetState(STATE_DEFAULT); - } + int maxNameWidth = 0; + for(int i=0; i < size; i++) + { + if(next >= 0) + { + if(optionBtn[i]->GetState() == STATE_DISABLED) + { + optionBtn[i]->SetVisible(true); + optionBtn[i]->SetState(STATE_DEFAULT); + } - optionTxt[i]->SetText(options->GetName(next)); - if (maxNameWidth < optionTxt[i]->GetTextWidth()) - maxNameWidth = optionTxt[i]->GetTextWidth(); - optionVal[i]->SetText(options->GetValue(next)); - optionValOver[i]->SetText(options->GetValue(next)); + optionTxt[i]->SetText(options->GetName(next)); + if(maxNameWidth < optionTxt[i]->GetTextWidth()) + maxNameWidth = optionTxt[i]->GetTextWidth(); + optionVal[i]->SetText(options->GetValue(next)); + optionValOver[i]->SetText(options->GetValue(next)); - optionIndex[i] = next; - next = this->FindMenuItem(next, 1); - } else { - optionBtn[i]->SetVisible(false); - optionBtn[i]->SetState(STATE_DISABLED); - } - } - if (coL2 < (24+maxNameWidth+16)) - coL2 = 24+maxNameWidth+16; - for (int i=0; i < size; i++) { - if (optionBtn[i]->GetState() != STATE_DISABLED) { - optionVal[i]->SetPosition(coL2,0); - optionVal[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), GuiText::DOTTED); + optionIndex[i] = next; + next = this->FindMenuItem(next, 1); + } + else + { + optionBtn[i]->SetVisible(false); + optionBtn[i]->SetState(STATE_DISABLED); + } + } + if(coL2 < (24+maxNameWidth+16)) + coL2 = 24+maxNameWidth+16; + for(int i=0; i < size; i++) + { + if(optionBtn[i]->GetState() != STATE_DISABLED) + { + optionVal[i]->SetPosition(coL2,0); + optionVal[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), GuiText::DOTTED); - optionValOver[i]->SetPosition(coL2,0); - optionValOver[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), GuiText::SCROLL); - } - } + optionValOver[i]->SetPosition(coL2,0); + optionValOver[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), GuiText::SCROLL); + } + } } -void GuiCustomOptionBrowser::Update(GuiTrigger * t) { - LOCK(this); - int next, prev, lang = options->GetLength(); +void GuiCustomOptionBrowser::Update(GuiTrigger * t) +{ + LOCK(this); + int next, prev, lang = options->GetLength(); - if (state == STATE_DISABLED || !t) - return; + if(state == STATE_DISABLED || !t) + return; - if (options->IsChanged()) { - coL2 = 0; - UpdateListEntries(); - } - int old_listOffset = listOffset; + if(options->IsChanged()) { + coL2 = 0; + UpdateListEntries(); + } + int old_listOffset = listOffset; - if (scrollbaron == 1) { - // update the location of the scroll box based on the position in the option list - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); - } + if (scrollbaron == 1) + { + // update the location of the scroll box based on the position in the option list + arrowUpBtn->Update(t); + arrowDownBtn->Update(t); + scrollbarBoxBtn->Update(t); + } - next = listOffset; + next = listOffset; - u32 buttonshold = ButtonsHold(); + u32 buttonshold = ButtonsHold(); - if (buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN) { - for (int i=0; i < size; i++) { - if (next >= 0) - next = this->FindMenuItem(next, 1); + if(buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN) { + for(int i=0; i < size; i++) + { + if(next >= 0) + next = this->FindMenuItem(next, 1); - if (focus) { - if (i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED) { - optionBtn[i]->ResetState(); - } else if (i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) { - optionBtn[selectedItem]->SetState(STATE_SELECTED); - } - } + if(focus) + { + if(i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED) { + optionBtn[i]->ResetState(); + } else if(i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) { + optionBtn[selectedItem]->SetState(STATE_SELECTED); + } + } - optionBtn[i]->Update(t); + optionBtn[i]->Update(t); - if (optionBtn[i]->GetState() == STATE_SELECTED) { - selectedItem = i; - } - } - } + if(optionBtn[i]->GetState() == STATE_SELECTED) + { + selectedItem = i; + } + } + } - // pad/joystick navigation - if (!focus) - return; // skip navigation + // pad/joystick navigation + if(!focus) + return; // skip navigation - if (t->Down()) { - next = this->FindMenuItem(optionIndex[selectedItem], 1); + if(t->Down()) + { + next = this->FindMenuItem(optionIndex[selectedItem], 1); - if (next >= 0) { - if (selectedItem == size-1) { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } else if (optionBtn[selectedItem+1]->IsVisible()) { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - } - } else if (t->Up()) { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); + if(next >= 0) + { + if(selectedItem == size-1) + { + // move list down by 1 + listOffset = this->FindMenuItem(listOffset, 1); + } + else if(optionBtn[selectedItem+1]->IsVisible()) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); + selectedItem++; + } + } + } + else if(t->Up()) + { + prev = this->FindMenuItem(optionIndex[selectedItem], -1); - if (prev >= 0) { - if (selectedItem == 0) { - // move list up by 1 - listOffset = prev; - } else { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - } - } + if(prev >= 0) + { + if(selectedItem == 0) + { + // move list up by 1 + listOffset = prev; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); + selectedItem--; + } + } + } - if (scrollbaron == 1) { - if (arrowDownBtn->GetState() == STATE_CLICKED || - arrowDownBtn->GetState() == STATE_HELD) { + if (scrollbaron == 1) + { + if (arrowDownBtn->GetState() == STATE_CLICKED || + arrowDownBtn->GetState() == STATE_HELD) + { - next = this->FindMenuItem(optionIndex[selectedItem], 1); + next = this->FindMenuItem(optionIndex[selectedItem], 1); - if (next >= 0) { - if (selectedItem == size-1) { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } else if (optionBtn[selectedItem+1]->IsVisible()) { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - scrollbarBoxBtn->Draw(); - usleep(35000); - } - if (buttonshold != WPAD_BUTTON_A) { - arrowDownBtn->ResetState(); - } - } else if (arrowUpBtn->GetState() == STATE_CLICKED || - arrowUpBtn->GetState() == STATE_HELD) { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); + if(next >= 0) + { + if(selectedItem == size-1) + { + // move list down by 1 + listOffset = this->FindMenuItem(listOffset, 1); + } + else if(optionBtn[selectedItem+1]->IsVisible()) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); + selectedItem++; + } + scrollbarBoxBtn->Draw(); + usleep(35000); + } + if (buttonshold != WPAD_BUTTON_A) { + arrowDownBtn->ResetState(); + } + } + else if(arrowUpBtn->GetState() == STATE_CLICKED || + arrowUpBtn->GetState() == STATE_HELD) + { + prev = this->FindMenuItem(optionIndex[selectedItem], -1); - if (prev >= 0) { - if (selectedItem == 0) { - // move list up by 1 - listOffset = prev; - } else { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - scrollbarBoxBtn->Draw(); - usleep(35000); - } - if (buttonshold != WPAD_BUTTON_A) { - arrowUpBtn->ResetState(); - } - } + if(prev >= 0) + { + if(selectedItem == 0) + { + // move list up by 1 + listOffset = prev; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); + selectedItem--; + } + scrollbarBoxBtn->Draw(); + usleep(35000); + } + if (buttonshold != WPAD_BUTTON_A) { + arrowUpBtn->ResetState(); + } + } - if (scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && options->GetLength() > size) { - scrollbarBoxBtn->SetPosition(width/2-18+7,0); + if(scrollbarBoxBtn->GetState() == STATE_HELD && + scrollbarBoxBtn->GetStateChan() == t->chan && + t->wpad.ir.valid && options->GetLength() > size) + { + scrollbarBoxBtn->SetPosition(width/2-18+7,0); - int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); + int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); - listOffset = (position * lang)/180 - selectedItem; + listOffset = (position * lang)/180 - selectedItem; - if (listOffset <= 0) { - listOffset = 0; - selectedItem = 0; - } else if (listOffset+size >= lang) { - listOffset = lang-size; - selectedItem = size-1; - } - } - int positionbar = 237*(listOffset + selectedItem) / lang; + if(listOffset <= 0) { + listOffset = 0; + selectedItem = 0; + } else if(listOffset+size >= lang) { + listOffset = lang-size; + selectedItem = size-1; + } + } + int positionbar = 237*(listOffset + selectedItem) / lang; - if (positionbar > 216) - positionbar = 216; - scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); + if(positionbar > 216) + positionbar = 216; + scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); - if (t->Right()) { - if (listOffset < lang && lang > size) { - listOffset =listOffset+ size; - if (listOffset+size >= lang) - listOffset = lang-size; - } - } else if (t->Left()) { - if (listOffset > 0) { - listOffset =listOffset- size; - if (listOffset < 0) - listOffset = 0; - } - } - } + if(t->Right()) + { + if(listOffset < lang && lang > size) + { + listOffset =listOffset+ size; + if(listOffset+size >= lang) + listOffset = lang-size; + } + } + else if(t->Left()) + { + if(listOffset > 0) + { + listOffset =listOffset- size; + if(listOffset < 0) + listOffset = 0; + } + } + } - if (old_listOffset != listOffset) - UpdateListEntries(); + if(old_listOffset != listOffset) + UpdateListEntries(); - if (updateCB) - updateCB(this); + if(updateCB) + updateCB(this); } diff --git a/source/libwiigui/gui_customoptionbrowser.h b/source/libwiigui/gui_customoptionbrowser.h index 306f4977..8bc8d176 100644 --- a/source/libwiigui/gui_customoptionbrowser.h +++ b/source/libwiigui/gui_customoptionbrowser.h @@ -1,97 +1,94 @@ #include "gui.h" class customOptionList { -public: - customOptionList(int Size); - ~customOptionList(); - void SetLength(int Length); - void SetName(int i, const char *format, ...) __attribute__((format (printf, 3, 4))); - const char *GetName(int i) { - if (i >= 0 && i < length && name[i]) - return name[i]; - else - return ""; - } - void SetValue(int i, const char *format, ...) __attribute__((format (printf, 3, 4))); - const char *GetValue(int i) { - if (i >= 0 && i < length && value[i]) - return value[i]; - else - return ""; - } - void Clear(bool OnlyValue=false); - int GetLength() { - return length; - } - bool IsChanged() { - bool ret = changed; - changed = false; - return ret; - } -private: - void SetSize(int Size); - int size; - char ** name; - char ** value; - int length; - bool changed; + public: + customOptionList(int Size); + ~customOptionList(); + void SetLength(int Length); + void SetName(int i, const char *format, ...) __attribute__((format (printf, 3, 4))); + const char *GetName(int i) + { + if(i >= 0 && i < length && name[i]) + return name[i]; + else + return ""; + } + void SetValue(int i, const char *format, ...) __attribute__((format (printf, 3, 4))); + const char *GetValue(int i) + { + if(i >= 0 && i < length && value[i]) + return value[i]; + else + return ""; + } + void Clear(bool OnlyValue=false); + int GetLength() { return length; } + bool IsChanged() { bool ret = changed; changed = false; return ret;} + private: + void SetSize(int Size); + int size; + char ** name; + char ** value; + int length; + bool changed; }; //!Display a list of menu options -class GuiCustomOptionBrowser : public GuiElement { -public: - GuiCustomOptionBrowser(int w, int h, customOptionList * l, const char * themePath, const char *custombg, const u8 *imagebg, int scrollbar, int col2); - ~GuiCustomOptionBrowser(); - int FindMenuItem(int c, int d); - int GetClickedOption(); - int GetSelectedOption(); - void SetClickable(bool enable); - void SetScrollbar(int enable); - void SetOffset(int optionnumber); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); -protected: - void UpdateListEntries(); - int selectedItem; - int listOffset; - int size; - int coL2; - int scrollbaron; +class GuiCustomOptionBrowser : public GuiElement +{ + public: + GuiCustomOptionBrowser(int w, int h, customOptionList * l, const char * themePath, const char *custombg, const u8 *imagebg, int scrollbar, int col2); + ~GuiCustomOptionBrowser(); + int FindMenuItem(int c, int d); + int GetClickedOption(); + int GetSelectedOption(); + void SetClickable(bool enable); + void SetScrollbar(int enable); + void SetOffset(int optionnumber); + void ResetState(); + void SetFocus(int f); + void Draw(); + void Update(GuiTrigger * t); + protected: + void UpdateListEntries(); + int selectedItem; + int listOffset; + int size; + int coL2; + int scrollbaron; - customOptionList * options; - int * optionIndex; - GuiButton ** optionBtn; - GuiText ** optionTxt; - GuiText ** optionVal; - GuiText ** optionValOver; - GuiImage ** optionBg; + customOptionList * options; + int * optionIndex; + GuiButton ** optionBtn; + GuiText ** optionTxt; + GuiText ** optionVal; + GuiText ** optionValOver; + GuiImage ** optionBg; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgOptionsImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowDownOverImg; - GuiImage * arrowUpImg; - GuiImage * arrowUpOverImg; - GuiImage * scrollbarBoxImg; - GuiImage * scrollbarBoxOverImg; + GuiImage * bgOptionsImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowDownOverImg; + GuiImage * arrowUpImg; + GuiImage * arrowUpOverImg; + GuiImage * scrollbarBoxImg; + GuiImage * scrollbarBoxOverImg; - GuiImageData * bgOptions; - GuiImageData * bgOptionsEntry; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowDownOver; - GuiImageData * arrowUp; - GuiImageData * arrowUpOver; - GuiImageData * scrollbarBox; - GuiImageData * scrollbarBoxOver; + GuiImageData * bgOptions; + GuiImageData * bgOptionsEntry; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowDownOver; + GuiImageData * arrowUp; + GuiImageData * arrowUpOver; + GuiImageData * scrollbarBox; + GuiImageData * scrollbarBoxOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigHeldA; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigHeldA; }; diff --git a/source/libwiigui/gui_diskcover.cpp b/source/libwiigui/gui_diskcover.cpp index aa1151b7..7e40c1cb 100644 --- a/source/libwiigui/gui_diskcover.cpp +++ b/source/libwiigui/gui_diskcover.cpp @@ -1,66 +1,78 @@ #include "gui_diskcover.h" -GuiDiskCover::GuiDiskCover() { - deg_beta=0.0; - eff_step=0; +GuiDiskCover::GuiDiskCover() +{ + deg_beta=0.0; + eff_step=0; // spin_angle = 0; - spin_speedup = 1.0; - spin_up = false; + spin_speedup = 1.0; + spin_up = false; } -GuiDiskCover::GuiDiskCover(GuiImageData *Disk) : GuiImage(Disk) { - deg_beta=0.0; - eff_step=0; +GuiDiskCover::GuiDiskCover(GuiImageData *Disk) : GuiImage(Disk) +{ + deg_beta=0.0; + eff_step=0; // spin_angle = 0; - spin_speedup = 1.0; - spin_up = false; + spin_speedup = 1.0; + spin_up = false; } -GuiDiskCover::~GuiDiskCover() { +GuiDiskCover::~GuiDiskCover() +{ } -void GuiDiskCover::SetBeta(f32 beta) { - deg_beta=beta; +void GuiDiskCover::SetBeta(f32 beta) +{ + deg_beta=beta; } -void GuiDiskCover::SetBetaRotateEffect(f32 beta, u16 step) { - eff_beta = beta/(f32)step; - eff_step = step; +void GuiDiskCover::SetBetaRotateEffect(f32 beta, u16 step) +{ + eff_beta = beta/(f32)step; + eff_step = step; } -bool GuiDiskCover::GetBetaRotateEffect() { - return eff_step != 0; +bool GuiDiskCover::GetBetaRotateEffect() +{ + return eff_step != 0; } -void GuiDiskCover::SetSpin(bool Up) { - spin_up = Up; +void GuiDiskCover::SetSpin(bool Up) +{ + spin_up = Up; } void Menu_DrawDiskCover(f32 xpos, f32 ypos, f32 zpos, u16 width, u16 height, u16 distance,u8 data[], - f32 deg_alpha, f32 deg_beta, f32 scaleX, f32 scaleY, u8 alpha, bool shadow); + f32 deg_alpha, f32 deg_beta, f32 scaleX, f32 scaleY, u8 alpha, bool shadow); void Menu_DrawDiskCoverShadow(f32 xpos, f32 ypos, f32 zpos, u16 width, u16 height, u16 distance,u8 data[], - f32 deg_alpha, f32 deg_beta, f32 scaleX, f32 scaleY, u8 alpha, bool shadow); + f32 deg_alpha, f32 deg_beta, f32 scaleX, f32 scaleY, u8 alpha, bool shadow); -void GuiDiskCover::Draw() { - LOCK(this); - if (!image || !this->IsVisible()) - return; - float currScale = this->GetScale(); +void GuiDiskCover::Draw() +{ + LOCK(this); + if(!image || !this->IsVisible()) + return; + float currScale = this->GetScale(); // Menu_DrawDiskCoverShadow(this->GetLeft(), this->GetTop(), 190, width, height, 40, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, this->GetAlpha(), true); - Menu_DrawDiskCover(this->GetLeft(), this->GetTop(), 50, width, height, 55, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, 64, true); - Menu_DrawDiskCover(this->GetLeft(), this->GetTop(), 50, width, height, 55, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, this->GetAlpha(), false); + Menu_DrawDiskCover(this->GetLeft(), this->GetTop(), 50, width, height, 55, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, 64, true); + Menu_DrawDiskCover(this->GetLeft(), this->GetTop(), 50, width, height, 55, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, this->GetAlpha(), false); - if (eff_step) { - deg_beta += eff_beta; - eff_step--; - } - GuiImage::imageangle += spin_speedup; - while (GuiImage::imageangle >= 360.0) GuiImage::imageangle -= 360.0; - - if (spin_up) { - if (spin_speedup < 11) // speed up - spin_speedup += 0.20; - } else { - if (spin_speedup > 1) - spin_speedup -=0.05; //slow down - } - - this->UpdateEffects(); + if(eff_step) + { + deg_beta += eff_beta; + eff_step--; + } + GuiImage::imageangle += spin_speedup; + while(GuiImage::imageangle >= 360.0) GuiImage::imageangle -= 360.0; + + if(spin_up) + { + if (spin_speedup < 11) // speed up + spin_speedup += 0.20; + } + else + { + if (spin_speedup > 1) + spin_speedup -=0.05; //slow down + } + + this->UpdateEffects(); } diff --git a/source/libwiigui/gui_diskcover.h b/source/libwiigui/gui_diskcover.h index 7bb0c4d2..09ad7fe8 100644 --- a/source/libwiigui/gui_diskcover.h +++ b/source/libwiigui/gui_diskcover.h @@ -4,25 +4,26 @@ #include "gui.h" -class GuiDiskCover : public GuiImage { +class GuiDiskCover : public GuiImage +{ public: - GuiDiskCover(); - GuiDiskCover(GuiImageData * img); - ~GuiDiskCover(); - void SetBeta(f32 beta); - void SetBetaRotateEffect(f32 beta, u16 Step); - bool GetBetaRotateEffect(); - - void SetSpin(bool Up); - void Draw(); + GuiDiskCover(); + GuiDiskCover(GuiImageData * img); + ~GuiDiskCover(); + void SetBeta(f32 beta); + void SetBetaRotateEffect(f32 beta, u16 Step); + bool GetBetaRotateEffect(); + + void SetSpin(bool Up); + void Draw(); private: - f32 deg_beta; - f32 eff_beta; - u16 eff_step; - + f32 deg_beta; + f32 eff_beta; + u16 eff_step; + // f32 spin_angle; - f32 spin_speedup; - bool spin_up; + f32 spin_speedup; + bool spin_up; }; diff --git a/source/libwiigui/gui_element.cpp b/source/libwiigui/gui_element.cpp index b6610c7a..e566ea3a 100644 --- a/source/libwiigui/gui_element.cpp +++ b/source/libwiigui/gui_element.cpp @@ -15,109 +15,116 @@ */ //mutex_t GuiElement::mutex = LWP_MUTEX_NULL; mutex_t GuiElement::_lock_mutex = LWP_MUTEX_NULL; -GuiElement::GuiElement() { - xoffset = 0; - yoffset = 0; - zoffset = 0; - xmin = 0; - xmax = 0; - ymin = 0; - ymax = 0; - width = 0; - height = 0; - alpha = 255; - scale = 1; - state = STATE_DEFAULT; - stateChan = -1; - trigger[0] = NULL; - trigger[1] = NULL; - trigger[2] = NULL; - trigger[3] = NULL; - trigger[4] = NULL; - trigger[5] = NULL; - parentElement = NULL; - rumble = true; - selectable = false; - clickable = false; - holdable = false; - visible = true; - focus = -1; // cannot be focused - updateCB = NULL; - yoffsetDyn = 0; - xoffsetDyn = 0; - yoffsetDynFloat = 0; - alphaDyn = -1; - scaleDyn = 1; - effects = 0; - effectAmount = 0; - effectTarget = 0; - effectsOver = 0; - effectAmountOver = 0; - effectTargetOver = 0; - frequency = 0.0f; - changervar = 0; - degree = -90.0f; - circleamount = 360.0f; - Radius = 150; - angleDyn = 0.0f; - anglespeed = 0.0f; +GuiElement::GuiElement() +{ + xoffset = 0; + yoffset = 0; + zoffset = 0; + xmin = 0; + xmax = 0; + ymin = 0; + ymax = 0; + width = 0; + height = 0; + alpha = 255; + scale = 1; + state = STATE_DEFAULT; + stateChan = -1; + trigger[0] = NULL; + trigger[1] = NULL; + trigger[2] = NULL; + trigger[3] = NULL; + trigger[4] = NULL; + trigger[5] = NULL; + parentElement = NULL; + rumble = true; + selectable = false; + clickable = false; + holdable = false; + visible = true; + focus = -1; // cannot be focused + updateCB = NULL; + yoffsetDyn = 0; + xoffsetDyn = 0; + yoffsetDynFloat = 0; + alphaDyn = -1; + scaleDyn = 1; + effects = 0; + effectAmount = 0; + effectTarget = 0; + effectsOver = 0; + effectAmountOver = 0; + effectTargetOver = 0; + frequency = 0.0f; + changervar = 0; + degree = -90.0f; + circleamount = 360.0f; + Radius = 150; + angleDyn = 0.0f; + anglespeed = 0.0f; - // default alignment - align to top left - alignmentVert = ALIGN_TOP; - alignmentHor = ALIGN_LEFT; + // default alignment - align to top left + alignmentVert = ALIGN_TOP; + alignmentHor = ALIGN_LEFT; // if(mutex == LWP_MUTEX_NULL) LWP_MutexInit(&mutex, true); - if (_lock_mutex == LWP_MUTEX_NULL) LWP_MutexInit(&_lock_mutex, true); - _lock_thread = LWP_THREAD_NULL; - _lock_count = 0; - _lock_queue = LWP_TQUEUE_NULL; + if(_lock_mutex == LWP_MUTEX_NULL) LWP_MutexInit(&_lock_mutex, true); + _lock_thread = LWP_THREAD_NULL; + _lock_count = 0; + _lock_queue = LWP_TQUEUE_NULL; } /** * Destructor for the GuiElement class. */ -GuiElement::~GuiElement() { +GuiElement::~GuiElement() +{ // LWP_MutexDestroy(mutex); } -void GuiElement::SetParent(GuiElement * e) { - LOCK(this); - parentElement = e; +void GuiElement::SetParent(GuiElement * e) +{ + LOCK(this); + parentElement = e; } -GuiElement * GuiElement::GetParent() { - return parentElement; +GuiElement * GuiElement::GetParent() +{ + return parentElement; } /** * Get the left position of the GuiElement. * @see SetLeft() * @return Left position in pixel. */ -int GuiElement::GetLeft() { - int x = 0; - int pWidth = 0; - int pLeft = 0; +int GuiElement::GetLeft() +{ + int x = 0; + int pWidth = 0; + int pLeft = 0; - if (parentElement) { - pWidth = parentElement->GetWidth(); - pLeft = parentElement->GetLeft(); - } + if(parentElement) + { + pWidth = parentElement->GetWidth(); + pLeft = parentElement->GetLeft(); + } - if (effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE)) - pLeft += xoffsetDyn; + if(effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE)) + pLeft += xoffsetDyn; - switch (alignmentHor) { - case ALIGN_LEFT: - x = pLeft; - break; - case ALIGN_CENTRE: - x = pLeft + (pWidth/2) - (width/2); - break; - case ALIGN_RIGHT: - x = pLeft + pWidth - width; - break; - } - return x + xoffset; + switch(alignmentHor) + { + case ALIGN_LEFT: + x = pLeft; + break; + case ALIGN_CENTRE: + x = pLeft + (pWidth/2) - (width/2); + break; + case ALIGN_RIGHT: + x = pLeft + pWidth - width; + break; + } + return x + xoffset; } /** @@ -125,68 +132,79 @@ int GuiElement::GetLeft() { * @see SetTop() * @return Top position in pixel. */ -int GuiElement::GetTop() { - int y = 0; - int pHeight = 0; - int pTop = 0; +int GuiElement::GetTop() +{ + int y = 0; + int pHeight = 0; + int pTop = 0; - if (parentElement) { - pHeight = parentElement->GetHeight(); - pTop = parentElement->GetTop(); - } + if(parentElement) + { + pHeight = parentElement->GetHeight(); + pTop = parentElement->GetTop(); + } - if (effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE)) - pTop += yoffsetDyn; + if(effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE)) + pTop += yoffsetDyn; - switch (alignmentVert) { - case ALIGN_TOP: - y = pTop; - break; - case ALIGN_MIDDLE: - y = pTop + (pHeight/2) - (height/2); - break; - case ALIGN_BOTTOM: - y = pTop + pHeight - height; - break; - } - return y + yoffset; + switch(alignmentVert) + { + case ALIGN_TOP: + y = pTop; + break; + case ALIGN_MIDDLE: + y = pTop + (pHeight/2) - (height/2); + break; + case ALIGN_BOTTOM: + y = pTop + pHeight - height; + break; + } + return y + yoffset; } -void GuiElement::SetMinX(int x) { - LOCK(this); - xmin = x; +void GuiElement::SetMinX(int x) +{ + LOCK(this); + xmin = x; } -int GuiElement::GetMinX() { - return xmin; +int GuiElement::GetMinX() +{ + return xmin; } -void GuiElement::SetMaxX(int x) { - LOCK(this); - xmax = x; +void GuiElement::SetMaxX(int x) +{ + LOCK(this); + xmax = x; } -int GuiElement::GetMaxX() { - return xmax; +int GuiElement::GetMaxX() +{ + return xmax; } -void GuiElement::SetMinY(int y) { - LOCK(this); - ymin = y; +void GuiElement::SetMinY(int y) +{ + LOCK(this); + ymin = y; } -int GuiElement::GetMinY() { - return ymin; +int GuiElement::GetMinY() +{ + return ymin; } -void GuiElement::SetMaxY(int y) { - LOCK(this); - ymax = y; +void GuiElement::SetMaxY(int y) +{ + LOCK(this); + ymax = y; } -int GuiElement::GetMaxY() { - return ymax; +int GuiElement::GetMaxY() +{ + return ymax; } /** @@ -194,8 +212,9 @@ int GuiElement::GetMaxY() { * @see SetWidth() * @return Width of the GuiElement. */ -int GuiElement::GetWidth() { - return width; +int GuiElement::GetWidth() +{ + return width; } /** @@ -203,8 +222,9 @@ int GuiElement::GetWidth() { * @see SetHeight() * @return Height of the GuiElement. */ -int GuiElement::GetHeight() { - return height; +int GuiElement::GetHeight() +{ + return height; } /** @@ -214,11 +234,12 @@ int GuiElement::GetHeight() { * @see SetWidth() * @see SetHeight() */ -void GuiElement::SetSize(int w, int h) { - LOCK(this); +void GuiElement::SetSize(int w, int h) +{ + LOCK(this); - width = w; - height = h; + width = w; + height = h; } /** @@ -226,8 +247,9 @@ void GuiElement::SetSize(int w, int h) { * @see SetVisible() * @return true if visible, false otherwise. */ -bool GuiElement::IsVisible() { - return visible; +bool GuiElement::IsVisible() +{ + return visible; } /** @@ -235,421 +257,493 @@ bool GuiElement::IsVisible() { * @param[in] Visible Set to true to show GuiElement. * @see IsVisible() */ -void GuiElement::SetVisible(bool v) { - LOCK(this); - visible = v; +void GuiElement::SetVisible(bool v) +{ + LOCK(this); + visible = v; } -void GuiElement::SetAlpha(int a) { - LOCK(this); - alpha = a; +void GuiElement::SetAlpha(int a) +{ + LOCK(this); + alpha = a; } -int GuiElement::GetAlpha() { - int a; +int GuiElement::GetAlpha() +{ + int a; - if (alphaDyn >= 0) - a = alphaDyn; - else - a = alpha; + if(alphaDyn >= 0) + a = alphaDyn; + else + a = alpha; - if (parentElement) - a *= parentElement->GetAlpha()/255.0; + if(parentElement) + a *= parentElement->GetAlpha()/255.0; - return a; + return a; } -float GuiElement::GetAngleDyn() { +float GuiElement::GetAngleDyn() +{ float a = 0.0; - if (angleDyn) - a = angleDyn; + if(angleDyn) + a = angleDyn; - if (parentElement && !angleDyn) - a = parentElement->GetAngleDyn(); + if(parentElement && !angleDyn) + a = parentElement->GetAngleDyn(); return a; } -void GuiElement::SetScale(float s) { - LOCK(this); - scale = s; +void GuiElement::SetScale(float s) +{ + LOCK(this); + scale = s; } -float GuiElement::GetScale() { - float s = scale * scaleDyn; +float GuiElement::GetScale() +{ + float s = scale * scaleDyn; - if (parentElement) - s *= parentElement->GetScale(); + if(parentElement) + s *= parentElement->GetScale(); - return s; + return s; } -int GuiElement::GetState() { - return state; +int GuiElement::GetState() +{ + return state; } -int GuiElement::GetStateChan() { - return stateChan; +int GuiElement::GetStateChan() +{ + return stateChan; } -void GuiElement::SetState(int s, int c) { - LOCK(this); - state = s; - stateChan = c; +void GuiElement::SetState(int s, int c) +{ + LOCK(this); + state = s; + stateChan = c; } -void GuiElement::ResetState() { - LOCK(this); - if (state != STATE_DISABLED) { - state = STATE_DEFAULT; - stateChan = -1; - } +void GuiElement::ResetState() +{ + LOCK(this); + if(state != STATE_DISABLED) + { + state = STATE_DEFAULT; + stateChan = -1; + } } -void GuiElement::SetClickable(bool c) { - LOCK(this); - clickable = c; +void GuiElement::SetClickable(bool c) +{ + LOCK(this); + clickable = c; } -void GuiElement::SetSelectable(bool s) { - LOCK(this); - selectable = s; +void GuiElement::SetSelectable(bool s) +{ + LOCK(this); + selectable = s; } -void GuiElement::SetHoldable(bool d) { - LOCK(this); - holdable = d; +void GuiElement::SetHoldable(bool d) +{ + LOCK(this); + holdable = d; } -bool GuiElement::IsSelectable() { - if (state == STATE_DISABLED || state == STATE_CLICKED) - return false; - else - return selectable; +bool GuiElement::IsSelectable() +{ + if(state == STATE_DISABLED || state == STATE_CLICKED) + return false; + else + return selectable; } -bool GuiElement::IsClickable() { - if (state == STATE_DISABLED || - state == STATE_CLICKED || - state == STATE_HELD) - return false; - else - return clickable; +bool GuiElement::IsClickable() +{ + if(state == STATE_DISABLED || + state == STATE_CLICKED || + state == STATE_HELD) + return false; + else + return clickable; } -bool GuiElement::IsHoldable() { - if (state == STATE_DISABLED) - return false; - else - return holdable; +bool GuiElement::IsHoldable() +{ + if(state == STATE_DISABLED) + return false; + else + return holdable; } -void GuiElement::SetFocus(int f) { - LOCK(this); - focus = f; +void GuiElement::SetFocus(int f) +{ + LOCK(this); + focus = f; } -int GuiElement::IsFocused() { - return focus; +int GuiElement::IsFocused() +{ + return focus; } -void GuiElement::SetTrigger(GuiTrigger * t) { - LOCK(this); - if (!trigger[0]) - trigger[0] = t; - else if (!trigger[1]) - trigger[1] = t; - else if (!trigger[2]) - trigger[2] = t; - else if (!trigger[3]) - trigger[3] = t; - else if (!trigger[4]) - trigger[4] = t; - else if (!trigger[5]) - trigger[5] = t; - else // both were assigned, so we'll just overwrite the first one - trigger[0] = t; +void GuiElement::SetTrigger(GuiTrigger * t) +{ + LOCK(this); + if(!trigger[0]) + trigger[0] = t; + else if(!trigger[1]) + trigger[1] = t; + else if(!trigger[2]) + trigger[2] = t; + else if(!trigger[3]) + trigger[3] = t; + else if(!trigger[4]) + trigger[4] = t; + else if(!trigger[5]) + trigger[5] = t; + else // both were assigned, so we'll just overwrite the first one + trigger[0] = t; } -void GuiElement::SetTrigger(u8 i, GuiTrigger * t) { - LOCK(this); - trigger[i] = t; +void GuiElement::SetTrigger(u8 i, GuiTrigger * t) +{ + LOCK(this); + trigger[i] = t; } -void GuiElement::RemoveTrigger(u8 i) { - LOCK(this); - trigger[i] = NULL; +void GuiElement::RemoveTrigger(u8 i) +{ + LOCK(this); + trigger[i] = NULL; } -bool GuiElement::Rumble() { - return rumble; +bool GuiElement::Rumble() +{ + return rumble; } -void GuiElement::SetRumble(bool r) { - LOCK(this); - rumble = r; +void GuiElement::SetRumble(bool r) +{ + LOCK(this); + rumble = r; } -int GuiElement::GetEffect() { - LOCK(this); - return effects; +int GuiElement::GetEffect() +{ + LOCK(this); + return effects; +} + +int GuiElement::GetEffectOnOver() +{ + LOCK(this); + return effectsOver; } -int GuiElement::GetEffectOnOver() { - LOCK(this); - return effectsOver; -} - -float GuiElement::GetFrequency() { - LOCK(this); - return frequency; +float GuiElement::GetFrequency() +{ + LOCK(this); + return frequency; } void GuiElement::SetEffect(int eff, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y) { - if (eff & EFFECT_GOROUND) { + if(eff & EFFECT_GOROUND) { xoffsetDyn = 0; //!position of circle in x yoffsetDyn = 0; //!position of circle in y Radius = r; //!radius of the circle degree = startdegree; //!for example -90 (°) to start at top of circle circleamount = circles; //!circleamoutn in degrees for example 360 for 1 circle angleDyn = 0.0f; //!this is used by the code to calc the angle - anglespeed = anglespeedset; //!This is anglespeed depending on circle speed 1 is same speed and 0.5 half speed - temp_xoffset = center_x; //!position of center in x - temp_yoffset = center_y; //!position of center in y + anglespeed = anglespeedset; //!This is anglespeed depending on circle speed 1 is same speed and 0.5 half speed + temp_xoffset = center_x; //!position of center in x + temp_yoffset = center_y; //!position of center in y } effects |= eff; effectAmount = speed; //!Circlespeed } -void GuiElement::SetEffect(int eff, int amount, int target) { - LOCK(this); - if (eff & EFFECT_SLIDE_IN) { - // these calculations overcompensate a little - if (eff & EFFECT_SLIDE_TOP) - yoffsetDyn = -screenheight; - else if (eff & EFFECT_SLIDE_LEFT) - xoffsetDyn = -screenwidth; - else if (eff & EFFECT_SLIDE_BOTTOM) - yoffsetDyn = screenheight; - else if (eff & EFFECT_SLIDE_RIGHT) - xoffsetDyn = screenwidth; - } +void GuiElement::SetEffect(int eff, int amount, int target) +{ + LOCK(this); + if(eff & EFFECT_SLIDE_IN) + { + // these calculations overcompensate a little + if(eff & EFFECT_SLIDE_TOP) + yoffsetDyn = -screenheight; + else if(eff & EFFECT_SLIDE_LEFT) + xoffsetDyn = -screenwidth; + else if(eff & EFFECT_SLIDE_BOTTOM) + yoffsetDyn = screenheight; + else if(eff & EFFECT_SLIDE_RIGHT) + xoffsetDyn = screenwidth; + } - if (eff & EFFECT_FADE && amount > 0) { - alphaDyn = 0; - } else if (eff & EFFECT_FADE && amount < 0) { - alphaDyn = alpha; + if(eff & EFFECT_FADE && amount > 0) + { + alphaDyn = 0; + } + else if(eff & EFFECT_FADE && amount < 0) + { + alphaDyn = alpha; - } else if (eff & EFFECT_ROCK_VERTICLE) { - changervar = 0; + } else if(eff & EFFECT_ROCK_VERTICLE) { + changervar = 0; yoffsetDyn = 0; yoffsetDynFloat = 0.0; + } + + effects |= eff; + effectAmount = amount; + effectTarget = target; +} + +void GuiElement::SetEffectOnOver(int eff, int amount, int target) +{ + LOCK(this); + effectsOver |= eff; + effectAmountOver = amount; + effectTargetOver = target; +} + +void GuiElement::SetEffectGrow() +{ + SetEffectOnOver(EFFECT_SCALE, 4, 110); +} + +void GuiElement::StopEffect() +{ + xoffsetDyn = 0; + yoffsetDyn = 0; + effects = 0; + effectsOver = 0; + effectAmount = 0; + effectAmountOver = 0; + effectTarget = 0; + effectTargetOver = 0; + scaleDyn = 1; + frequency = 0.0f; + changervar = 0; + //angleDyn = 0.0f; + anglespeed = 0.0f; +} + +void GuiElement::UpdateEffects() +{ + LOCK(this); + + if(effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND)) + { + if(effects & EFFECT_SLIDE_IN) + { + if(effects & EFFECT_SLIDE_LEFT) + { + xoffsetDyn += effectAmount; + + if(xoffsetDyn >= 0) + { + xoffsetDyn = 0; + effects = 0; + } + } + else if(effects & EFFECT_SLIDE_RIGHT) + { + xoffsetDyn -= effectAmount; + + if(xoffsetDyn <= 0) + { + xoffsetDyn = 0; + effects = 0; + } + } + else if(effects & EFFECT_SLIDE_TOP) + { + yoffsetDyn += effectAmount; + + if(yoffsetDyn >= 0) + { + yoffsetDyn = 0; + effects = 0; + } + } + else if(effects & EFFECT_SLIDE_BOTTOM) + { + yoffsetDyn -= effectAmount; + + if(yoffsetDyn <= 0) + { + yoffsetDyn = 0; + effects = 0; + } + } + } + else + { + if(effects & EFFECT_SLIDE_LEFT) + { + xoffsetDyn -= effectAmount; + + if(xoffsetDyn <= -screenwidth) + effects = 0; // shut off effect + } + else if(effects & EFFECT_SLIDE_RIGHT) + { + xoffsetDyn += effectAmount; + + if(xoffsetDyn >= screenwidth) + effects = 0; // shut off effect + } + else if(effects & EFFECT_SLIDE_TOP) + { + yoffsetDyn -= effectAmount; + + if(yoffsetDyn <= -screenheight) + effects = 0; // shut off effect + } + else if(effects & EFFECT_SLIDE_BOTTOM) + { + yoffsetDyn += effectAmount; + + if(yoffsetDyn >= screenheight) + effects = 0; // shut off effect + } + } + } + + if(effects & EFFECT_GOROUND) { + //!< check out gui.h for info + xoffset = temp_xoffset; + yoffset = temp_yoffset; + if(fabs(frequency) < circleamount) { + angleDyn = (frequency+degree+90.0f) * anglespeed; + xoffsetDyn = (int) lround(((f32) Radius)*cos((frequency+degree)*PI/180.0f)); + yoffsetDyn = (int) lround(((f32) Radius)*sin((frequency+degree)*PI/180.0f)); + frequency += ((f32) effectAmount)*0.01f; + } else { + f32 temp_frequency = ((effectAmount<0)?-1.0f:1.0f)*circleamount; + angleDyn = (temp_frequency+degree+90.0f) * anglespeed; + xoffsetDyn = (int) lround(((f32) Radius)*cos((temp_frequency+degree)*PI/180.0f)); + yoffsetDyn = (int) lround(((f32) Radius)*sin((temp_frequency+degree)*PI/180.0f)); + xoffset += xoffsetDyn; + yoffset += yoffsetDyn; + effects ^= EFFECT_GOROUND; + frequency = 0.0f; + } } - effects |= eff; - effectAmount = amount; - effectTarget = target; -} - -void GuiElement::SetEffectOnOver(int eff, int amount, int target) { - LOCK(this); - effectsOver |= eff; - effectAmountOver = amount; - effectTargetOver = target; -} - -void GuiElement::SetEffectGrow() { - SetEffectOnOver(EFFECT_SCALE, 4, 110); -} - -void GuiElement::StopEffect() { - xoffsetDyn = 0; - yoffsetDyn = 0; - effects = 0; - effectsOver = 0; - effectAmount = 0; - effectAmountOver = 0; - effectTarget = 0; - effectTargetOver = 0; - scaleDyn = 1; - frequency = 0.0f; - changervar = 0; - //angleDyn = 0.0f; - anglespeed = 0.0f; -} - -void GuiElement::UpdateEffects() { - LOCK(this); - - if (effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND)) { - if (effects & EFFECT_SLIDE_IN) { - if (effects & EFFECT_SLIDE_LEFT) { - xoffsetDyn += effectAmount; - - if (xoffsetDyn >= 0) { - xoffsetDyn = 0; - effects = 0; - } - } else if (effects & EFFECT_SLIDE_RIGHT) { - xoffsetDyn -= effectAmount; - - if (xoffsetDyn <= 0) { - xoffsetDyn = 0; - effects = 0; - } - } else if (effects & EFFECT_SLIDE_TOP) { - yoffsetDyn += effectAmount; - - if (yoffsetDyn >= 0) { - yoffsetDyn = 0; - effects = 0; - } - } else if (effects & EFFECT_SLIDE_BOTTOM) { - yoffsetDyn -= effectAmount; - - if (yoffsetDyn <= 0) { - yoffsetDyn = 0; - effects = 0; - } - } - } else { - if (effects & EFFECT_SLIDE_LEFT) { - xoffsetDyn -= effectAmount; - - if (xoffsetDyn <= -screenwidth) - effects = 0; // shut off effect - } else if (effects & EFFECT_SLIDE_RIGHT) { - xoffsetDyn += effectAmount; - - if (xoffsetDyn >= screenwidth) - effects = 0; // shut off effect - } else if (effects & EFFECT_SLIDE_TOP) { - yoffsetDyn -= effectAmount; - - if (yoffsetDyn <= -screenheight) - effects = 0; // shut off effect - } else if (effects & EFFECT_SLIDE_BOTTOM) { - yoffsetDyn += effectAmount; - - if (yoffsetDyn >= screenheight) - effects = 0; // shut off effect - } - } - } - - if (effects & EFFECT_GOROUND) { - //!< check out gui.h for info - xoffset = temp_xoffset; - yoffset = temp_yoffset; - if (fabs(frequency) < circleamount) { - angleDyn = (frequency+degree+90.0f) * anglespeed; - xoffsetDyn = (int) lround(((f32) Radius)*cos((frequency+degree)*PI/180.0f)); - yoffsetDyn = (int) lround(((f32) Radius)*sin((frequency+degree)*PI/180.0f)); - frequency += ((f32) effectAmount)*0.01f; - } else { - f32 temp_frequency = ((effectAmount<0)?-1.0f:1.0f)*circleamount; - angleDyn = (temp_frequency+degree+90.0f) * anglespeed; - xoffsetDyn = (int) lround(((f32) Radius)*cos((temp_frequency+degree)*PI/180.0f)); - yoffsetDyn = (int) lround(((f32) Radius)*sin((temp_frequency+degree)*PI/180.0f)); - xoffset += xoffsetDyn; - yoffset += yoffsetDyn; - effects ^= EFFECT_GOROUND; - frequency = 0.0f; - } - } - - if (effects & EFFECT_ROCK_VERTICLE) { + if(effects & EFFECT_ROCK_VERTICLE) { //move up to 10pixel above 0 - if (changervar == 0 && yoffsetDynFloat < 11.0) { + if(changervar == 0 && yoffsetDynFloat < 11.0) { yoffsetDynFloat += (effectAmount*0.01); - } else if (yoffsetDynFloat > 10.0) { + } else if(yoffsetDynFloat > 10.0) { changervar = 1; } //move down till 10pixel under 0 - if (changervar == 1 && yoffsetDynFloat > -11.0) { + if(changervar == 1 && yoffsetDynFloat > -11.0) { yoffsetDynFloat -= (effectAmount*0.01); - } else if (yoffsetDynFloat < -10.0) { + } else if(yoffsetDynFloat < -10.0) { changervar = 0; } yoffsetDyn = (int)(yoffsetDynFloat); } - if (effects & EFFECT_FADE) { - alphaDyn += effectAmount; + if(effects & EFFECT_FADE) + { + alphaDyn += effectAmount; - if (effectAmount < 0 && alphaDyn <= 0) { - alphaDyn = 0; - effects = 0; // shut off effect - } else if (effectAmount > 0 && alphaDyn >= alpha) { - alphaDyn = alpha; - effects = 0; // shut off effect - } - } - if (effects & EFFECT_SCALE) { - scaleDyn += effectAmount/100.0; + if(effectAmount < 0 && alphaDyn <= 0) + { + alphaDyn = 0; + effects = 0; // shut off effect + } + else if(effectAmount > 0 && alphaDyn >= alpha) + { + alphaDyn = alpha; + effects = 0; // shut off effect + } + } + if(effects & EFFECT_SCALE) + { + scaleDyn += effectAmount/100.0; - if ((effectAmount < 0 && scaleDyn <= effectTarget/100.0) - || (effectAmount > 0 && scaleDyn >= effectTarget/100.0)) { - scaleDyn = effectTarget/100.0; - effects = 0; // shut off effect - } - } - if (effects & EFFECT_PULSE) { - int percent = 10; //go down from target by this + if((effectAmount < 0 && scaleDyn <= effectTarget/100.0) + || (effectAmount > 0 && scaleDyn >= effectTarget/100.0)) + { + scaleDyn = effectTarget/100.0; + effects = 0; // shut off effect + } + } + if(effects & EFFECT_PULSE) + { + int percent = 10; //go down from target by this - if ((scaleDyn <= (effectTarget*0.01)) && (!changervar)) { + if((scaleDyn <= (effectTarget*0.01)) && (!changervar)) { scaleDyn += (effectAmount*0.001); - } else if (scaleDyn > (effectTarget*0.01)) { + } else if(scaleDyn > (effectTarget*0.01)) { changervar = 1; - } - if ((scaleDyn >= ((effectTarget-percent)*0.01)) && (changervar)) { + } + if((scaleDyn >= ((effectTarget-percent)*0.01)) && (changervar)) { scaleDyn -= (effectAmount*0.001); - } else if (scaleDyn < ((effectTarget-percent)*0.01)) { + } else if(scaleDyn < ((effectTarget-percent)*0.01)) { changervar = 0; - } - } + } + } } -void GuiElement::Update(GuiTrigger * t) { - LOCK(this); - if (updateCB) - updateCB(this); +void GuiElement::Update(GuiTrigger * t) +{ + LOCK(this); + if(updateCB) + updateCB(this); } -void GuiElement::SetUpdateCallback(UpdateCallback u) { - LOCK(this); - updateCB = u; +void GuiElement::SetUpdateCallback(UpdateCallback u) +{ + LOCK(this); + updateCB = u; } -void GuiElement::SetPosition(int xoff, int yoff, int zoff) { - LOCK(this); - xoffset = xoff; - yoffset = yoff; - zoffset = zoff; +void GuiElement::SetPosition(int xoff, int yoff, int zoff) +{ + LOCK(this); + xoffset = xoff; + yoffset = yoff; + zoffset = zoff; } -void GuiElement::SetAlignment(int hor, int vert) { - LOCK(this); - alignmentHor = hor; - alignmentVert = vert; +void GuiElement::SetAlignment(int hor, int vert) +{ + LOCK(this); + alignmentHor = hor; + alignmentVert = vert; } -int GuiElement::GetSelected() { - return -1; +int GuiElement::GetSelected() +{ + return -1; } /** * Draw an element on screen. */ -void GuiElement::Draw() { +void GuiElement::Draw() +{ } /** * Draw Tooltips on screen. */ -void GuiElement::DrawTooltip() { +void GuiElement::DrawTooltip() +{ } /** @@ -657,55 +751,69 @@ void GuiElement::DrawTooltip() { * @param[in] x X position in pixel. * @param[in] y Y position in pixel. */ -bool GuiElement::IsInside(int x, int y) { - if (x > this->GetLeft() && x < (this->GetLeft()+width) - && y > this->GetTop() && y < (this->GetTop()+height)) - return true; - return false; +bool GuiElement::IsInside(int x, int y) +{ + if(x > this->GetLeft() && x < (this->GetLeft()+width) + && y > this->GetTop() && y < (this->GetTop()+height)) + return true; + return false; } -void GuiElement::Lock() { +void GuiElement::Lock() +{ // LWP_MutexLock(mutex); - for (;;) { // loop while element is locked by self - LWP_MutexLock(_lock_mutex); + for(;;) // loop while element is locked by self + { + LWP_MutexLock(_lock_mutex); - if (_lock_thread == LWP_THREAD_NULL) { // element is not locked - _lock_thread = LWP_GetSelf(); // mark as locked - _lock_count = 1; // set count of lock to 1 - LWP_MutexUnlock(_lock_mutex); - return; - } else if (_lock_thread == LWP_GetSelf()) { // thread is locked by my self - _lock_count++; // inc count of locks; - LWP_MutexUnlock(_lock_mutex); - return; - } else { // otherwise the element is locked by an other thread - if (_lock_queue == LWP_TQUEUE_NULL) // no queue - meens it is the first access to the locked element - LWP_InitQueue(&_lock_queue); // init queue - LWP_MutexUnlock(_lock_mutex); - LWP_ThreadSleep(_lock_queue); // and sleep - // try lock again; - } - } + if(_lock_thread == LWP_THREAD_NULL) // element is not locked + { + _lock_thread = LWP_GetSelf(); // mark as locked + _lock_count = 1; // set count of lock to 1 + LWP_MutexUnlock(_lock_mutex); + return; + } + else if(_lock_thread == LWP_GetSelf()) // thread is locked by my self + { + _lock_count++; // inc count of locks; + LWP_MutexUnlock(_lock_mutex); + return; + } + else // otherwise the element is locked by an other thread + { + if(_lock_queue == LWP_TQUEUE_NULL) // no queue - meens it is the first access to the locked element + LWP_InitQueue(&_lock_queue); // init queue + LWP_MutexUnlock(_lock_mutex); + LWP_ThreadSleep(_lock_queue); // and sleep + // try lock again; + } + } } -void GuiElement::Unlock() { +void GuiElement::Unlock() +{ // LWP_MutexUnlock(mutex); - LWP_MutexLock(_lock_mutex); - // only the thread was locked this element, can call unlock - if (_lock_thread == LWP_GetSelf()) { // but we check it here – safe is safe - if (--_lock_count == 0) { // dec count of locks and check if it last lock; - _lock_thread = LWP_THREAD_NULL; // mark as unlocked - if (_lock_queue != LWP_TQUEUE_NULL) { // has a queue - LWP_CloseQueue(_lock_queue); // close the queue and wake all waited threads - _lock_queue = LWP_TQUEUE_NULL; - } - } - } - LWP_MutexUnlock(_lock_mutex); + LWP_MutexLock(_lock_mutex); + // only the thread was locked this element, can call unlock + if(_lock_thread == LWP_GetSelf()) // but we check it here – safe is safe + { + if(--_lock_count == 0) // dec count of locks and check if it last lock; + { + _lock_thread = LWP_THREAD_NULL; // mark as unlocked + if(_lock_queue != LWP_TQUEUE_NULL) // has a queue + { + LWP_CloseQueue(_lock_queue); // close the queue and wake all waited threads + _lock_queue = LWP_TQUEUE_NULL; + } + } + } + LWP_MutexUnlock(_lock_mutex); } -SimpleLock::SimpleLock(GuiElement *e) : element(e) { - element->Lock(); +SimpleLock::SimpleLock(GuiElement *e) : element(e) +{ + element->Lock(); } -SimpleLock::~SimpleLock() { - element->Unlock(); +SimpleLock::~SimpleLock() +{ + element->Unlock(); } diff --git a/source/libwiigui/gui_filebrowser.cpp b/source/libwiigui/gui_filebrowser.cpp index 36c01255..389c8ee0 100644 --- a/source/libwiigui/gui_filebrowser.cpp +++ b/source/libwiigui/gui_filebrowser.cpp @@ -15,360 +15,401 @@ /** * Constructor for the GuiFileBrowser class. */ -GuiFileBrowser::GuiFileBrowser(int w, int h) { - width = w; - height = h; - selectedItem = 0; - selectable = true; - listChanged = true; // trigger an initial list update - triggerdisabled = false; // trigger disable - focus = 0; // allow focus +GuiFileBrowser::GuiFileBrowser(int w, int h) +{ + width = w; + height = h; + selectedItem = 0; + selectable = true; + listChanged = true; // trigger an initial list update + triggerdisabled = false; // trigger disable + focus = 0; // allow focus - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigHeldA = new GuiTrigger; + trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbg_browser.png", CFG.theme_path); - bgFileSelection = new GuiImageData(imgPath, bg_browser_png); - bgFileSelectionImg = new GuiImage(bgFileSelection); - bgFileSelectionImg->SetParent(this); - bgFileSelectionImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + char imgPath[100]; + snprintf(imgPath, sizeof(imgPath), "%sbg_browser.png", CFG.theme_path); + bgFileSelection = new GuiImageData(imgPath, bg_browser_png); + bgFileSelectionImg = new GuiImage(bgFileSelection); + bgFileSelectionImg->SetParent(this); + bgFileSelectionImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - snprintf(imgPath, sizeof(imgPath), "%sbg_browser_selection.png", CFG.theme_path); - bgFileSelectionEntry = new GuiImageData(imgPath, bg_browser_selection_png); + snprintf(imgPath, sizeof(imgPath), "%sbg_browser_selection.png", CFG.theme_path); + bgFileSelectionEntry = new GuiImageData(imgPath, bg_browser_selection_png); // fileArchives = new GuiImageData(icon_archives_png); // fileDefault = new GuiImageData(icon_default_png); - fileFolder = new GuiImageData(icon_folder_png); + fileFolder = new GuiImageData(icon_folder_png); // fileGFX = new GuiImageData(icon_gfx_png); // filePLS = new GuiImageData(icon_pls_png); // fileSFX = new GuiImageData(icon_sfx_png); // fileTXT = new GuiImageData(icon_txt_png); // fileXML = new GuiImageData(icon_xml_png); + + snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", CFG.theme_path); + scrollbar = new GuiImageData(imgPath, scrollbar_png); + scrollbarImg = new GuiImage(scrollbar); + scrollbarImg->SetParent(this); + scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + scrollbarImg->SetPosition(0, 2); + scrollbarImg->SetSkew(0,0,0,0,0,-30,0,-30); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", CFG.theme_path); - scrollbar = new GuiImageData(imgPath, scrollbar_png); - scrollbarImg = new GuiImage(scrollbar); - scrollbarImg->SetParent(this); - scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarImg->SetPosition(0, 2); - scrollbarImg->SetSkew(0,0,0,0,0,-30,0,-30); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", CFG.theme_path); + arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownImg = new GuiImage(arrowDown); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", CFG.theme_path); + arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpImg = new GuiImage(arrowUp); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", CFG.theme_path); + scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); + scrollbarBoxImg = new GuiImage(scrollbarBox); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", CFG.theme_path); - arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", CFG.theme_path); - arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", CFG.theme_path); - scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); + arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); + arrowUpBtn->SetParent(this); + arrowUpBtn->SetImage(arrowUpImg); + arrowUpBtn->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + arrowUpBtn->SetPosition(12,-12); + arrowUpBtn->SetSelectable(false); + arrowUpBtn->SetClickable(false); + arrowUpBtn->SetHoldable(true); + arrowUpBtn->SetTrigger(trigHeldA); + arrowUpBtn->SetSoundOver(btnSoundOver); + arrowUpBtn->SetSoundClick(btnSoundClick); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - arrowUpBtn->SetPosition(12,-12); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetClickable(false); - arrowUpBtn->SetHoldable(true); - arrowUpBtn->SetTrigger(trigHeldA); - arrowUpBtn->SetSoundOver(btnSoundOver); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); + arrowDownBtn->SetParent(this); + arrowDownBtn->SetImage(arrowDownImg); + arrowDownBtn->SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + arrowDownBtn->SetPosition(12,12); + arrowDownBtn->SetSelectable(false); + arrowDownBtn->SetClickable(false); + arrowDownBtn->SetHoldable(true); + arrowDownBtn->SetTrigger(trigHeldA); + arrowDownBtn->SetSoundOver(btnSoundOver); + arrowDownBtn->SetSoundClick(btnSoundClick); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(12,12); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetClickable(false); - arrowDownBtn->SetHoldable(true); - arrowDownBtn->SetTrigger(trigHeldA); - arrowDownBtn->SetSoundOver(btnSoundOver); - arrowDownBtn->SetSoundClick(btnSoundClick); + scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); + scrollbarBoxBtn->SetParent(this); + scrollbarBoxBtn->SetImage(scrollbarBoxImg); + scrollbarBoxBtn->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + scrollbarBoxBtn->SetPosition(-10, 0); + scrollbarBoxBtn->SetMinY(-10); + scrollbarBoxBtn->SetMaxY(156); + scrollbarBoxBtn->SetSelectable(false); + scrollbarBoxBtn->SetClickable(false); + scrollbarBoxBtn->SetHoldable(true); + scrollbarBoxBtn->SetTrigger(trigHeldA); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarBoxBtn->SetPosition(-10, 0); - scrollbarBoxBtn->SetMinY(-10); - scrollbarBoxBtn->SetMaxY(156); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetClickable(false); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + for(int i=0; iSetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + fileListText[i]->SetPosition(5,0); + fileListText[i]->SetMaxWidth(bgFileSelectionImg->GetWidth() - (arrowDownImg->GetWidth()+20), GuiText::DOTTED); - for (int i=0; iSetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - fileListText[i]->SetPosition(5,0); - fileListText[i]->SetMaxWidth(bgFileSelectionImg->GetWidth() - (arrowDownImg->GetWidth()+20), GuiText::DOTTED); + fileListTextOver[i] = new GuiText(NULL,20, (GXColor){0, 0, 0, 0xff}); + fileListTextOver[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + fileListTextOver[i]->SetPosition(5,0); + fileListTextOver[i]->SetMaxWidth(bgFileSelectionImg->GetWidth() - (arrowDownImg->GetWidth()+20), GuiText::SCROLL); - fileListTextOver[i] = new GuiText(NULL,20, (GXColor) {0, 0, 0, 0xff}); - fileListTextOver[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - fileListTextOver[i]->SetPosition(5,0); - fileListTextOver[i]->SetMaxWidth(bgFileSelectionImg->GetWidth() - (arrowDownImg->GetWidth()+20), GuiText::SCROLL); - - fileListBg[i] = new GuiImage(bgFileSelectionEntry); - //fileListArchives[i] = new GuiImage(fileArchives); - //fileListDefault[i] = new GuiImage(fileDefault); - fileListFolder[i] = new GuiImage(fileFolder); - //fileListGFX[i] = new GuiImage(fileGFX); - //fileListPLS[i] = new GuiImage(filePLS); - //fileListSFX[i] = new GuiImage(fileSFX); - //fileListTXT[i] = new GuiImage(fileTXT); - //fileListXML[i] = new GuiImage(fileXML); - fileList[i] = new GuiButton(350,30); - fileList[i]->SetParent(this); - fileList[i]->SetLabel(fileListText[i]); - fileList[i]->SetLabelOver(fileListTextOver[i]); - fileList[i]->SetImageOver(fileListBg[i]); - fileList[i]->SetPosition(2,30*i+3); - fileList[i]->SetTrigger(trigA); - fileList[i]->SetRumble(false); - fileList[i]->SetSoundClick(btnSoundClick); - } + fileListBg[i] = new GuiImage(bgFileSelectionEntry); + //fileListArchives[i] = new GuiImage(fileArchives); + //fileListDefault[i] = new GuiImage(fileDefault); + fileListFolder[i] = new GuiImage(fileFolder); + //fileListGFX[i] = new GuiImage(fileGFX); + //fileListPLS[i] = new GuiImage(filePLS); + //fileListSFX[i] = new GuiImage(fileSFX); + //fileListTXT[i] = new GuiImage(fileTXT); + //fileListXML[i] = new GuiImage(fileXML); + fileList[i] = new GuiButton(350,30); + fileList[i]->SetParent(this); + fileList[i]->SetLabel(fileListText[i]); + fileList[i]->SetLabelOver(fileListTextOver[i]); + fileList[i]->SetImageOver(fileListBg[i]); + fileList[i]->SetPosition(2,30*i+3); + fileList[i]->SetTrigger(trigA); + fileList[i]->SetRumble(false); + fileList[i]->SetSoundClick(btnSoundClick); + } } /** * Destructor for the GuiFileBrowser class. */ -GuiFileBrowser::~GuiFileBrowser() { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; +GuiFileBrowser::~GuiFileBrowser() +{ + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; - delete bgFileSelectionImg; - delete scrollbarImg; - delete arrowDownImg; - delete arrowUpImg; - delete scrollbarBoxImg; + delete bgFileSelectionImg; + delete scrollbarImg; + delete arrowDownImg; + delete arrowUpImg; + delete scrollbarBoxImg; - delete bgFileSelection; - delete bgFileSelectionEntry; - //delete fileArchives; - //delete fileDefault; - delete fileFolder; - //delete fileGFX; - //delete filePLS; - //delete fileSFX; - //delete fileTXT; - //delete fileXML; - delete scrollbar; - delete arrowDown; - delete arrowUp; - delete scrollbarBox; + delete bgFileSelection; + delete bgFileSelectionEntry; + //delete fileArchives; + //delete fileDefault; + delete fileFolder; + //delete fileGFX; + //delete filePLS; + //delete fileSFX; + //delete fileTXT; + //delete fileXML; + delete scrollbar; + delete arrowDown; + delete arrowUp; + delete scrollbarBox; - delete btnSoundOver; - delete btnSoundClick; - delete trigHeldA; - delete trigA; + delete btnSoundOver; + delete btnSoundClick; + delete trigHeldA; + delete trigA; - for (int i=0; iResetState(); + for(int i=0; iResetState(); - if (f == 1) - fileList[selectedItem]->SetState(STATE_SELECTED); + if(f == 1) + fileList[selectedItem]->SetState(STATE_SELECTED); } -void GuiFileBrowser::DisableTriggerUpdate(bool set) { - LOCK(this); - triggerdisabled = set; +void GuiFileBrowser::DisableTriggerUpdate(bool set) +{ + LOCK(this); + triggerdisabled = set; } -void GuiFileBrowser::ResetState() { - LOCK(this); - state = STATE_DEFAULT; - stateChan = -1; - selectedItem = 0; +void GuiFileBrowser::ResetState() +{ + LOCK(this); + state = STATE_DEFAULT; + stateChan = -1; + selectedItem = 0; - for (int i=0; iResetState(); - } + for(int i=0; iResetState(); + } } -void GuiFileBrowser::TriggerUpdate() { - LOCK(this); - listChanged = true; +void GuiFileBrowser::TriggerUpdate() +{ + LOCK(this); + listChanged = true; } /** * Draw the button on screen */ -void GuiFileBrowser::Draw() { - LOCK(this); - if (!this->IsVisible()) - return; +void GuiFileBrowser::Draw() +{ + LOCK(this); + if(!this->IsVisible()) + return; - bgFileSelectionImg->Draw(); + bgFileSelectionImg->Draw(); - for (int i=0; iDraw(); - } + for(int i=0; iDraw(); + } - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); - this->UpdateEffects(); + this->UpdateEffects(); } -void GuiFileBrowser::Update(GuiTrigger * t) { - LOCK(this); - if (state == STATE_DISABLED || !t || triggerdisabled) - return; +void GuiFileBrowser::Update(GuiTrigger * t) +{ + LOCK(this); + if(state == STATE_DISABLED || !t || triggerdisabled) + return; - int position = 0; - int positionWiimote = 0; + int position = 0; + int positionWiimote = 0; - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); + arrowUpBtn->Update(t); + arrowDownBtn->Update(t); + scrollbarBoxBtn->Update(t); - // move the file listing to respond to wiimote cursor movement - if (scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && - browser->browserList.size() > FILEBROWSERSIZE - ) { - scrollbarBoxBtn->SetPosition(20,-10); - positionWiimote = t->wpad.ir.y - 60 - scrollbarBoxBtn->GetTop(); + // move the file listing to respond to wiimote cursor movement + if(scrollbarBoxBtn->GetState() == STATE_HELD && + scrollbarBoxBtn->GetStateChan() == t->chan && + t->wpad.ir.valid && + browser->browserList.size() > FILEBROWSERSIZE + ) + { + scrollbarBoxBtn->SetPosition(20,-10); + positionWiimote = t->wpad.ir.y - 60 - scrollbarBoxBtn->GetTop(); - if (positionWiimote < scrollbarBoxBtn->GetMinY()) - positionWiimote = scrollbarBoxBtn->GetMinY(); - else if (positionWiimote > scrollbarBoxBtn->GetMaxY()) - positionWiimote = scrollbarBoxBtn->GetMaxY(); + if(positionWiimote < scrollbarBoxBtn->GetMinY()) + positionWiimote = scrollbarBoxBtn->GetMinY(); + else if(positionWiimote > scrollbarBoxBtn->GetMaxY()) + positionWiimote = scrollbarBoxBtn->GetMaxY(); - browser->pageIndex = (positionWiimote * browser->browserList.size())/136.0 - selectedItem; + browser->pageIndex = (positionWiimote * browser->browserList.size())/136.0 - selectedItem; - if (browser->pageIndex <= 0) { - browser->pageIndex = 0; - } else if (browser->pageIndex+FILEBROWSERSIZE >= (int)browser->browserList.size()) { - browser->pageIndex = browser->browserList.size()-FILEBROWSERSIZE; - } - listChanged = true; - focus = false; + if(browser->pageIndex <= 0) + { + browser->pageIndex = 0; + } + else if(browser->pageIndex+FILEBROWSERSIZE >= (int)browser->browserList.size()) + { + browser->pageIndex = browser->browserList.size()-FILEBROWSERSIZE; + } + listChanged = true; + focus = false; + + } - } + if(arrowDownBtn->GetState() == STATE_HELD && arrowDownBtn->GetStateChan() == t->chan) + { + t->wpad.btns_h |= WPAD_BUTTON_DOWN; + if(!this->IsFocused()) + ((GuiWindow *)this->GetParent())->ChangeFocus(this); + + } + else if(arrowUpBtn->GetState() == STATE_HELD && arrowUpBtn->GetStateChan() == t->chan) + { + t->wpad.btns_h |= WPAD_BUTTON_UP; + if(!this->IsFocused()) + ((GuiWindow *)this->GetParent())->ChangeFocus(this); + + } - if (arrowDownBtn->GetState() == STATE_HELD && arrowDownBtn->GetStateChan() == t->chan) { - t->wpad.btns_h |= WPAD_BUTTON_DOWN; - if (!this->IsFocused()) - ((GuiWindow *)this->GetParent())->ChangeFocus(this); +/* // pad/joystick navigation + if(!focus) + { + goto endNavigation; // skip navigation + listChanged = false; + } +*/ + if(t->Right()) + { + if(browser->pageIndex < (int)browser->browserList.size() && browser->browserList.size() > FILEBROWSERSIZE) + { + browser->pageIndex += FILEBROWSERSIZE; + if(browser->pageIndex+FILEBROWSERSIZE >= (int)browser->browserList.size()) + browser->pageIndex = browser->browserList.size()-FILEBROWSERSIZE; + listChanged = true; + } + } + else if(t->Left()) + { + if(browser->pageIndex > 0) + { + browser->pageIndex -= FILEBROWSERSIZE; + if(browser->pageIndex < 0) + browser->pageIndex = 0; + listChanged = true; + } + } + else if(t->Down()) + { + if(browser->pageIndex + selectedItem + 1 < (int)browser->browserList.size()) + { + if(selectedItem == FILEBROWSERSIZE-1) + { + // move list down by 1 + browser->pageIndex++; + listChanged = true; + } + else if(fileList[selectedItem+1]->IsVisible()) + { + fileList[selectedItem]->ResetState(); + fileList[++selectedItem]->SetState(STATE_SELECTED, t->chan); + } + } + } + else if(t->Up()) + { + if(selectedItem == 0 && browser->pageIndex + selectedItem > 0) + { + // move list up by 1 + browser->pageIndex--; + listChanged = true; + } + else if(selectedItem > 0) + { + fileList[selectedItem]->ResetState(); + fileList[--selectedItem]->SetState(STATE_SELECTED, t->chan); + } + } - } else if (arrowUpBtn->GetState() == STATE_HELD && arrowUpBtn->GetStateChan() == t->chan) { - t->wpad.btns_h |= WPAD_BUTTON_UP; - if (!this->IsFocused()) - ((GuiWindow *)this->GetParent())->ChangeFocus(this); + //endNavigation: - } + for(int i=0; ipageIndex+i < (int)browser->browserList.size()) + { + if(fileList[i]->GetState() == STATE_DISABLED) + fileList[i]->SetState(STATE_DEFAULT); - /* // pad/joystick navigation - if(!focus) - { - goto endNavigation; // skip navigation - listChanged = false; - } - */ - if (t->Right()) { - if (browser->pageIndex < (int)browser->browserList.size() && browser->browserList.size() > FILEBROWSERSIZE) { - browser->pageIndex += FILEBROWSERSIZE; - if (browser->pageIndex+FILEBROWSERSIZE >= (int)browser->browserList.size()) - browser->pageIndex = browser->browserList.size()-FILEBROWSERSIZE; - listChanged = true; - } - } else if (t->Left()) { - if (browser->pageIndex > 0) { - browser->pageIndex -= FILEBROWSERSIZE; - if (browser->pageIndex < 0) - browser->pageIndex = 0; - listChanged = true; - } - } else if (t->Down()) { - if (browser->pageIndex + selectedItem + 1 < (int)browser->browserList.size()) { - if (selectedItem == FILEBROWSERSIZE-1) { - // move list down by 1 - browser->pageIndex++; - listChanged = true; - } else if (fileList[selectedItem+1]->IsVisible()) { - fileList[selectedItem]->ResetState(); - fileList[++selectedItem]->SetState(STATE_SELECTED, t->chan); - } - } - } else if (t->Up()) { - if (selectedItem == 0 && browser->pageIndex + selectedItem > 0) { - // move list up by 1 - browser->pageIndex--; - listChanged = true; - } else if (selectedItem > 0) { - fileList[selectedItem]->ResetState(); - fileList[--selectedItem]->SetState(STATE_SELECTED, t->chan); - } - } + if(fileList[i]->GetState() == STATE_SELECTED) + haveselected = true; - //endNavigation: + fileList[i]->SetVisible(true); - for (int i=0; ipageIndex+i < (int)browser->browserList.size()) { - if (fileList[i]->GetState() == STATE_DISABLED) - fileList[i]->SetState(STATE_DEFAULT); + fileListText[i]->SetText(browser->browserList[browser->pageIndex+i].displayname); + fileListTextOver[i]->SetText(browser->browserList[browser->pageIndex+i].displayname); - if (fileList[i]->GetState() == STATE_SELECTED) - haveselected = true; - - fileList[i]->SetVisible(true); - - fileListText[i]->SetText(browser->browserList[browser->pageIndex+i].displayname); - fileListTextOver[i]->SetText(browser->browserList[browser->pageIndex+i].displayname); - - if (browser->browserList[browser->pageIndex+i].isdir) { // directory - fileList[i]->SetIcon(fileListFolder[i]); - fileListText[i]->SetPosition(30,0); - fileListTextOver[i]->SetPosition(30,0); - } else { - /* - char *fileext = strrchr(browserList[browser.pageIndex+i].displayname, '.'); - fileListText[i]->SetPosition(32,0); - fileListTextOver[i]->SetPosition(32,0); - if(fileext) - { + if(browser->browserList[browser->pageIndex+i].isdir) // directory + { + fileList[i]->SetIcon(fileListFolder[i]); + fileListText[i]->SetPosition(30,0); + fileListTextOver[i]->SetPosition(30,0); + } + else + { + /* + char *fileext = strrchr(browserList[browser.pageIndex+i].displayname, '.'); + fileListText[i]->SetPosition(32,0); + fileListTextOver[i]->SetPosition(32,0); + if(fileext) + { if(!strcasecmp(fileext, ".png") || !strcasecmp(fileext, ".jpg") || !strcasecmp(fileext, ".jpeg") || - !strcasecmp(fileext, ".gif") || !strcasecmp(fileext, ".tga") || !strcasecmp(fileext, ".tpl") || - !strcasecmp(fileext, ".bmp")) { + !strcasecmp(fileext, ".gif") || !strcasecmp(fileext, ".tga") || !strcasecmp(fileext, ".tpl") || + !strcasecmp(fileext, ".bmp")) { fileList[i]->SetIcon(fileListGFX[i]); } else if(!strcasecmp(fileext, ".mp3") || !strcasecmp(fileext, ".ogg") || !strcasecmp(fileext, ".flac") || - !strcasecmp(fileext, ".mpc") || !strcasecmp(fileext, ".m4a") || !strcasecmp(fileext, ".wav")) { + !strcasecmp(fileext, ".mpc") || !strcasecmp(fileext, ".m4a") || !strcasecmp(fileext, ".wav")) { fileList[i]->SetIcon(fileListSFX[i]); } else if(!strcasecmp(fileext, ".pls") || !strcasecmp(fileext, ".m3u")) { fileList[i]->SetIcon(fileListPLS[i]); @@ -377,62 +418,68 @@ void GuiFileBrowser::Update(GuiTrigger * t) { } else if(!strcasecmp(fileext, ".xml")) { fileList[i]->SetIcon(fileListXML[i]); } else if(!strcasecmp(fileext, ".rar") || !strcasecmp(fileext, ".zip") || - !strcasecmp(fileext, ".gz") || !strcasecmp(fileext, ".7z")) { + !strcasecmp(fileext, ".gz") || !strcasecmp(fileext, ".7z")) { fileList[i]->SetIcon(fileListArchives[i]); } else { fileList[i]->SetIcon(fileListDefault[i]); } - } else { + } else { fileList[i]->SetIcon(fileListDefault[i]); - } - */ - fileList[i]->SetIcon(NULL); - fileListText[i]->SetPosition(10,0); - fileListTextOver[i]->SetPosition(10,0); - } - } else { - fileList[i]->SetVisible(false); - fileList[i]->SetState(STATE_DISABLED); - } - if (!haveselected && browser->pageIndex < (int)browser->browserList.size()) - fileList[i]->SetState(STATE_SELECTED, t->chan); + } + */ + fileList[i]->SetIcon(NULL); + fileListText[i]->SetPosition(10,0); + fileListTextOver[i]->SetPosition(10,0); + } + } + else + { + fileList[i]->SetVisible(false); + fileList[i]->SetState(STATE_DISABLED); + } + if(!haveselected && browser->pageIndex < (int)browser->browserList.size()) + fileList[i]->SetState(STATE_SELECTED, t->chan); - } + } - if (i != selectedItem && fileList[i]->GetState() == STATE_SELECTED) - fileList[i]->ResetState(); - else if (focus && i == selectedItem && fileList[i]->GetState() == STATE_DEFAULT) - fileList[selectedItem]->SetState(STATE_SELECTED, t->chan); + if(i != selectedItem && fileList[i]->GetState() == STATE_SELECTED) + fileList[i]->ResetState(); + else if(focus && i == selectedItem && fileList[i]->GetState() == STATE_DEFAULT) + fileList[selectedItem]->SetState(STATE_SELECTED, t->chan); - int currChan = t->chan; + int currChan = t->chan; - if (t->wpad.ir.valid && !fileList[i]->IsInside(t->wpad.ir.x, t->wpad.ir.y)) - t->chan = -1; + if(t->wpad.ir.valid && !fileList[i]->IsInside(t->wpad.ir.x, t->wpad.ir.y)) + t->chan = -1; - fileList[i]->Update(t); - t->chan = currChan; + fileList[i]->Update(t); + t->chan = currChan; - if (fileList[i]->GetState() == STATE_SELECTED) { - selectedItem = i; - } - } + if(fileList[i]->GetState() == STATE_SELECTED) + { + selectedItem = i; + } + } - // update the location of the scroll box based on the position in the file list - if (positionWiimote > 0) { - position = positionWiimote; // follow wiimote cursor - } else { - position = 136*(browser->pageIndex + FILEBROWSERSIZE/2.0) / (browser->browserList.size()*1.0); + // update the location of the scroll box based on the position in the file list + if(positionWiimote > 0) + { + position = positionWiimote; // follow wiimote cursor + } + else + { + position = 136*(browser->pageIndex + FILEBROWSERSIZE/2.0) / (browser->browserList.size()*1.0); - if (browser->pageIndex/(FILEBROWSERSIZE/2.0) < 1) - position = -10; - else if ((browser->pageIndex+FILEBROWSERSIZE)/(FILEBROWSERSIZE*1.0) >= (browser->browserList.size())/(FILEBROWSERSIZE*1.0)) - position = 156; - } + if(browser->pageIndex/(FILEBROWSERSIZE/2.0) < 1) + position = -10; + else if((browser->pageIndex+FILEBROWSERSIZE)/(FILEBROWSERSIZE*1.0) >= (browser->browserList.size())/(FILEBROWSERSIZE*1.0)) + position = 156; + } - scrollbarBoxBtn->SetPosition(12,position+26); + scrollbarBoxBtn->SetPosition(12,position+26); - listChanged = false; + listChanged = false; - if (updateCB) - updateCB(this); + if(updateCB) + updateCB(this); } diff --git a/source/libwiigui/gui_gamebrowser.cpp b/source/libwiigui/gui_gamebrowser.cpp index 05e6b892..c99c04bb 100644 --- a/source/libwiigui/gui_gamebrowser.cpp +++ b/source/libwiigui/gui_gamebrowser.cpp @@ -23,238 +23,253 @@ int txtscroll = 0; /** * Constructor for the GuiGameBrowser class. */ -GuiGameBrowser::GuiGameBrowser(int w, int h, struct discHdr * l, int gameCnt, const char *themePath, const u8 *imagebg, int selected, int offset) { - width = w; - height = h; - this->gameCnt = gameCnt; - gameList = l; - pagesize = THEME.pagesize; - scrollbaron = (gameCnt > pagesize) ? 1 : 0; - selectable = true; - listOffset = MAX(0,MIN(offset,(gameCnt-pagesize))); - selectedItem = selected - offset; - focus = 1; // allow focus - char imgPath[100]; +GuiGameBrowser::GuiGameBrowser(int w, int h, struct discHdr * l, int gameCnt, const char *themePath, const u8 *imagebg, int selected, int offset) +{ + width = w; + height = h; + this->gameCnt = gameCnt; + gameList = l; + pagesize = THEME.pagesize; + scrollbaron = (gameCnt > pagesize) ? 1 : 0; + selectable = true; + listOffset = MAX(0,MIN(offset,(gameCnt-pagesize))); + selectedItem = selected - offset; + focus = 1; // allow focus + char imgPath[100]; - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); + btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", themePath); - bgGames = new GuiImageData(imgPath, imagebg); + snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", themePath); + bgGames = new GuiImageData(imgPath, imagebg); - snprintf(imgPath, sizeof(imgPath), "%snew.png", themePath); - newGames = new GuiImageData(imgPath, new_png); + snprintf(imgPath, sizeof(imgPath), "%snew.png", themePath); + newGames = new GuiImageData(imgPath, new_png); - bgGameImg = new GuiImage(bgGames); - bgGameImg->SetParent(this); - bgGameImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + bgGameImg = new GuiImage(bgGames); + bgGameImg->SetParent(this); + bgGameImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + + maxTextWidth = bgGameImg->GetWidth() - 24 - 4; - maxTextWidth = bgGameImg->GetWidth() - 24 - 4; + snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); + bgGamesEntry = new GuiImageData(imgPath, bg_options_entry_png); - snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); - bgGamesEntry = new GuiImageData(imgPath, bg_options_entry_png); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", themePath); + scrollbar = new GuiImageData(imgPath, scrollbar_png); + scrollbarImg = new GuiImage(scrollbar); + scrollbarImg->SetParent(this); + scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + scrollbarImg->SetPosition(0, 4); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", themePath); - scrollbar = new GuiImageData(imgPath, scrollbar_png); - scrollbarImg = new GuiImage(scrollbar); - scrollbarImg->SetParent(this); - scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarImg->SetPosition(0, 4); + maxTextWidth -= scrollbarImg->GetWidth() + 4; - maxTextWidth -= scrollbarImg->GetWidth() + 4; + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", themePath); + arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownImg = new GuiImage(arrowDown); + arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownOverImg = new GuiImage(arrowDownOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); + arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpImg = new GuiImage(arrowUp); + arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpOverImg = new GuiImage(arrowUpOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); + scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); + scrollbarBoxImg = new GuiImage(scrollbarBox); + scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); + scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", themePath); - arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownOverImg = new GuiImage(arrowDownOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); - arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpOverImg = new GuiImage(arrowUpOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); - scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); - scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); + arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); + arrowUpBtn->SetParent(this); + arrowUpBtn->SetImage(arrowUpImg); + arrowUpBtn->SetImageOver(arrowUpOverImg); + arrowUpBtn->SetImageHold(arrowUpOverImg); + arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + arrowUpBtn->SetPosition(width/2-18+7,-18); + arrowUpBtn->SetSelectable(false); + arrowUpBtn->SetTrigger(trigA); + arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowUpBtn->SetSoundClick(btnSoundClick); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetImageOver(arrowUpOverImg); - arrowUpBtn->SetImageHold(arrowUpOverImg); - arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - arrowUpBtn->SetPosition(width/2-18+7,-18); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetTrigger(trigA); - arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); + arrowDownBtn->SetParent(this); + arrowDownBtn->SetImage(arrowDownImg); + arrowDownBtn->SetImageOver(arrowDownOverImg); + arrowDownBtn->SetImageHold(arrowDownOverImg); + arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + arrowDownBtn->SetPosition(width/2-18+7,18); + arrowDownBtn->SetSelectable(false); + arrowDownBtn->SetTrigger(trigA); + arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowDownBtn->SetSoundClick(btnSoundClick); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetImageOver(arrowDownOverImg); - arrowDownBtn->SetImageHold(arrowDownOverImg); - arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(width/2-18+7,18); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetTrigger(trigA); - arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowDownBtn->SetSoundClick(btnSoundClick); + scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); + scrollbarBoxBtn->SetParent(this); + scrollbarBoxBtn->SetImage(scrollbarBoxImg); + scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); + scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); + scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + scrollbarBoxBtn->SetSelectable(false); + scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); + scrollbarBoxBtn->SetMinY(0); + scrollbarBoxBtn->SetMaxY(height-30); + scrollbarBoxBtn->SetHoldable(true); + scrollbarBoxBtn->SetTrigger(trigHeldA); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); - scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); - scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); - scrollbarBoxBtn->SetMinY(0); - scrollbarBoxBtn->SetMaxY(height-30); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + gameIndex = new int[pagesize]; + game = new GuiButton * [pagesize]; + gameTxt = new GuiText * [pagesize]; + gameTxtOver = new GuiText * [pagesize]; + gameBg = new GuiImage * [pagesize]; + newImg = new GuiImage * [pagesize]; - gameIndex = new int[pagesize]; - game = new GuiButton * [pagesize]; - gameTxt = new GuiText * [pagesize]; - gameTxtOver = new GuiText * [pagesize]; - gameBg = new GuiImage * [pagesize]; - newImg = new GuiImage * [pagesize]; - - for (int i=0; i < pagesize; i++) { - gameTxt[i] = new GuiText(get_title(&gameList[i]), 20, THEME.gametext); - gameTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - gameTxt[i]->SetPosition(24,0); - gameTxt[i]->SetMaxWidth(maxTextWidth, GuiText::DOTTED); + for(int i=0; i < pagesize; i++) + { + gameTxt[i] = new GuiText(get_title(&gameList[i]), 20, THEME.gametext); + gameTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + gameTxt[i]->SetPosition(24,0); + gameTxt[i]->SetMaxWidth(maxTextWidth, GuiText::DOTTED); - gameTxtOver[i] = new GuiText(get_title(&gameList[i]), 20, THEME.gametext); - gameTxtOver[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - gameTxtOver[i]->SetPosition(24,0); - gameTxtOver[i]->SetMaxWidth(maxTextWidth, GuiText::SCROLL); + gameTxtOver[i] = new GuiText(get_title(&gameList[i]), 20, THEME.gametext); + gameTxtOver[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + gameTxtOver[i]->SetPosition(24,0); + gameTxtOver[i]->SetMaxWidth(maxTextWidth, GuiText::SCROLL); - gameBg[i] = new GuiImage(bgGamesEntry); + gameBg[i] = new GuiImage(bgGamesEntry); - newImg[i] = new GuiImage(newGames); - newImg[i]->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); - newImg[i]->SetVisible(false); + newImg[i] = new GuiImage(newGames); + newImg[i]->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); + newImg[i]->SetVisible(false); - game[i] = new GuiButton(width-28,GAMESELECTSIZE); - game[i]->SetParent(this); - game[i]->SetLabel(gameTxt[i]); - game[i]->SetLabelOver(gameTxtOver[i]); - game[i]->SetIcon(newImg[i]); - game[i]->SetImageOver(gameBg[i]); - game[i]->SetPosition(5,GAMESELECTSIZE*i+4); - game[i]->SetRumble(false); - game[i]->SetTrigger(trigA); - game[i]->SetSoundClick(btnSoundClick); + game[i] = new GuiButton(width-28,GAMESELECTSIZE); + game[i]->SetParent(this); + game[i]->SetLabel(gameTxt[i]); + game[i]->SetLabelOver(gameTxtOver[i]); + game[i]->SetIcon(newImg[i]); + game[i]->SetImageOver(gameBg[i]); + game[i]->SetPosition(5,GAMESELECTSIZE*i+4); + game[i]->SetRumble(false); + game[i]->SetTrigger(trigA); + game[i]->SetSoundClick(btnSoundClick); - gameIndex[i] = i; - } - UpdateListEntries(); + gameIndex[i] = i; + } + UpdateListEntries(); } /** * Destructor for the GuiGameBrowser class. */ -GuiGameBrowser::~GuiGameBrowser() { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; - delete scrollbarImg; - delete arrowDownImg; - delete arrowDownOverImg; - delete arrowUpImg; - delete arrowUpOverImg; - delete scrollbarBoxImg; - delete scrollbarBoxOverImg; - delete scrollbar; - delete arrowDown; - delete arrowDownOver; - delete arrowUp; - delete arrowUpOver; - delete scrollbarBox; - delete scrollbarBoxOver; - delete bgGameImg; - delete bgGames; - delete bgGamesEntry; - delete newGames; +GuiGameBrowser::~GuiGameBrowser() +{ + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; + delete scrollbarImg; + delete arrowDownImg; + delete arrowDownOverImg; + delete arrowUpImg; + delete arrowUpOverImg; + delete scrollbarBoxImg; + delete scrollbarBoxOverImg; + delete scrollbar; + delete arrowDown; + delete arrowDownOver; + delete arrowUp; + delete arrowUpOver; + delete scrollbarBox; + delete scrollbarBoxOver; + delete bgGameImg; + delete bgGames; + delete bgGamesEntry; + delete newGames; - delete trigA; - delete trigHeldA; - delete btnSoundClick; + delete trigA; + delete trigHeldA; + delete btnSoundClick; - for (int i=0; iResetState(); + for(int i=0; iResetState(); - if (f == 1) - game[selectedItem]->SetState(STATE_SELECTED); + if(f == 1) + game[selectedItem]->SetState(STATE_SELECTED); } -void GuiGameBrowser::ResetState() { - LOCK(this); - if (state != STATE_DISABLED) { - state = STATE_DEFAULT; - stateChan = -1; - } +void GuiGameBrowser::ResetState() +{ + LOCK(this); + if(state != STATE_DISABLED) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for (int i=0; iResetState(); - } + for(int i=0; iResetState(); + } } -int GuiGameBrowser::GetOffset() { - return listOffset; +int GuiGameBrowser::GetOffset() +{ + return listOffset; } -int GuiGameBrowser::GetClickedOption() { - int found = -1; - for (int i=0; iGetState() == STATE_CLICKED) { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; +int GuiGameBrowser::GetClickedOption() +{ + int found = -1; + for(int i=0; iGetState() == STATE_CLICKED) + { + game[i]->SetState(STATE_SELECTED); + found = gameIndex[i]; + break; + } + } + return found; } -int GuiGameBrowser::GetSelectedOption() { - int found = -1; - for (int i=0; iGetState() == STATE_SELECTED) { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; +int GuiGameBrowser::GetSelectedOption() +{ + int found = -1; + for(int i=0; iGetState() == STATE_SELECTED) + { + game[i]->SetState(STATE_SELECTED); + found = gameIndex[i]; + break; + } + } + return found; } /**************************************************************************** @@ -263,297 +278,362 @@ int GuiGameBrowser::GetSelectedOption() { * Help function to find the next visible menu item on the list ***************************************************************************/ -int GuiGameBrowser::FindMenuItem(int currentItem, int direction) { - int nextItem = currentItem + direction; +int GuiGameBrowser::FindMenuItem(int currentItem, int direction) +{ + int nextItem = currentItem + direction; - if (nextItem < 0 || nextItem >= gameCnt) - return -1; + if(nextItem < 0 || nextItem >= gameCnt) + return -1; - if (strlen(get_title(&gameList[nextItem])) > 0) - return nextItem; - else - return FindMenuItem(nextItem, direction); + if(strlen(get_title(&gameList[nextItem])) > 0) + return nextItem; + else + return FindMenuItem(nextItem, direction); } /** * Draw the button on screen */ -void GuiGameBrowser::Draw() { - LOCK(this); - if (!this->IsVisible() || !gameCnt) - return; +void GuiGameBrowser::Draw() +{ + LOCK(this); + if(!this->IsVisible() || !gameCnt) + return; - bgGameImg->Draw(); + bgGameImg->Draw(); - int next = listOffset; + int next = listOffset; - for (int i=0; i= 0) { - game[i]->Draw(); - next = this->FindMenuItem(next, 1); - } else - break; - } + for(int i=0; i= 0) + { + game[i]->Draw(); + next = this->FindMenuItem(next, 1); + } + else + break; + } - if (scrollbaron == 1) { - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); - } - this->UpdateEffects(); + if(scrollbaron == 1) { + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); + } + this->UpdateEffects(); } -void GuiGameBrowser::UpdateListEntries() { - int next = listOffset; - for (int i=0; i= 0) { - if (game[i]->GetState() == STATE_DISABLED) { - game[i]->SetVisible(true); - game[i]->SetState(STATE_DEFAULT); - } - gameTxt[i]->SetText(get_title(&gameList[next])); - gameTxt[i]->SetPosition(24, 0); - gameTxtOver[i]->SetText(get_title(&gameList[next])); - gameTxtOver[i]->SetPosition(24, 0); +void GuiGameBrowser::UpdateListEntries() +{ + int next = listOffset; + for(int i=0; i= 0) + { + if(game[i]->GetState() == STATE_DISABLED) + { + game[i]->SetVisible(true); + game[i]->SetState(STATE_DEFAULT); + } + gameTxt[i]->SetText(get_title(&gameList[next])); + gameTxt[i]->SetPosition(24, 0); + gameTxtOver[i]->SetText(get_title(&gameList[next])); + gameTxtOver[i]->SetPosition(24, 0); - if (Settings.marknewtitles) { - bool isNew = NewTitles::Instance()->IsNew(gameList[next].id); - if (isNew) { - gameTxt[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), GuiText::DOTTED); - gameTxtOver[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), GuiText::SCROLL); - } else { - gameTxt[i]->SetMaxWidth(maxTextWidth, GuiText::DOTTED); - gameTxtOver[i]->SetMaxWidth(maxTextWidth, GuiText::SCROLL); - } - newImg[i]->SetVisible(isNew); - } + if (Settings.marknewtitles) { + bool isNew = NewTitles::Instance()->IsNew(gameList[next].id); + if (isNew) { + gameTxt[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), GuiText::DOTTED); + gameTxtOver[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), GuiText::SCROLL); + } else { + gameTxt[i]->SetMaxWidth(maxTextWidth, GuiText::DOTTED); + gameTxtOver[i]->SetMaxWidth(maxTextWidth, GuiText::SCROLL); + } + newImg[i]->SetVisible(isNew); + } - gameIndex[i] = next; - next = this->FindMenuItem(next, 1); - } else { - game[i]->SetVisible(false); - game[i]->SetState(STATE_DISABLED); - } - } + gameIndex[i] = next; + next = this->FindMenuItem(next, 1); + } + else + { + game[i]->SetVisible(false); + game[i]->SetState(STATE_DISABLED); + } + } } -void GuiGameBrowser::Update(GuiTrigger * t) { - LOCK(this); - if (state == STATE_DISABLED || !t || !gameCnt) - return; +void GuiGameBrowser::Update(GuiTrigger * t) +{ + LOCK(this); + if(state == STATE_DISABLED || !t || !gameCnt) + return; - int next, prev; - int old_listOffset = listOffset; - static int position2; - // scrolldelay affects how fast the list scrolls - // when the arrows are clicked - float scrolldelay = 3.5; + int next, prev; + int old_listOffset = listOffset; + static int position2; + // scrolldelay affects how fast the list scrolls + // when the arrows are clicked + float scrolldelay = 3.5; - if (scrollbaron == 1) { - // update the location of the scroll box based on the position in the option list - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); - } + if (scrollbaron == 1) { + // update the location of the scroll box based on the position in the option list + arrowUpBtn->Update(t); + arrowDownBtn->Update(t); + scrollbarBoxBtn->Update(t); + } - next = listOffset; + next = listOffset; u32 buttonshold = ButtonsHold(); - if (buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN) { + if(buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN) { - for (int i=0; i= 0) + for(int i=0; i= 0) next = this->FindMenuItem(next, 1); - if (focus) { - if (i != selectedItem && game[i]->GetState() == STATE_SELECTED) + if(focus) + { + if(i != selectedItem && game[i]->GetState() == STATE_SELECTED) game[i]->ResetState(); - else if (i == selectedItem && game[i]->GetState() == STATE_DEFAULT) + else if(i == selectedItem && game[i]->GetState() == STATE_DEFAULT) game[selectedItem]->SetState(STATE_SELECTED, t->chan); } game[i]->Update(t); - if (game[i]->GetState() == STATE_SELECTED) { + if(game[i]->GetState() == STATE_SELECTED) + { selectedItem = i; } } } - // pad and joystick navigation - if (!focus || !gameCnt) - return; // skip navigation + // pad and joystick navigation + if(!focus || !gameCnt) + return; // skip navigation - if (scrollbaron == 1) { + if (scrollbaron == 1) + { - if (t->Down() || arrowDownBtn->GetState() == STATE_CLICKED || arrowDownBtn->GetState() == STATE_HELD) { //down + if (t->Down() || arrowDownBtn->GetState() == STATE_CLICKED || arrowDownBtn->GetState() == STATE_HELD) //down + { - next = this->FindMenuItem(gameIndex[selectedItem], 1); + next = this->FindMenuItem(gameIndex[selectedItem], 1); - if (next >= 0) { - if (selectedItem == pagesize-1) { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } else if (game[selectedItem+1]->IsVisible()) { - game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } + if(next >= 0) + { + if(selectedItem == pagesize-1) + { + // move list down by 1 + listOffset = this->FindMenuItem(listOffset, 1); + } + else if(game[selectedItem+1]->IsVisible()) + { + game[selectedItem]->ResetState(); + game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); + selectedItem++; + } // scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - if (!(ButtonsHold() & WPAD_BUTTON_A)) - arrowDownBtn->ResetState(); - } else if (t->Up() || arrowUpBtn->GetState() == STATE_CLICKED || arrowUpBtn->GetState() == STATE_HELD) { //up - prev = this->FindMenuItem(gameIndex[selectedItem], -1); + usleep(10000 * scrolldelay); + } + if (!(ButtonsHold() & WPAD_BUTTON_A)) + arrowDownBtn->ResetState(); + } + else if(t->Up() || arrowUpBtn->GetState() == STATE_CLICKED || arrowUpBtn->GetState() == STATE_HELD) //up + { + prev = this->FindMenuItem(gameIndex[selectedItem], -1); - if (prev >= 0) { - if (selectedItem == 0) { - // move list up by 1 - listOffset = prev; - } else { - game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } + if(prev >= 0) + { + if(selectedItem == 0) + { + // move list up by 1 + listOffset = prev; + } + else + { + game[selectedItem]->ResetState(); + game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); + selectedItem--; + } // scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - if (!(ButtonsHold() & WPAD_BUTTON_A)) - arrowUpBtn->ResetState(); - } - int position1 = t->wpad.ir.y; + usleep(10000 * scrolldelay); + } + if (!(ButtonsHold() & WPAD_BUTTON_A)) + arrowUpBtn->ResetState(); + } + int position1 = t->wpad.ir.y; - if (position2 == 0 && position1 > 0) { - position2 = position1; - } + if (position2 == 0 && position1 > 0) + { + position2 = position1; + } - if ((buttonshold & WPAD_BUTTON_B) && position1 > 0) { - scrollbarBoxBtn->ScrollIsOn(1); - if (position2 > position1) { + if ((buttonshold & WPAD_BUTTON_B) && position1 > 0) + { + scrollbarBoxBtn->ScrollIsOn(1); + if (position2 > position1) + { - prev = this->FindMenuItem(gameIndex[selectedItem], -1); + prev = this->FindMenuItem(gameIndex[selectedItem], -1); - if (prev >= 0) { - if (selectedItem == 0) { - // move list up by 1 - listOffset = prev; - } else { - game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } + if(prev >= 0) + { + if(selectedItem == 0) + { + // move list up by 1 + listOffset = prev; + } + else + { + game[selectedItem]->ResetState(); + game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); + selectedItem--; + } // scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - } else if (position2 < position1) { - next = this->FindMenuItem(gameIndex[selectedItem], 1); + usleep(10000 * scrolldelay); + } + } + else if (position2 < position1) + { + next = this->FindMenuItem(gameIndex[selectedItem], 1); - if (next >= 0) { - if (selectedItem == pagesize-1) { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } else if (game[selectedItem+1]->IsVisible()) { - game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } + if(next >= 0) + { + if(selectedItem == pagesize-1) + { + // move list down by 1 + listOffset = this->FindMenuItem(listOffset, 1); + } + else if(game[selectedItem+1]->IsVisible()) + { + game[selectedItem]->ResetState(); + game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); + selectedItem++; + } // scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - } + usleep(10000 * scrolldelay); + } + } - } else if (!(buttonshold & WPAD_BUTTON_B)) { - scrollbarBoxBtn->ScrollIsOn(0); - position2 = 0; - } + } + else if(!(buttonshold & WPAD_BUTTON_B)) + { + scrollbarBoxBtn->ScrollIsOn(0); + position2 = 0; + } - if (scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid && gameCnt > pagesize) { - // allow dragging of scrollbar box - scrollbarBoxBtn->SetPosition(width/2-18+7,0); - int position = t->wpad.ir.y - 32 - scrollbarBoxBtn->GetTop(); + if(scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid && gameCnt > pagesize) + { + // allow dragging of scrollbar box + scrollbarBoxBtn->SetPosition(width/2-18+7,0); + int position = t->wpad.ir.y - 32 - scrollbarBoxBtn->GetTop(); - listOffset = (position * gameCnt)/(25.2 * pagesize) - selectedItem; + listOffset = (position * gameCnt)/(25.2 * pagesize) - selectedItem; - if (listOffset <= 0) { - listOffset = 0; - selectedItem = 0; - } else if (listOffset+pagesize >= gameCnt) { - listOffset = gameCnt - pagesize; - selectedItem = pagesize-1; - } + if(listOffset <= 0) + { + listOffset = 0; + selectedItem = 0; + } + else if(listOffset+pagesize >= gameCnt) + { + listOffset = gameCnt - pagesize; + selectedItem = pagesize-1; + } - } - int positionbar = (25.2 * pagesize)*(listOffset + selectedItem) / gameCnt; + } + int positionbar = (25.2 * pagesize)*(listOffset + selectedItem) / gameCnt; - if (positionbar > (24 * pagesize)) - positionbar = (24 * pagesize); - scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); + if(positionbar > (24 * pagesize)) + positionbar = (24 * pagesize); + scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); - if (t->Right()) { //skip pagesize # of games if right is pressed - if (listOffset < gameCnt && gameCnt > pagesize) { - listOffset =listOffset+ pagesize; - if (listOffset+pagesize >= gameCnt) - listOffset = gameCnt-pagesize; - } - } else if (t->Left()) { - if (listOffset > 0) { - listOffset =listOffset- pagesize; - if (listOffset < 0) - listOffset = 0; - } - } + if(t->Right()) //skip pagesize # of games if right is pressed + { + if(listOffset < gameCnt && gameCnt > pagesize) + { + listOffset =listOffset+ pagesize; + if(listOffset+pagesize >= gameCnt) + listOffset = gameCnt-pagesize; + } + } + else if(t->Left()) + { + if(listOffset > 0) + { + listOffset =listOffset- pagesize; + if(listOffset < 0) + listOffset = 0; + } + } - } else { - if (t->Down()) { //if there isn't a scrollbar and down is pressed - next = this->FindMenuItem(gameIndex[selectedItem], 1); + } + else + { + if(t->Down()) //if there isn't a scrollbar and down is pressed + { + next = this->FindMenuItem(gameIndex[selectedItem], 1); - if (next >= 0) { - if (selectedItem == pagesize-1) { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } else if (game[selectedItem+1]->IsVisible()) { - game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - } - } else if (t->Up()) { //up - prev = this->FindMenuItem(gameIndex[selectedItem], -1); + if(next >= 0) + { + if(selectedItem == pagesize-1) + { + // move list down by 1 + listOffset = this->FindMenuItem(listOffset, 1); + } + else if(game[selectedItem+1]->IsVisible()) + { + game[selectedItem]->ResetState(); + game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); + selectedItem++; + } + } + } + else if(t->Up()) //up + { + prev = this->FindMenuItem(gameIndex[selectedItem], -1); - if (prev >= 0) { - if (selectedItem == 0) { - // move list up by 1 - listOffset = prev; - } else { - game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - } - } - } + if(prev >= 0) + { + if(selectedItem == 0) + { + // move list up by 1 + listOffset = prev; + } + else + { + game[selectedItem]->ResetState(); + game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); + selectedItem--; + } + } + } + } - if (old_listOffset != listOffset) - UpdateListEntries(); + if(old_listOffset != listOffset) + UpdateListEntries(); - if (updateCB) - updateCB(this); + if(updateCB) + updateCB(this); } -void GuiGameBrowser::Reload(struct discHdr * l, int count) { - LOCK(this); - gameList = l; - gameCnt = count; - scrollbaron = (gameCnt > pagesize) ? 1 : 0; - selectedItem = 0; - listOffset = 0; - focus = 1; - UpdateListEntries(); +void GuiGameBrowser::Reload(struct discHdr * l, int count) +{ + LOCK(this); + gameList = l; + gameCnt = count; + scrollbaron = (gameCnt > pagesize) ? 1 : 0; + selectedItem = 0; + listOffset = 0; + focus = 1; + UpdateListEntries(); - for (int i=0; iResetState(); + for(int i=0; iResetState(); } diff --git a/source/libwiigui/gui_gamebrowser.h b/source/libwiigui/gui_gamebrowser.h index 75639c31..88c71df7 100644 --- a/source/libwiigui/gui_gamebrowser.h +++ b/source/libwiigui/gui_gamebrowser.h @@ -1,67 +1,68 @@ -#ifndef _GUIGAMEBROWSER_H_ +#ifndef _GUIGAMEBROWSER_H_ #define _GUIGAMEBROWSER_H_ #include "gui.h" #include "../usbloader/disc.h" -class GuiGameBrowser : public GuiElement { -public: - GuiGameBrowser(int w, int h, struct discHdr *l, int gameCnt, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); - ~GuiGameBrowser(); - int FindMenuItem(int c, int d); - int GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); - int GetOffset(); - void Reload(struct discHdr * l, int count); - //GuiText * optionVal[PAGESIZE]; -protected: - void UpdateListEntries(); - int selectedItem; - int listOffset; - int scrollbaron; - int pagesize; - int maxTextWidth; +class GuiGameBrowser : public GuiElement +{ + public: + GuiGameBrowser(int w, int h, struct discHdr *l, int gameCnt, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); + ~GuiGameBrowser(); + int FindMenuItem(int c, int d); + int GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus(int f); + void Draw(); + void Update(GuiTrigger * t); + int GetOffset(); + void Reload(struct discHdr * l, int count); + //GuiText * optionVal[PAGESIZE]; + protected: + void UpdateListEntries(); + int selectedItem; + int listOffset; + int scrollbaron; + int pagesize; + int maxTextWidth; - struct discHdr * gameList; - int gameCnt; + struct discHdr * gameList; + int gameCnt; - int * gameIndex; - GuiButton ** game; - GuiText ** gameTxt; - GuiText ** gameTxtOver; - GuiImage ** gameBg; - GuiImage ** newImg; + int * gameIndex; + GuiButton ** game; + GuiText ** gameTxt; + GuiText ** gameTxtOver; + GuiImage ** gameBg; + GuiImage ** newImg; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgGameImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowDownOverImg; - GuiImage * arrowUpImg; - GuiImage * arrowUpOverImg; - GuiImage * scrollbarBoxImg; - GuiImage * scrollbarBoxOverImg; + GuiImage * bgGameImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowDownOverImg; + GuiImage * arrowUpImg; + GuiImage * arrowUpOverImg; + GuiImage * scrollbarBoxImg; + GuiImage * scrollbarBoxOverImg; - GuiImageData * bgGames; - GuiImageData * bgGamesEntry; - GuiImageData * newGames; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowDownOver; - GuiImageData * arrowUp; - GuiImageData * arrowUpOver; - GuiImageData * scrollbarBox; - GuiImageData * scrollbarBoxOver; + GuiImageData * bgGames; + GuiImageData * bgGamesEntry; + GuiImageData * newGames; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowDownOver; + GuiImageData * arrowUp; + GuiImageData * arrowUpOver; + GuiImageData * scrollbarBox; + GuiImageData * scrollbarBoxOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigHeldA; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigHeldA; }; #endif diff --git a/source/libwiigui/gui_gamecarousel.cpp b/source/libwiigui/gui_gamecarousel.cpp index b1dad13b..c32c6107 100644 --- a/source/libwiigui/gui_gamecarousel.cpp +++ b/source/libwiigui/gui_gamecarousel.cpp @@ -25,396 +25,433 @@ #define RADIUS 780 #define IN_SPEED 175 #define SHIFT_SPEED 75 -#define SPEED_STEP 4 +#define SPEED_STEP 4 #define SPEED_LIMIT 250 -static inline int OFFSETLIMIT(int Offset, int gameCnt) { - while (Offset < 0) Offset+=gameCnt; - return Offset%gameCnt; +static inline int OFFSETLIMIT(int Offset, int gameCnt) +{ + while(Offset < 0) Offset+=gameCnt; + return Offset%gameCnt; } #define GetGameIndex(pageEntry, listOffset, gameCnt) OFFSETLIMIT(listOffset+pageEntry, gameCnt) -static GuiImageData *GameCarouselLoadCoverImage(void * Arg) { - return LoadCoverImage((struct discHdr *)Arg, true, false); +static GuiImageData *GameCarouselLoadCoverImage(void * Arg) +{ + return LoadCoverImage((struct discHdr *)Arg, true, false); } /** * Constructor for the GuiGameCarousel class. */ GuiGameCarousel::GuiGameCarousel(int w, int h, struct discHdr * l, int count, const char *themePath, const u8 *imagebg, int selected, int offset) : - noCover(nocover_png) { - width = w; - height = h; - gameCnt = count; - gameList = l; - pagesize = (gameCnt < 11) ? gameCnt : 11; - listOffset = 0; - selectable = true; - selectedItem = -1; - focus = 1; // allow focus - clickedItem = -1; +noCover(nocover_png) +{ + width = w; + height = h; + gameCnt = count; + gameList = l; + pagesize = (gameCnt < 11) ? gameCnt : 11; + listOffset = 0; + selectable = true; + selectedItem = -1; + focus = 1; // allow focus + clickedItem = -1; + + speed = 0; + char imgPath[100]; - speed = 0; - char imgPath[100]; + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigL = new GuiTrigger; + trigL->SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); + trigR = new GuiTrigger; + trigR->SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); + trigPlus = new GuiTrigger; + trigPlus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); + trigMinus = new GuiTrigger; + trigMinus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigL = new GuiTrigger; - trigL->SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); - trigR = new GuiTrigger; - trigR->SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); - trigPlus = new GuiTrigger; - trigPlus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - trigMinus = new GuiTrigger; - trigMinus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); + btnSoundClick = new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - btnSoundClick = new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); + imgLeft = new GuiImageData(imgPath, startgame_arrow_left_png); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); + imgRight = new GuiImageData(imgPath, startgame_arrow_right_png); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); - imgLeft = new GuiImageData(imgPath, startgame_arrow_left_png); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); - imgRight = new GuiImageData(imgPath, startgame_arrow_right_png); + int btnHeight = (int) lround(sqrt(RADIUS*RADIUS - 90000)-RADIUS-50); - int btnHeight = (int) lround(sqrt(RADIUS*RADIUS - 90000)-RADIUS-50); + btnLeftImg = new GuiImage(imgLeft); + if (Settings.wsprompt == yes) + btnLeftImg->SetWidescreen(CFG.widescreen); + btnLeft = new GuiButton(imgLeft->GetWidth(), imgLeft->GetHeight()); + btnLeft->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + btnLeft->SetPosition(20, btnHeight); + btnLeft->SetParent(this); + btnLeft->SetImage(btnLeftImg); + btnLeft->SetSoundOver(btnSoundOver); + btnLeft->SetTrigger(trigA); + btnLeft->SetTrigger(trigL); + btnLeft->SetTrigger(trigMinus); + btnLeft->SetEffectGrow(); - btnLeftImg = new GuiImage(imgLeft); - if (Settings.wsprompt == yes) - btnLeftImg->SetWidescreen(CFG.widescreen); - btnLeft = new GuiButton(imgLeft->GetWidth(), imgLeft->GetHeight()); - btnLeft->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - btnLeft->SetPosition(20, btnHeight); - btnLeft->SetParent(this); - btnLeft->SetImage(btnLeftImg); - btnLeft->SetSoundOver(btnSoundOver); - btnLeft->SetTrigger(trigA); - btnLeft->SetTrigger(trigL); - btnLeft->SetTrigger(trigMinus); - btnLeft->SetEffectGrow(); + btnRightImg = new GuiImage(imgRight); + if (Settings.wsprompt == yes) + btnRightImg->SetWidescreen(CFG.widescreen); + btnRight = new GuiButton(imgRight->GetWidth(), imgRight->GetHeight()); + btnRight->SetParent(this); + btnRight->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); + btnRight->SetPosition(-20, btnHeight); + btnRight->SetImage(btnRightImg); + btnRight->SetSoundOver(btnSoundOver); + btnRight->SetTrigger(trigA); + btnRight->SetTrigger(trigR); + btnRight->SetTrigger(trigPlus); + btnRight->SetEffectGrow(); + + gamename = new GuiText(" ", 18, THEME.info); + gamename->SetParent(this); + gamename->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + gamename->SetPosition(0, 330); + gamename->SetMaxWidth(280, GuiText::DOTTED); - btnRightImg = new GuiImage(imgRight); - if (Settings.wsprompt == yes) - btnRightImg->SetWidescreen(CFG.widescreen); - btnRight = new GuiButton(imgRight->GetWidth(), imgRight->GetHeight()); - btnRight->SetParent(this); - btnRight->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); - btnRight->SetPosition(-20, btnHeight); - btnRight->SetImage(btnRightImg); - btnRight->SetSoundOver(btnSoundOver); - btnRight->SetTrigger(trigA); - btnRight->SetTrigger(trigR); - btnRight->SetTrigger(trigPlus); - btnRight->SetEffectGrow(); + gameIndex = new int[pagesize]; + game = new GuiButton * [pagesize]; + coverImg = new GuiImageAsync * [pagesize]; - gamename = new GuiText(" ", 18, THEME.info); - gamename->SetParent(this); - gamename->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - gamename->SetPosition(0, 330); - gamename->SetMaxWidth(280, GuiText::DOTTED); + for(int i=0; i < pagesize; i++) + { + //------------------------ + // Index + //------------------------ + gameIndex[i] = GetGameIndex(i, listOffset, gameCnt); - gameIndex = new int[pagesize]; - game = new GuiButton * [pagesize]; - coverImg = new GuiImageAsync * [pagesize]; + //------------------------ + // Image + //------------------------ + coverImg[i] = new(std::nothrow) GuiImageAsync(GameCarouselLoadCoverImage, &gameList[gameIndex[i]], sizeof(struct discHdr), &noCover); + if(coverImg[i]) + coverImg[i]->SetWidescreen(CFG.widescreen); - for (int i=0; i < pagesize; i++) { - //------------------------ - // Index - //------------------------ - gameIndex[i] = GetGameIndex(i, listOffset, gameCnt); + //------------------------ + // GameButton + //------------------------ - //------------------------ - // Image - //------------------------ - coverImg[i] = new(std::nothrow) GuiImageAsync(GameCarouselLoadCoverImage, &gameList[gameIndex[i]], sizeof(struct discHdr), &noCover); - if (coverImg[i]) - coverImg[i]->SetWidescreen(CFG.widescreen); - - //------------------------ - // GameButton - //------------------------ - - game[i] = new GuiButton(122,244); - game[i]->SetParent(this); - game[i]->SetAlignment(ALIGN_CENTRE,ALIGN_MIDDLE); - game[i]->SetPosition(0,740); - game[i]->SetImage(coverImg[i]); + game[i] = new GuiButton(122,244); + game[i]->SetParent(this); + game[i]->SetAlignment(ALIGN_CENTRE,ALIGN_MIDDLE); + game[i]->SetPosition(0,740); + game[i]->SetImage(coverImg[i]); game[i]->SetScale(SCALE); - game[i]->SetRumble(false); - game[i]->SetTrigger(trigA); - game[i]->SetSoundClick(btnSoundClick); - game[i]->SetClickable(true); - game[i]->SetEffect(EFFECT_GOROUND, IN_SPEED, 90-(pagesize-2*i-1)*DEG_OFFSET/2, RADIUS, 180, 1, 0, RADIUS); - } + game[i]->SetRumble(false); + game[i]->SetTrigger(trigA); + game[i]->SetSoundClick(btnSoundClick); + game[i]->SetClickable(true); + game[i]->SetEffect(EFFECT_GOROUND, IN_SPEED, 90-(pagesize-2*i-1)*DEG_OFFSET/2, RADIUS, 180, 1, 0, RADIUS); + } } /** * Destructor for the GuiGameCarousel class. */ -GuiGameCarousel::~GuiGameCarousel() { - delete imgRight; - delete imgLeft; - delete btnLeftImg; - delete btnRightImg; - delete btnRight; - delete btnLeft; +GuiGameCarousel::~GuiGameCarousel() +{ + delete imgRight; + delete imgLeft; + delete btnLeftImg; + delete btnRightImg; + delete btnRight; + delete btnLeft; - delete trigA; - delete trigL; - delete trigR; - delete trigPlus; - delete trigMinus; - delete btnSoundClick; - delete btnSoundOver; + delete trigA; + delete trigL; + delete trigR; + delete trigPlus; + delete trigMinus; + delete btnSoundClick; + delete btnSoundOver; delete gamename; - for (int i=0; iResetState(); + for(int i=0; iResetState(); - if (f == 1 && selectedItem>=0) - game[selectedItem]->SetState(STATE_SELECTED); + if(f == 1 && selectedItem>=0) + game[selectedItem]->SetState(STATE_SELECTED); } -void GuiGameCarousel::ResetState() { - LOCK(this); - if (state != STATE_DISABLED) { - state = STATE_DEFAULT; - stateChan = -1; - } +void GuiGameCarousel::ResetState() +{ + LOCK(this); + if(state != STATE_DISABLED) { + state = STATE_DEFAULT; + stateChan = -1; + } - for (int i=0; iResetState(); - } + for(int i=0; iResetState(); + } } -int GuiGameCarousel::GetOffset() { - LOCK(this); - return listOffset; +int GuiGameCarousel::GetOffset() +{ + LOCK(this); + return listOffset; } -int GuiGameCarousel::GetClickedOption() { - LOCK(this); - int found = -1; - if (clickedItem>=0) { - game[clickedItem]->SetState(STATE_SELECTED); - found = gameIndex[clickedItem]; - clickedItem=-1; - } - return found; +int GuiGameCarousel::GetClickedOption() +{ + LOCK(this); + int found = -1; + if (clickedItem>=0) + { + game[clickedItem]->SetState(STATE_SELECTED); + found = gameIndex[clickedItem]; + clickedItem=-1; + } + return found; } -int GuiGameCarousel::GetSelectedOption() { - LOCK(this); - int found = -1; - for (int i=0; iGetState() == STATE_SELECTED) { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; +int GuiGameCarousel::GetSelectedOption() +{ + LOCK(this); + int found = -1; + for(int i=0; iGetState() == STATE_SELECTED) + { + game[i]->SetState(STATE_SELECTED); + found = gameIndex[i]; + break; + } + } + return found; } /** * Draw the button on screen */ -void GuiGameCarousel::Draw() { - LOCK(this); - if (!this->IsVisible() || !gameCnt) - return; +void GuiGameCarousel::Draw() +{ + LOCK(this); + if(!this->IsVisible() || !gameCnt) + return; - for (int i=0; iDraw(); + for(int i=0; iDraw(); + + gamename->Draw(); - gamename->Draw(); + if(gameCnt > 6) + { + btnRight->Draw(); + btnLeft->Draw(); + } + + //!Draw tooltip after the Images to have it on top + if (focus && Settings.tooltips == TooltipsOn) + for(int i=0; iDrawTooltip(); - if (gameCnt > 6) { - btnRight->Draw(); - btnLeft->Draw(); - } - - //!Draw tooltip after the Images to have it on top - if (focus && Settings.tooltips == TooltipsOn) - for (int i=0; iDrawTooltip(); - - this->UpdateEffects(); + this->UpdateEffects(); } -void GuiGameCarousel::Update(GuiTrigger * t) { - LOCK(this); - if (state == STATE_DISABLED || !t || !gameCnt) - return; +void GuiGameCarousel::Update(GuiTrigger * t) +{ + LOCK(this); + if(state == STATE_DISABLED || !t || !gameCnt) + return; - btnRight->Update(t); - btnLeft->Update(t); + btnRight->Update(t); + btnLeft->Update(t); + + if(game[0]->GetEffect() & EFFECT_GOROUND || game[pagesize-1]->GetEffect() & EFFECT_GOROUND) + { + return; // skip when rotate + } + + // find selected + clicked + int selectedItem_old = selectedItem; + selectedItem = -1; + clickedItem = -1; + for(int i=pagesize-1; i>=0; i--) + { + game[i]->Update(t); + if(game[i]->GetState() == STATE_SELECTED) + { + selectedItem = i; + } + if(game[i]->GetState() == STATE_CLICKED) + { + clickedItem = i; + } - if (game[0]->GetEffect() & EFFECT_GOROUND || game[pagesize-1]->GetEffect() & EFFECT_GOROUND) { - return; // skip when rotate - } + } - // find selected + clicked - int selectedItem_old = selectedItem; - selectedItem = -1; - clickedItem = -1; - for (int i=pagesize-1; i>=0; i--) { - game[i]->Update(t); - if (game[i]->GetState() == STATE_SELECTED) { - selectedItem = i; - } - if (game[i]->GetState() == STATE_CLICKED) { - clickedItem = i; - } + /// OnOver-Effect + GameText + Tooltop + if(selectedItem_old != selectedItem) + { + if(selectedItem>=0) + { + game[selectedItem]->SetEffect(EFFECT_SCALE, 1, 130); + char *gameTitle = get_title(&gameList[gameIndex[selectedItem]]); + gamename->SetText(gameTitle); + } + else + gamename->SetText((char*)NULL); + if(selectedItem_old>=0) + game[selectedItem_old]->SetEffect(EFFECT_SCALE, -1, 100); + } + // navigation + if(focus && gameCnt>6) + { - } + int newspeed = 0; + // Left/Right Navigation + if (btnLeft->GetState() == STATE_CLICKED) + { + WPAD_ScanPads(); + u16 buttons = 0; + for(int i=0; i<4; i++) + buttons |= WPAD_ButtonsHeld(i); + if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_MINUS) || t->Left())) + { + btnLeft->ResetState(); + return; + } - /// OnOver-Effect + GameText + Tooltop - if (selectedItem_old != selectedItem) { - if (selectedItem>=0) { - game[selectedItem]->SetEffect(EFFECT_SCALE, 1, 130); - char *gameTitle = get_title(&gameList[gameIndex[selectedItem]]); - gamename->SetText(gameTitle); - } else - gamename->SetText((char*)NULL); - if (selectedItem_old>=0) - game[selectedItem_old]->SetEffect(EFFECT_SCALE, -1, 100); - } - // navigation - if (focus && gameCnt>6) { - - int newspeed = 0; - // Left/Right Navigation - if (btnLeft->GetState() == STATE_CLICKED) { - WPAD_ScanPads(); - u16 buttons = 0; - for (int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if (!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_MINUS) || t->Left())) { - btnLeft->ResetState(); - return; - } - - if (Settings.xflip==sysmenu || Settings.xflip==yes || Settings.xflip==disk3d) - newspeed = SHIFT_SPEED; - else - newspeed = -SHIFT_SPEED; - } else if (btnRight->GetState() == STATE_CLICKED) { - WPAD_ScanPads(); - u16 buttons = 0; - for (int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if (!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_PLUS) || t->Right())) { - btnRight->ResetState(); - return; - } - if (Settings.xflip==sysmenu ||Settings.xflip==yes || Settings.xflip==disk3d) - newspeed = -SHIFT_SPEED; - else - newspeed = SHIFT_SPEED; - } - if (newspeed) { - if (speed==0) - speed = newspeed; - else if (speed>0) { - if ((speed+=SPEED_STEP) > SPEED_LIMIT) - speed = SPEED_LIMIT; - } else { - if ((speed-=SPEED_STEP) < -SPEED_LIMIT) - speed = -SPEED_LIMIT; - } - } else - speed = 0; + if (Settings.xflip==sysmenu || Settings.xflip==yes || Settings.xflip==disk3d) + newspeed = SHIFT_SPEED; + else + newspeed = -SHIFT_SPEED; + } + else if(btnRight->GetState() == STATE_CLICKED) + { + WPAD_ScanPads(); + u16 buttons = 0; + for(int i=0; i<4; i++) + buttons |= WPAD_ButtonsHeld(i); + if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_PLUS) || t->Right())) + { + btnRight->ResetState(); + return; + } + if (Settings.xflip==sysmenu ||Settings.xflip==yes || Settings.xflip==disk3d) + newspeed = -SHIFT_SPEED; + else + newspeed = SHIFT_SPEED; + } + if(newspeed) + { + if(speed==0) + speed = newspeed; + else if(speed>0) + { + if((speed+=SPEED_STEP) > SPEED_LIMIT) + speed = SPEED_LIMIT; + } + else + { + if((speed-=SPEED_STEP) < -SPEED_LIMIT) + speed = -SPEED_LIMIT; + } + } + else + speed = 0; - if (speed > 0) { // rotate right - GuiButton *tmpButton; - listOffset = OFFSETLIMIT(listOffset - 1, gameCnt); // set the new listOffset - // Save right Button + TollTip and destroy right Image + Image-Data - delete coverImg[pagesize-1]; - coverImg[pagesize-1] = NULL; - game[pagesize-1]->SetImage(NULL); - tmpButton = game[pagesize-1]; + if(speed > 0) // rotate right + { + GuiButton *tmpButton; + listOffset = OFFSETLIMIT(listOffset - 1, gameCnt); // set the new listOffset + // Save right Button + TollTip and destroy right Image + Image-Data + delete coverImg[pagesize-1]; coverImg[pagesize-1] = NULL;game[pagesize-1]->SetImage(NULL); + tmpButton = game[pagesize-1]; + + // Move all Page-Entries one step right + for (int i=pagesize-1; i>=1; i--) + { + coverImg[i] = coverImg[i-1]; + game[i] = game[i-1]; + gameIndex[i] = gameIndex[i-1]; + } + // set saved Button & gameIndex to right + gameIndex[0] = listOffset; + coverImg[0] = new GuiImageAsync(GameCarouselLoadCoverImage, &gameList[gameIndex[0]], sizeof(struct discHdr), &noCover); + coverImg[0] ->SetWidescreen(CFG.widescreen); - // Move all Page-Entries one step right - for (int i=pagesize-1; i>=1; i--) { - coverImg[i] = coverImg[i-1]; - game[i] = game[i-1]; - gameIndex[i] = gameIndex[i-1]; - } - // set saved Button & gameIndex to right - gameIndex[0] = listOffset; - coverImg[0] = new GuiImageAsync(GameCarouselLoadCoverImage, &gameList[gameIndex[0]], sizeof(struct discHdr), &noCover); - coverImg[0] ->SetWidescreen(CFG.widescreen); + game[0] = tmpButton; + game[0] ->SetImage(coverImg[0]); - game[0] = tmpButton; - game[0] ->SetImage(coverImg[0]); + + for(int i=0; iStopEffect(); + game[i]->ResetState(); + game[i]->SetEffect(EFFECT_GOROUND, speed, DEG_OFFSET, RADIUS, 270-(pagesize-2*i+1)*DEG_OFFSET/2, 1, 0, RADIUS); + game[i]->UpdateEffects(); // rotate one step for liquid scrolling + } + } + else if(speed < 0) // rotate left + { + GuiButton *tmpButton; + listOffset = OFFSETLIMIT(listOffset + 1, gameCnt); // set the new listOffset + // Save left Button + TollTip and destroy left Image + Image-Data + delete coverImg[0]; coverImg[0] = NULL;game[0]->SetImage(NULL); + tmpButton = game[0]; + + // Move all Page-Entries one step left + for (int i=0; i<(pagesize-1); i++) + { + coverImg[i] = coverImg[i+1]; + game[i] = game[i+1]; + gameIndex[i] = gameIndex[i+1]; + } + // set saved Button & gameIndex to right + int ii = pagesize-1; + gameIndex[ii] = OFFSETLIMIT(listOffset + ii, gameCnt); + coverImg[ii] = new GuiImageAsync(GameCarouselLoadCoverImage, &gameList[gameIndex[ii]], sizeof(struct discHdr), &noCover); + coverImg[ii] ->SetWidescreen(CFG.widescreen); + game[ii] = tmpButton; + game[ii] ->SetImage(coverImg[ii]); - for (int i=0; iStopEffect(); - game[i]->ResetState(); - game[i]->SetEffect(EFFECT_GOROUND, speed, DEG_OFFSET, RADIUS, 270-(pagesize-2*i+1)*DEG_OFFSET/2, 1, 0, RADIUS); - game[i]->UpdateEffects(); // rotate one step for liquid scrolling - } - } else if (speed < 0) { // rotate left - GuiButton *tmpButton; - listOffset = OFFSETLIMIT(listOffset + 1, gameCnt); // set the new listOffset - // Save left Button + TollTip and destroy left Image + Image-Data - delete coverImg[0]; - coverImg[0] = NULL; - game[0]->SetImage(NULL); - tmpButton = game[0]; + + for(int i=0; iStopEffect(); + game[i]->ResetState(); + game[i]->SetEffect(EFFECT_GOROUND, speed, DEG_OFFSET, RADIUS, 270-(pagesize-2*i-3)*DEG_OFFSET/2, 1, 0, RADIUS); + game[i]->UpdateEffects(); // rotate one step for liquid scrolling + } + } - // Move all Page-Entries one step left - for (int i=0; i<(pagesize-1); i++) { - coverImg[i] = coverImg[i+1]; - game[i] = game[i+1]; - gameIndex[i] = gameIndex[i+1]; - } - // set saved Button & gameIndex to right - int ii = pagesize-1; - gameIndex[ii] = OFFSETLIMIT(listOffset + ii, gameCnt); - coverImg[ii] = new GuiImageAsync(GameCarouselLoadCoverImage, &gameList[gameIndex[ii]], sizeof(struct discHdr), &noCover); - coverImg[ii] ->SetWidescreen(CFG.widescreen); - - game[ii] = tmpButton; - game[ii] ->SetImage(coverImg[ii]); - - - for (int i=0; iStopEffect(); - game[i]->ResetState(); - game[i]->SetEffect(EFFECT_GOROUND, speed, DEG_OFFSET, RADIUS, 270-(pagesize-2*i-3)*DEG_OFFSET/2, 1, 0, RADIUS); - game[i]->UpdateEffects(); // rotate one step for liquid scrolling - } - } - - } - if (updateCB) - updateCB(this); + } + if(updateCB) + updateCB(this); } diff --git a/source/libwiigui/gui_gamecarousel.h b/source/libwiigui/gui_gamecarousel.h index 727a73b5..e4906893 100644 --- a/source/libwiigui/gui_gamecarousel.h +++ b/source/libwiigui/gui_gamecarousel.h @@ -4,53 +4,54 @@ #include "gui.h" #include "../usbloader/disc.h" class GuiImageAsync; -class GuiGameCarousel : public GuiElement { -public: - GuiGameCarousel(int w, int h, struct discHdr * l, int gameCnt, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); - ~GuiGameCarousel(); - int FindMenuItem(int c, int d); - int GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); - int GetOffset(); - void Reload(struct discHdr * l, int count); - //GuiText * optionVal[PAGESIZE]; -protected: - GuiImageData noCover; - int selectedItem; - int listOffset; - int scrollbaron; - int pagesize; - int speed; - int clickedItem; +class GuiGameCarousel : public GuiElement +{ + public: + GuiGameCarousel(int w, int h, struct discHdr * l, int gameCnt, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); + ~GuiGameCarousel(); + int FindMenuItem(int c, int d); + int GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus(int f); + void Draw(); + void Update(GuiTrigger * t); + int GetOffset(); + void Reload(struct discHdr * l, int count); + //GuiText * optionVal[PAGESIZE]; + protected: + GuiImageData noCover; + int selectedItem; + int listOffset; + int scrollbaron; + int pagesize; + int speed; + int clickedItem; - struct discHdr * gameList; - int gameCnt; + struct discHdr * gameList; + int gameCnt; - int * gameIndex; - GuiButton ** game; - GuiImageAsync ** coverImg; + int * gameIndex; + GuiButton ** game; + GuiImageAsync ** coverImg; - GuiText * gamename; + GuiText * gamename; - GuiButton * btnRight; - GuiButton * btnLeft; + GuiButton * btnRight; + GuiButton * btnLeft; - GuiImage * btnLeftImg; - GuiImage * btnRightImg; + GuiImage * btnLeftImg; + GuiImage * btnRightImg; - GuiImageData * imgLeft; - GuiImageData * imgRight; + GuiImageData * imgLeft; + GuiImageData * imgRight; - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigL; - GuiTrigger * trigR; - GuiTrigger * trigPlus; - GuiTrigger * trigMinus; + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigL; + GuiTrigger * trigR; + GuiTrigger * trigPlus; + GuiTrigger * trigMinus; }; #endif diff --git a/source/libwiigui/gui_gamegrid.cpp b/source/libwiigui/gui_gamegrid.cpp index d1f2e638..30acbcd2 100644 --- a/source/libwiigui/gui_gamegrid.cpp +++ b/source/libwiigui/gui_gamegrid.cpp @@ -38,484 +38,509 @@ extern const int vol; static int Skew1[7][8] = { - {-14,-66,14,-34,14,34,-14,66}, - {-10,-44,10,-26,10,26,-10,44}, - {-6,-22,6,-14,6,14,-6,22}, - {0,-11,0,-11,0,11,0,11}, - {-6,-14,6,-22,6,22,-6,14}, - {-10,-26,10,-44,10,44,-10,26}, - {-14,-34,14,-66,14,66,-14,34} -}; + {-14,-66,14,-34,14,34,-14,66}, + {-10,-44,10,-26,10,26,-10,44}, + {-6,-22,6,-14,6,14,-6,22}, + {0,-11,0,-11,0,11,0,11}, + {-6,-14,6,-22,6,22,-6,14}, + {-10,-26,10,-44,10,44,-10,26}, + {-14,-34,14,-66,14,66,-14,34} + }; static int Pos1[7][2][2] = { - // {{16:9 x,y},{ 4:3 x,y}} - {{-230,74}, {-320,74}}, - {{-70,74}, {-130,74}}, - {{88,74}, {60,74}}, - {{239,74}, {239,74}}, - {{390,74}, {420,74}}, - {{550,74}, {612,74}}, - {{710,74}, {772,74}} -}; + // {{16:9 x,y},{ 4:3 x,y}} + {{-230,74}, {-320,74}}, + {{-70,74}, {-130,74}}, + {{88,74}, {60,74}}, + {{239,74}, {239,74}}, + {{390,74}, {420,74}}, + {{550,74}, {612,74}}, + {{710,74}, {772,74}} + }; static int Skew2[18][8] = { - {-5,-49,5,-27,5,0,-5,0}, - {-5,0,5,0,5,27,-5,49}, - - {-5,-49,5,-27,5,0,-5,0}, - {-5,0,5,0,5,27,-5,49}, - - {-4,-22,4,-14,4,0,-4,0}, - {-4,0,4,0,4,14,-4,22}, - - {0,-9,0,-5,0,0,0,0}, - {0,0,0,0,0,5,0,9}, - - {0,0,0,0,0,0,0,0}, - {0,0,0,0,0,0,0,0}, - - {0,-5,0,-9,0,0,0,0}, - {0,0,0,0,0,9,0,5}, - - {-4,-14,4,-22,4,0,-4,0}, - {-4,0,4,0,4,22,-4,14}, - - {-5,-27,5,-49,5,0,-5,0}, - {-5,0,5,0,5,49,-5,27}, - - {-5,-27,5,-49,5,0,-5,0}, - {-5,0,5,0,5,49,-5,27} -}; + {-5,-49,5,-27,5,0,-5,0}, + {-5,0,5,0,5,27,-5,49}, + + {-5,-49,5,-27,5,0,-5,0}, + {-5,0,5,0,5,27,-5,49}, + + {-4,-22,4,-14,4,0,-4,0}, + {-4,0,4,0,4,14,-4,22}, + + {0,-9,0,-5,0,0,0,0}, + {0,0,0,0,0,5,0,9}, + + {0,0,0,0,0,0,0,0}, + {0,0,0,0,0,0,0,0}, + + {0,-5,0,-9,0,0,0,0}, + {0,0,0,0,0,9,0,5}, + + {-4,-14,4,-22,4,0,-4,0}, + {-4,0,4,0,4,22,-4,14}, + + {-5,-27,5,-49,5,0,-5,0}, + {-5,0,5,0,5,49,-5,27}, + + {-5,-27,5,-49,5,0,-5,0}, + {-5,0,5,0,5,49,-5,27} + }; static int Pos2[18][2][2] = { - // {{16:9 x,y},{ 4:3 x,y}} - {{-91,50}, {-166,50}}, - {{-91,193},{-166,193}}, - - {{3,50}, {-54,50}}, - {{3,193}, {-54,193}}, - - {{97,50}, {58,50}}, - {{97,193}, {58,193}}, - - {{187,50}, {166,50}}, - {{187,193}, {166,193}}, - - {{272,50}, {272,50}}, - {{272,193}, {272,193}}, - - {{358,50}, {378,50}}, - {{358,193}, {378,193}}, - - {{449,50}, {487,50}}, - {{449,193}, {487,193}}, - - {{545,50}, {599,50}}, - {{545,193}, {599,193}}, - - {{641,50}, {700,50}}, - {{641,193}, {700,193}} -}; + // {{16:9 x,y},{ 4:3 x,y}} + {{-91,50}, {-166,50}}, + {{-91,193},{-166,193}}, + + {{3,50}, {-54,50}}, + {{3,193}, {-54,193}}, + + {{97,50}, {58,50}}, + {{97,193}, {58,193}}, + + {{187,50}, {166,50}}, + {{187,193}, {166,193}}, + + {{272,50}, {272,50}}, + {{272,193}, {272,193}}, + + {{358,50}, {378,50}}, + {{358,193}, {378,193}}, + + {{449,50}, {487,50}}, + {{449,193}, {487,193}}, + + {{545,50}, {599,50}}, + {{545,193}, {599,193}}, + + {{641,50}, {700,50}}, + {{641,193}, {700,193}} + }; static int Skew3[45][8] = { - {-38,-110,15,-42,15,65,-38,32}, - {-38,-75,15,-48,15,45,-38,72}, - {-38,-52,15,-70,15,27,-38,100}, + {-38,-110,15,-42,15,65,-38,32}, + {-38,-75,15,-48,15,45,-38,72}, + {-38,-52,15,-70,15,27,-38,100}, - {-38,-110,15,-42,15,65,-38,32}, - {-38,-75,15,-48,15,45,-38,72}, - {-38,-52,15,-70,15,27,-38,100}, + {-38,-110,15,-42,15,65,-38,32}, + {-38,-75,15,-48,15,45,-38,72}, + {-38,-52,15,-70,15,27,-38,100}, - {-38,-70,15,-24,15,40,-38,27}, - {-38,-50,15,-35,15,40,-38,50}, - {-38,-34,15,-47,15,24,-38,58}, + {-38,-70,15,-24,15,40,-38,27}, + {-38,-50,15,-35,15,40,-38,50}, + {-38,-34,15,-47,15,24,-38,58}, - {-27,-55,19,-22,19,30,-27,22}, - {-27,-40,19,-30,19,30,-27,40}, - {-27,-20,19,-30,19,20,-27,50}, + {-27,-55,19,-22,19,30,-27,22}, + {-27,-40,19,-30,19,30,-27,40}, + {-27,-20,19,-30,19,20,-27,50}, - {-19,-28,0,-17,0,15,-19,10}, - {-19,-30,0,-20,0,12,-19,30}, - {-19,-15,0,-20,0,10,-19,24}, + {-19,-28,0,-17,0,15,-19,10}, + {-19,-30,0,-20,0,12,-19,30}, + {-19,-15,0,-20,0,10,-19,24}, - {-10,-20,3,-13,3,14,-10,10}, - {-10,-20,3,-18,3,18,-10,20}, - {-10,-10,3,-10,3,0,-10,10}, + {-10,-20,3,-13,3,14,-10,10}, + {-10,-20,3,-18,3,18,-10,20}, + {-10,-10,3,-10,3,0,-10,10}, - {-10,-15,3,-12,3,13,-10,13}, - {-10,-17,3,-10,3,10,-10,17}, - {-10,-10,3,-15,3,10,-10,10}, + {-10,-15,3,-12,3,13,-10,13}, + {-10,-17,3,-10,3,10,-10,17}, + {-10,-10,3,-15,3,10,-10,10}, - {-10,-10,3,-10,3,14,-10,14}, - {-10,-10,3,-10,3,10,-10,10},//middle - {-10,-10,3,-10,3,10,-10,10}, + {-10,-10,3,-10,3,14,-10,14}, + {-10,-10,3,-10,3,10,-10,10},//middle + {-10,-10,3,-10,3,10,-10,10}, - {-14,-10,4,-20,3,10,-14,10}, - {-14,-10,4,-17,3,17,-14,10}, - {-14,-10,4,-10,3,10,-14,10}, + {-14,-10,4,-20,3,10,-14,10}, + {-14,-10,4,-17,3,17,-14,10}, + {-14,-10,4,-10,3,10,-14,10}, - {-10,-13,3,-20,3,14,-10,10}, - {-10,-18,3,-20,3,20,-10,18}, - {-10,-10,3,-10,3,20,-10,5}, + {-10,-13,3,-20,3,14,-10,10}, + {-10,-18,3,-20,3,20,-10,18}, + {-10,-10,3,-10,3,20,-10,5}, - {-19,-17,0,-28,0,10,-19,15}, - {-19,-20,0,-30,0,30,-19,12}, - {-19,-20,0,-15,0,30,-19,10}, + {-19,-17,0,-28,0,10,-19,15}, + {-19,-20,0,-30,0,30,-19,12}, + {-19,-20,0,-15,0,30,-19,10}, - {-27,-22,19,-55,19,22,-27,30}, - {-27,-30,19,-40,19,40,-27,30}, - {-27,-30,19,-20,19,55,-27,20}, + {-27,-22,19,-55,19,22,-27,30}, + {-27,-30,19,-40,19,40,-27,30}, + {-27,-30,19,-20,19,55,-27,20}, - {-38,-24,15,-70,15,27,-38,40}, - {-38,-35,15,-50,15,50,-38,40}, - {-38,-47,15,-34,15,58,-38,24}, + {-38,-24,15,-70,15,27,-38,40}, + {-38,-35,15,-50,15,50,-38,40}, + {-38,-47,15,-34,15,58,-38,24}, - {-38,-42,15,-110,15,32,-38,60}, - {-38,-48,15,-75,15,70,-38,45}, - {-38,-70,15,-52,15,100,-38,27}, + {-38,-42,15,-110,15,32,-38,60}, + {-38,-48,15,-75,15,70,-38,45}, + {-38,-70,15,-52,15,100,-38,27}, - {-38,-42,15,-110,15,32,-38,60}, - {-38,-48,15,-75,15,70,-38,45}, - {-38,-70,15,-52,15,100,-38,27} -}; + {-38,-42,15,-110,15,32,-38,60}, + {-38,-48,15,-75,15,70,-38,45}, + {-38,-70,15,-52,15,100,-38,27} + }; static int Pos3[45][2][2] = { - // {{16:9 x,y},{ 4:3 x,y}} - {{-42,49}, {-91,49}}, - {{-42,153},{-91,153}}, - {{-42,261},{-91,261}}, - - {{13,58}, {-29,58}}, - {{13,153}, {-29,153}}, - {{13,250}, {-29,250}}, - - {{68,67}, {33,67}}, - {{68,153}, {33,153}}, - {{68,239}, {33,239}}, - - {{120,74}, {92,74}}, - {{120,153}, {92,153}}, - {{120,232}, {92,232}}, - - {{170,78}, {149,78}}, - {{170,153}, {149,153}}, - {{170,228}, {149,228}}, - - {{214,80}, {200,80}}, - {{214,153}, {200,153}}, - {{214,226}, {200,226}}, - - {{258,81}, {251,81}}, - {{258,153}, {251,153}}, - {{258,224}, {251,224}}, - - {{302,81}, {302,81}}, - {{302,153}, {302,153}}, - {{302,223}, {302,223}}, - - {{346,81}, {353,81}}, - {{346,153}, {353,153}}, - {{346,223}, {353,223}}, - - {{390,80}, {404,80}}, - {{390,153}, {404,153}}, - {{390,225}, {404,225}}, - - {{434,77}, {457,77}}, - {{434,153}, {457,153}}, - {{434,227}, {457,227}}, - - {{484,73}, {512,73}}, - {{484,153}, {512,153}}, - {{484,231}, {512,231}}, - - {{537,67}, {572,67}}, - {{537,153}, {572,153}}, - {{537,239}, {572,239}}, - - {{591,58}, {633,58}}, - {{591,153}, {633,153}}, - {{591,250}, {633,250}}, - - {{645,58}, {633,58}}, - {{645,153}, {633,153}}, - {{645,250}, {633,250}} - -}; + // {{16:9 x,y},{ 4:3 x,y}} + {{-42,49}, {-91,49}}, + {{-42,153},{-91,153}}, + {{-42,261},{-91,261}}, + + {{13,58}, {-29,58}}, + {{13,153}, {-29,153}}, + {{13,250}, {-29,250}}, + + {{68,67}, {33,67}}, + {{68,153}, {33,153}}, + {{68,239}, {33,239}}, + + {{120,74}, {92,74}}, + {{120,153}, {92,153}}, + {{120,232}, {92,232}}, + + {{170,78}, {149,78}}, + {{170,153}, {149,153}}, + {{170,228}, {149,228}}, + + {{214,80}, {200,80}}, + {{214,153}, {200,153}}, + {{214,226}, {200,226}}, + + {{258,81}, {251,81}}, + {{258,153}, {251,153}}, + {{258,224}, {251,224}}, + + {{302,81}, {302,81}}, + {{302,153}, {302,153}}, + {{302,223}, {302,223}}, + + {{346,81}, {353,81}}, + {{346,153}, {353,153}}, + {{346,223}, {353,223}}, + + {{390,80}, {404,80}}, + {{390,153}, {404,153}}, + {{390,225}, {404,225}}, + + {{434,77}, {457,77}}, + {{434,153}, {457,153}}, + {{434,227}, {457,227}}, + + {{484,73}, {512,73}}, + {{484,153}, {512,153}}, + {{484,231}, {512,231}}, + + {{537,67}, {572,67}}, + {{537,153}, {572,153}}, + {{537,239}, {572,239}}, + + {{591,58}, {633,58}}, + {{591,153}, {633,153}}, + {{591,250}, {633,250}}, + + {{645,58}, {633,58}}, + {{645,153}, {633,153}}, + {{645,250}, {633,250}} + + }; #define VALUE4ROWS(rows, val1, val2, val3) (rows==3 ? val3 : (rows==2 ? val2 : val1)) #define ROWS2PAGESIZE(rows) (rows==3 ? 45 : (rows==2 ? 18 : 7)) -static inline int OFFSETLIMIT(int Offset, int rows, int gameCnt) { - gameCnt += ( rows - ( gameCnt % rows ) ) % rows; // add count of skiped Entries at end if List - while (Offset > gameCnt) Offset -= gameCnt; - while (Offset < 0) Offset += gameCnt; - return Offset; -} +static inline int OFFSETLIMIT(int Offset, int rows, int gameCnt) +{ + gameCnt += ( rows - ( gameCnt % rows ) ) % rows; // add count of skiped Entries at end if List + while(Offset > gameCnt) Offset -= gameCnt; + while(Offset < 0) Offset += gameCnt; + return Offset; +} // Help-Function to Calc GameIndex -static int GetGameIndex(int pageEntry, int rows, int listOffset, int gameCnt) { - int skip = ( rows - ( gameCnt % rows ) ) % rows; // count of skiped Entries at end if List - int pagesize = ROWS2PAGESIZE(rows); +static int GetGameIndex(int pageEntry, int rows, int listOffset, int gameCnt) +{ + int skip = ( rows - ( gameCnt % rows ) ) % rows; // count of skiped Entries at end if List + int pagesize = ROWS2PAGESIZE(rows); - if ( gameCnt < (pagesize-2*rows) ) { - int listStart = (pagesize-gameCnt)>>1; // align list on the center - listStart = listStart - (listStart%rows); // align listStart to the top row - if (pageEntry < listStart || pageEntry >= listStart + gameCnt) - return -1; - return pageEntry - listStart; - } else { - listOffset = listOffset - (listOffset%rows); // align listOffset to the top row - listOffset = listOffset - 2*rows; // align listOffset to the left full visible column - if (listOffset < 0) - listOffset += gameCnt + skip; // set the correct Offset - pageEntry = (listOffset + pageEntry) % (gameCnt + skip); // get offset of pageEntry - if (pageEntry >= gameCnt) - return -1; - return pageEntry; - } + if( gameCnt < (pagesize-2*rows) ) + { + int listStart = (pagesize-gameCnt)>>1; // align list on the center + listStart = listStart - (listStart%rows); // align listStart to the top row + if(pageEntry < listStart || pageEntry >= listStart + gameCnt) + return -1; + return pageEntry - listStart; + } + else + { + listOffset = listOffset - (listOffset%rows); // align listOffset to the top row + listOffset = listOffset - 2*rows; // align listOffset to the left full visible column + if(listOffset < 0) + listOffset += gameCnt + skip; // set the correct Offset + pageEntry = (listOffset + pageEntry) % (gameCnt + skip); // get offset of pageEntry + if(pageEntry >= gameCnt) + return -1; + return pageEntry; + } } -static GuiImageData *GameGridLoadCoverImage(void * Arg) { - return LoadCoverImage((struct discHdr *)Arg, false, false); +static GuiImageData *GameGridLoadCoverImage(void * Arg) +{ + return LoadCoverImage((struct discHdr *)Arg, false, false); } /** * Constructor for the GuiGamegrid class. */ GuiGameGrid::GuiGameGrid(int w, int h, struct discHdr * l, int count, const char *themePath, const u8 *imagebg, int selected, int offset) : - noCover(nocoverFlat_png) { - width = w; - height = h; +noCover(nocoverFlat_png) +{ + width = w; + height = h; // gameCnt = count; will be set later in Reload // gameList = l; will be set later in Reload // listOffset = 0; will be set later in Reload // goLeft = 0; will be set later in Reload // goRight = 0; will be set later in Reload - selectable = true; - focus = 1; // allow focus + selectable = true; + focus = 1; // allow focus // selectedItem = -1; will be set later in Reload // clickedItem = -1; will be set later in Reload - /* will be set later in Reload - rows = Settings.gridRows; - if ((count<45)&&(rows==3))rows=2; - if ((count<18)&&(rows==2))rows=1; +/* will be set later in Reload + rows = Settings.gridRows; + if ((count<45)&&(rows==3))rows=2; + if ((count<18)&&(rows==2))rows=1; - pagesize = ROWS2PAGESIZE(rows); - */ - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigL = new GuiTrigger; - trigL->SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); - trigR = new GuiTrigger; - trigR->SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); - trig1 = new GuiTrigger; - trig1->SetButtonOnlyTrigger(-1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_X, PAD_BUTTON_X); - trig2 = new GuiTrigger; - trig2->SetButtonOnlyTrigger(-1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_Y, PAD_BUTTON_Y); - trigPlus = new GuiTrigger; - trigPlus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - trigMinus = new GuiTrigger; - trigMinus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); + pagesize = ROWS2PAGESIZE(rows); +*/ + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigL = new GuiTrigger; + trigL->SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); + trigR = new GuiTrigger; + trigR->SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); + trig1 = new GuiTrigger; + trig1->SetButtonOnlyTrigger(-1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_X, PAD_BUTTON_X); + trig2 = new GuiTrigger; + trig2->SetButtonOnlyTrigger(-1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_Y, PAD_BUTTON_Y); + trigPlus = new GuiTrigger; + trigPlus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); + trigMinus = new GuiTrigger; + trigMinus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); - btnSoundClick = new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + btnSoundClick = new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - int btnHeight = (int) lround(sqrt(RADIUS*RADIUS - 90000)-RADIUS-50); + int btnHeight = (int) lround(sqrt(RADIUS*RADIUS - 90000)-RADIUS-50); - // Button Left - btnLeft = new GuiButton(0,0); - btnLeft->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - btnLeft->SetPosition(20, btnHeight); - btnLeft->SetParent(this); - btnLeft->SetSoundOver(btnSoundOver); - btnLeft->SetTrigger(trigL); - btnLeft->SetTrigger(trigMinus); + // Button Left + btnLeft = new GuiButton(0,0); + btnLeft->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + btnLeft->SetPosition(20, btnHeight); + btnLeft->SetParent(this); + btnLeft->SetSoundOver(btnSoundOver); + btnLeft->SetTrigger(trigL); + btnLeft->SetTrigger(trigMinus); - // Button Right - btnRight = new GuiButton(0,0); - btnRight->SetParent(this); - btnRight->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); - btnRight->SetPosition(-20, btnHeight); - btnRight->SetSoundOver(btnSoundOver); - btnRight->SetTrigger(trigR); - btnRight->SetTrigger(trigPlus); + // Button Right + btnRight = new GuiButton(0,0); + btnRight->SetParent(this); + btnRight->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); + btnRight->SetPosition(-20, btnHeight); + btnRight->SetSoundOver(btnSoundOver); + btnRight->SetTrigger(trigR); + btnRight->SetTrigger(trigPlus); - // Button RowUp - btnRowUp = new GuiButton(0,0); - btnRowUp->SetParent(this); - btnRowUp->SetAlignment(ALIGN_LEFT, ALIGN_TOP); - btnRowUp->SetPosition(0,0); - btnRowUp->SetTrigger(trig2); + // Button RowUp + btnRowUp = new GuiButton(0,0); + btnRowUp->SetParent(this); + btnRowUp->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + btnRowUp->SetPosition(0,0); + btnRowUp->SetTrigger(trig2); - // Button RowDown - btnRowDown = new GuiButton(0,0); - btnRowDown->SetParent(this); - btnRowDown->SetAlignment(ALIGN_LEFT, ALIGN_TOP); - btnRowDown->SetPosition(0,0); - btnRowDown->SetTrigger(trig1); + // Button RowDown + btnRowDown = new GuiButton(0,0); + btnRowDown->SetParent(this); + btnRowDown->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + btnRowDown->SetPosition(0,0); + btnRowDown->SetTrigger(trig1); - // Page-Stuff - gameIndex = NULL; - titleTT = NULL; + // Page-Stuff + gameIndex = NULL; + titleTT = NULL; // cover = NULL; - coverImg = NULL; - game = NULL; + coverImg = NULL; + game = NULL; - Reload(l, count, Settings.gridRows, 0); + Reload(l, count, Settings.gridRows, 0); } /** * Destructor for the GuiGameGrid class. */ -GuiGameGrid::~GuiGameGrid() { +GuiGameGrid::~GuiGameGrid() +{ - delete btnRight; - delete btnLeft; - delete btnRowUp; - delete btnRowDown; + delete btnRight; + delete btnLeft; + delete btnRowUp; + delete btnRowDown; - delete trigA; - delete trigL; - delete trigR; - delete trigPlus; - delete trigMinus; - delete trig1; - delete trig2; - delete btnSoundClick; - delete btnSoundOver; + delete trigA; + delete trigL; + delete trigR; + delete trigPlus; + delete trigMinus; + delete trig1; + delete trig2; + delete btnSoundClick; + delete btnSoundOver; - for (int i=pagesize-1; i>=0; i--) { - delete game[i]; - delete coverImg[i]; - delete titleTT[i]; - } + for(int i=pagesize-1; i>=0; i--) + { + delete game[i]; + delete coverImg[i]; + delete titleTT[i]; + } - delete [] gameIndex; - delete [] game; - delete [] coverImg; - delete [] titleTT; + delete [] gameIndex; + delete [] game; + delete [] coverImg; + delete [] titleTT; } -void GuiGameGrid::SetFocus(int f) { - LOCK(this); - if (!gameCnt) - return; +void GuiGameGrid::SetFocus(int f) +{ + LOCK(this); + if(!gameCnt) + return; - focus = f; + focus = f; - for (int i=0; iResetState(); + for(int i=0; iResetState(); - if (f == 1 && selectedItem >= 0) - game[selectedItem]->SetState(STATE_SELECTED); + if(f == 1 && selectedItem >= 0) + game[selectedItem]->SetState(STATE_SELECTED); } -void GuiGameGrid::ResetState() { - LOCK(this); - if (state != STATE_DISABLED) { - state = STATE_DEFAULT; - stateChan = -1; - } +void GuiGameGrid::ResetState() +{ + LOCK(this); + if(state != STATE_DISABLED) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for (int i=0; iResetState(); - } + for(int i=0; iResetState(); + } } -int GuiGameGrid::GetOffset() { - LOCK(this); - return listOffset; +int GuiGameGrid::GetOffset() +{ + LOCK(this); + return listOffset; } -int GuiGameGrid::GetClickedOption() { - LOCK(this); - int found = -1; - if (clickedItem>=0) { - game[clickedItem]->SetState(STATE_SELECTED); - found = gameIndex[clickedItem]; - clickedItem=-1; - } - return found; +int GuiGameGrid::GetClickedOption() +{ + LOCK(this); + int found = -1; + if (clickedItem>=0) + { + game[clickedItem]->SetState(STATE_SELECTED); + found = gameIndex[clickedItem]; + clickedItem=-1; + } + return found; } -int GuiGameGrid::GetSelectedOption() { - LOCK(this); - int found = -1; - for (int i=0; iGetState() == STATE_SELECTED) { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; +int GuiGameGrid::GetSelectedOption() +{ + LOCK(this); + int found = -1; + for(int i=0; iGetState() == STATE_SELECTED) + { + game[i]->SetState(STATE_SELECTED); + found = gameIndex[i]; + break; + } + } + return found; } /** * Draw the button on screen */ -void GuiGameGrid::Draw() { - LOCK(this); - if (!this->IsVisible() || !gameCnt) - return; +void GuiGameGrid::Draw() +{ + LOCK(this); + if(!this->IsVisible() || !gameCnt) + return; - if (goLeft>0) { - goLeft--; - int wsi = CFG.widescreen ? 0:1; - float f2 = ((float)goLeft)/goSteps; - float f1 = 1.0-f2; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + if(goLeft>0) + { + goLeft--; + int wsi = CFG.widescreen ? 0:1; + float f2 = ((float)goLeft)/goSteps; + float f1 = 1.0-f2; + int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); + int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); - for (int i=0; iSetPosition( Pos[i][wsi][0]*f1 + Pos[i+rows][wsi][0]*f2+THEME.gamegrid_x, - Pos[i][wsi][1]*f1 + Pos[i+rows][wsi][1]*f2+THEME.gamegrid_y); + for(int i=0; iSetPosition( Pos[i][wsi][0]*f1 + Pos[i+rows][wsi][0]*f2+THEME.gamegrid_x, + Pos[i][wsi][1]*f1 + Pos[i+rows][wsi][1]*f2+THEME.gamegrid_y); + + game[i]->SetSkew( Skew[i][0]*f1 + Skew[i+rows][0]*f2, + Skew[i][1]*f1 + Skew[i+rows][1]*f2, + Skew[i][2]*f1 + Skew[i+rows][2]*f2, + Skew[i][3]*f1 + Skew[i+rows][3]*f2, + Skew[i][4]*f1 + Skew[i+rows][4]*f2, + Skew[i][5]*f1 + Skew[i+rows][5]*f2, + Skew[i][6]*f1 + Skew[i+rows][6]*f2, + Skew[i][7]*f1 + Skew[i+rows][7]*f2); + } + } + else if(goRight>0) + { + goRight--; + int wsi = CFG.widescreen ? 0:1; + float f2 = ((float)goRight)/goSteps; + float f1 = 1.0-f2; + int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); + int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + for(int i=rows; iSetPosition( Pos[i][wsi][0]*f1 + Pos[i-rows][wsi][0]*f2+THEME.gamegrid_x, + Pos[i][wsi][1]*f1 + Pos[i-rows][wsi][1]*f2+THEME.gamegrid_y); + + game[i]->SetSkew( Skew[i][0]*f1 + Skew[i-rows][0]*f2, + Skew[i][1]*f1 + Skew[i-rows][1]*f2, + Skew[i][2]*f1 + Skew[i-rows][2]*f2, + Skew[i][3]*f1 + Skew[i-rows][3]*f2, + Skew[i][4]*f1 + Skew[i-rows][4]*f2, + Skew[i][5]*f1 + Skew[i-rows][5]*f2, + Skew[i][6]*f1 + Skew[i-rows][6]*f2, + Skew[i][7]*f1 + Skew[i-rows][7]*f2); + } + } - game[i]->SetSkew( Skew[i][0]*f1 + Skew[i+rows][0]*f2, - Skew[i][1]*f1 + Skew[i+rows][1]*f2, - Skew[i][2]*f1 + Skew[i+rows][2]*f2, - Skew[i][3]*f1 + Skew[i+rows][3]*f2, - Skew[i][4]*f1 + Skew[i+rows][4]*f2, - Skew[i][5]*f1 + Skew[i+rows][5]*f2, - Skew[i][6]*f1 + Skew[i+rows][6]*f2, - Skew[i][7]*f1 + Skew[i+rows][7]*f2); - } - } else if (goRight>0) { - goRight--; - int wsi = CFG.widescreen ? 0:1; - float f2 = ((float)goRight)/goSteps; - float f1 = 1.0-f2; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); - for (int i=rows; iSetPosition( Pos[i][wsi][0]*f1 + Pos[i-rows][wsi][0]*f2+THEME.gamegrid_x, - Pos[i][wsi][1]*f1 + Pos[i-rows][wsi][1]*f2+THEME.gamegrid_y); + for(int i=0; iDraw(); + if(gameCnt > pagesize-2*rows) + { + btnRight->Draw(); + btnLeft->Draw(); + } - game[i]->SetSkew( Skew[i][0]*f1 + Skew[i-rows][0]*f2, - Skew[i][1]*f1 + Skew[i-rows][1]*f2, - Skew[i][2]*f1 + Skew[i-rows][2]*f2, - Skew[i][3]*f1 + Skew[i-rows][3]*f2, - Skew[i][4]*f1 + Skew[i-rows][4]*f2, - Skew[i][5]*f1 + Skew[i-rows][5]*f2, - Skew[i][6]*f1 + Skew[i-rows][6]*f2, - Skew[i][7]*f1 + Skew[i-rows][7]*f2); - } - } + btnRowUp->Draw(); + btnRowDown->Draw(); - for (int i=0; iDraw(); - if (gameCnt > pagesize-2*rows) { - btnRight->Draw(); - btnLeft->Draw(); - } + if (focus && Settings.tooltips == TooltipsOn) + for(int i=0; iDrawTooltip(); - btnRowUp->Draw(); - btnRowDown->Draw(); - - if (focus && Settings.tooltips == TooltipsOn) - for (int i=0; iDrawTooltip(); - - this->UpdateEffects(); + this->UpdateEffects(); } @@ -523,373 +548,418 @@ void GuiGameGrid::Draw() { /** * Change the number of rows */ -void GuiGameGrid::ChangeRows(int n) { - LOCK(this); - if (n != rows) - Reload(gameList, gameCnt, n, -1); +void GuiGameGrid::ChangeRows(int n) +{ + LOCK(this); + if(n != rows) + Reload(gameList, gameCnt, n, -1); } -void GuiGameGrid::Update(GuiTrigger * t) { - LOCK(this); - if (state == STATE_DISABLED || !t || !gameCnt) - return; +void GuiGameGrid::Update(GuiTrigger * t) +{ + LOCK(this); + if(state == STATE_DISABLED || !t || !gameCnt) + return; - if (!(game[0]->GetEffect() || game[0]->GetEffectOnOver())) { - for (int i=0; iSetEffectGrow(); - } + if(!(game[0]->GetEffect() || game[0]->GetEffectOnOver())) + { + for(int i=0; iSetEffectGrow(); + } + + btnRight->Update(t); + btnLeft->Update(t); + btnRowUp->Update(t); + btnRowDown->Update(t); + + selectedItem = -1; + clickedItem = -1; + for(int i=0; iUpdate(t); + if(game[i]->GetState() == STATE_SELECTED) + { + selectedItem = i; + } + if(game[i]->GetState() == STATE_CLICKED) + { + clickedItem = i; + } - btnRight->Update(t); - btnLeft->Update(t); - btnRowUp->Update(t); - btnRowDown->Update(t); + } + // navigation + if(focus && gameCnt >= (pagesize-2*rows) && goLeft==0 && goRight==0) + { + // Left/Right Navigation - selectedItem = -1; - clickedItem = -1; - for (int i=0; iUpdate(t); - if (game[i]->GetState() == STATE_SELECTED) { - selectedItem = i; - } - if (game[i]->GetState() == STATE_CLICKED) { - clickedItem = i; - } + if (btnLeft->GetState() == STATE_CLICKED) + { + WPAD_ScanPads(); + u16 buttons = 0; + for(int i=0; i<4; i++) + buttons |= WPAD_ButtonsHeld(i); + if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_MINUS) || t->Left())) + { + btnLeft->ResetState(); + return; + } - } - // navigation - if (focus && gameCnt >= (pagesize-2*rows) && goLeft==0 && goRight==0) { - // Left/Right Navigation + if (Settings.xflip==sysmenu || Settings.xflip==yes || Settings.xflip==disk3d) + goRight = goSteps; + else + goLeft = goSteps; + } + else if(btnRight->GetState() == STATE_CLICKED) + { + WPAD_ScanPads(); + u16 buttons = 0; + for(int i=0; i<4; i++) + buttons |= WPAD_ButtonsHeld(i); + if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_PLUS) || t->Right())) + { + btnRight->ResetState(); + return; + } + if (Settings.xflip==sysmenu ||Settings.xflip==yes || Settings.xflip==disk3d) + goLeft = goSteps; + else + goRight = goSteps; + } - if (btnLeft->GetState() == STATE_CLICKED) { - WPAD_ScanPads(); - u16 buttons = 0; - for (int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if (!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_MINUS) || t->Left())) { - btnLeft->ResetState(); - return; - } + if (goLeft == goSteps) + { + GuiButton *tmpButton[rows]; + GuiTooltip *tmpTooltip[rows]; + listOffset = OFFSETLIMIT(listOffset + rows, rows, gameCnt); // set the new listOffset + // Save left Tooltip & Button and destroy left Image + Image-Data + for (int i=0; iSetImage(NULL); + tmpTooltip[i] = titleTT[i]; + tmpButton[i] = game[i]; + } + // Move all Page-Entries one step left + for (int i=0; i<(pagesize-rows); i++) + { + titleTT[i] = titleTT[i+rows]; + coverImg[i] = coverImg[i+rows]; + game[i] = game[i+rows]; + gameIndex[i] = gameIndex[i+rows]; + } + // set saved Tooltip, Button & gameIndex to right + int wsi = CFG.widescreen ? 0:1; + int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); + int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); - if (Settings.xflip==sysmenu || Settings.xflip==yes || Settings.xflip==disk3d) - goRight = goSteps; - else - goLeft = goSteps; - } else if (btnRight->GetState() == STATE_CLICKED) { - WPAD_ScanPads(); - u16 buttons = 0; - for (int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if (!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_PLUS) || t->Right())) { - btnRight->ResetState(); - return; - } - if (Settings.xflip==sysmenu ||Settings.xflip==yes || Settings.xflip==disk3d) - goLeft = goSteps; - else - goRight = goSteps; - } + for (int i=0; iSetWidescreen(CFG.widescreen); + coverImg[ii] ->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); + coverImg[ii] ->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); + } + titleTT[ii] ->SetText(get_title(&gameList[gameIndex[ii]])); + } + else + { + titleTT[ii] ->SetText(NULL); + } - if (goLeft == goSteps) { - GuiButton *tmpButton[rows]; - GuiTooltip *tmpTooltip[rows]; - listOffset = OFFSETLIMIT(listOffset + rows, rows, gameCnt); // set the new listOffset - // Save left Tooltip & Button and destroy left Image + Image-Data - for (int i=0; iSetImage(NULL); - tmpTooltip[i] = titleTT[i]; - tmpButton[i] = game[i]; - } - // Move all Page-Entries one step left - for (int i=0; i<(pagesize-rows); i++) { - titleTT[i] = titleTT[i+rows]; - coverImg[i] = coverImg[i+rows]; - game[i] = game[i+rows]; - gameIndex[i] = gameIndex[i+rows]; - } - // set saved Tooltip, Button & gameIndex to right - int wsi = CFG.widescreen ? 0:1; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + game[ii] = tmpButton[i]; + game[ii] ->SetImage(coverImg[ii]); + game[ii] ->SetPosition(Pos[ii][wsi][0], Pos[ii][wsi][1]); + game[ii] ->SetSkew(&Skew[ii][0]); + game[ii] ->RemoveToolTip(); + if(gameIndex[ii] != -1) + { + game[ii] ->SetClickable(true); + game[ii] ->SetVisible(true); + } + else + { + game[ii] ->SetVisible(false); + game[ii] ->SetClickable(false); + game[ii] ->RemoveSoundOver(); + } + } + // Set Tooltip-Position + int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); + int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; + for (int i=0; iSetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); + break; + case 1: + game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); + break; + case 2: + game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); + break; + default: + break; + } + } + } + else if (goRight == goSteps) + { + GuiButton *tmpButton[rows]; + GuiTooltip *tmpTooltip[rows]; + listOffset = OFFSETLIMIT(listOffset - rows, rows, gameCnt); // set the new listOffset + // Save right Button & Tooltip and destroy right Image-Data + for (int i=0; iSetImage(NULL); + tmpTooltip[i] = titleTT[ii]; + tmpButton[i] = game[ii]; + } + // Move all Page-Entries one step right + for (int i=pagesize-1; i>=rows; i--) + { + titleTT[i] = titleTT[i-rows]; + coverImg[i] = coverImg[i-rows]; + game[i] = game[i-rows]; + gameIndex[i] = gameIndex[i-rows]; + } + // set saved Image, Button & gameIndex to left + int wsi = CFG.widescreen ? 0:1; + int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); + int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); - for (int i=0; iSetWidescreen(CFG.widescreen); - coverImg[ii] ->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); - coverImg[ii] ->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); - } - titleTT[ii] ->SetText(get_title(&gameList[gameIndex[ii]])); - } else { - titleTT[ii] ->SetText(NULL); - } + for (int i=0; iSetWidescreen(CFG.widescreen); + coverImg[i] ->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); + coverImg[i] ->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); + } + titleTT[i] ->SetText(get_title(&gameList[gameIndex[i]])); + } + else + { + titleTT[i] ->SetText(NULL); + } + game[i] = tmpButton[i]; + game[i] ->SetImage(coverImg[i]); + game[i] ->SetPosition(Pos[i][wsi][0], Pos[i][wsi][1]); + game[i] ->SetSkew(&Skew[i][0]); + game[i] ->RemoveToolTip(); + if(gameIndex[i] != -1) + { + game[i] ->SetClickable(true); + game[i] ->SetVisible(true); + } + else + { + game[i] ->SetVisible(false); + game[i] ->SetClickable(false); + game[i] ->RemoveSoundOver(); + } + } + // Set Tooltip-Position + int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); + int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; + for (int i=0; i< pagesize; i++) + { + switch((i*3)/pagesize) + { + case 0: + game[i]->SetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); + break; + case 1: + game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); + break; + case 2: + game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); + break; + default: + break; + } + } + } + } - game[ii] = tmpButton[i]; - game[ii] ->SetImage(coverImg[ii]); - game[ii] ->SetPosition(Pos[ii][wsi][0], Pos[ii][wsi][1]); - game[ii] ->SetSkew(&Skew[ii][0]); - game[ii] ->RemoveToolTip(); - if (gameIndex[ii] != -1) { - game[ii] ->SetClickable(true); - game[ii] ->SetVisible(true); - } else { - game[ii] ->SetVisible(false); - game[ii] ->SetClickable(false); - game[ii] ->RemoveSoundOver(); - } - } - // Set Tooltip-Position - int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); - int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; - for (int i=0; iSetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); - break; - case 1: - game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); - break; - case 2: - game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); - break; - default: - break; - } - } - } else if (goRight == goSteps) { - GuiButton *tmpButton[rows]; - GuiTooltip *tmpTooltip[rows]; - listOffset = OFFSETLIMIT(listOffset - rows, rows, gameCnt); // set the new listOffset - // Save right Button & Tooltip and destroy right Image-Data - for (int i=0; iSetImage(NULL); - tmpTooltip[i] = titleTT[ii]; - tmpButton[i] = game[ii]; - } - // Move all Page-Entries one step right - for (int i=pagesize-1; i>=rows; i--) { - titleTT[i] = titleTT[i-rows]; - coverImg[i] = coverImg[i-rows]; - game[i] = game[i-rows]; - gameIndex[i] = gameIndex[i-rows]; - } - // set saved Image, Button & gameIndex to left - int wsi = CFG.widescreen ? 0:1; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + if ((btnRowUp->GetState() == STATE_CLICKED)) + { + if ((rows==1)&&(gameCnt>=18))this->ChangeRows(2); + else if ((rows==2)&&(gameCnt>=45))this->ChangeRows(3); + btnRowUp->ResetState(); + return; + } - for (int i=0; iSetWidescreen(CFG.widescreen); - coverImg[i] ->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); - coverImg[i] ->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); - } - titleTT[i] ->SetText(get_title(&gameList[gameIndex[i]])); - } else { - titleTT[i] ->SetText(NULL); - } - game[i] = tmpButton[i]; - game[i] ->SetImage(coverImg[i]); - game[i] ->SetPosition(Pos[i][wsi][0], Pos[i][wsi][1]); - game[i] ->SetSkew(&Skew[i][0]); - game[i] ->RemoveToolTip(); - if (gameIndex[i] != -1) { - game[i] ->SetClickable(true); - game[i] ->SetVisible(true); - } else { - game[i] ->SetVisible(false); - game[i] ->SetClickable(false); - game[i] ->RemoveSoundOver(); - } - } - // Set Tooltip-Position - int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); - int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; - for (int i=0; i< pagesize; i++) { - switch ((i*3)/pagesize) { - case 0: - game[i]->SetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); - break; - case 1: - game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); - break; - case 2: - game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); - break; - default: - break; - } - } - } - } + if ((btnRowDown->GetState() == STATE_CLICKED)) + { + if (rows==3)this->ChangeRows(2); + else if (rows==2)this->ChangeRows(1); + btnRowDown->ResetState(); + return; + } - if ((btnRowUp->GetState() == STATE_CLICKED)) { - if ((rows==1)&&(gameCnt>=18))this->ChangeRows(2); - else if ((rows==2)&&(gameCnt>=45))this->ChangeRows(3); - btnRowUp->ResetState(); - return; - } - - if ((btnRowDown->GetState() == STATE_CLICKED)) { - if (rows==3)this->ChangeRows(2); - else if (rows==2)this->ChangeRows(1); - btnRowDown->ResetState(); - return; - } - - if (updateCB) - updateCB(this); + if(updateCB) + updateCB(this); } -void GuiGameGrid::Reload(struct discHdr * l, int count, int Rows, int ListOffset) { - LOCK(this); +void GuiGameGrid::Reload(struct discHdr * l, int count, int Rows, int ListOffset) +{ + LOCK(this); + + // CleanUp + if(game) + for(int i=pagesize-1; i>=0; i--) + delete game[i]; - // CleanUp - if (game) - for (int i=pagesize-1; i>=0; i--) - delete game[i]; - - if (coverImg) - for (int i=pagesize-1; i>=0; i--) - delete coverImg[i]; + if(coverImg) + for(int i=pagesize-1; i>=0; i--) + delete coverImg[i]; // if(cover) // for(int i=pagesize-1; i>=0; i--) // delete cover[i]; + + if(titleTT) + for(int i=pagesize-1; i>=0; i--) + delete titleTT[i]; - if (titleTT) - for (int i=pagesize-1; i>=0; i--) - delete titleTT[i]; - - delete [] gameIndex; - delete [] game; - delete [] coverImg; + delete [] gameIndex; + delete [] game; + delete [] coverImg; // delete [] cover; - delete [] titleTT; + delete [] titleTT; + + gameList = l; + gameCnt = count; + goLeft = 0; + goRight = 0; - gameList = l; - gameCnt = count; - goLeft = 0; - goRight = 0; + rows = Rows > 3 ? 3 : (Rows < 1 ? 1 : Rows); + if ((count<45)&&(rows==3))rows=2; + if ((count<18)&&(rows==2))rows=1; - rows = Rows > 3 ? 3 : (Rows < 1 ? 1 : Rows); - if ((count<45)&&(rows==3))rows=2; - if ((count<18)&&(rows==2))rows=1; + if(ListOffset>=0) // if ListOffset < 0 then no change + listOffset = ListOffset; + listOffset = OFFSETLIMIT(listOffset, rows, gameCnt); - if (ListOffset>=0) // if ListOffset < 0 then no change - listOffset = ListOffset; - listOffset = OFFSETLIMIT(listOffset, rows, gameCnt); + selectedItem = -1; + clickedItem = -1; - selectedItem = -1; - clickedItem = -1; + pagesize = ROWS2PAGESIZE(rows); - pagesize = ROWS2PAGESIZE(rows); - - // Page-Stuff - gameIndex = new int[pagesize]; - titleTT = new GuiTooltip *[pagesize]; + // Page-Stuff + gameIndex = new int[pagesize]; + titleTT = new GuiTooltip *[pagesize]; // cover = new GuiImageData *[pagesize]; - coverImg = new GuiImageAsync *[pagesize]; - game = new GuiButton *[pagesize]; + coverImg = new GuiImageAsync *[pagesize]; + game = new GuiButton *[pagesize]; - int wsi = CFG.widescreen ? 0:1; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + int wsi = CFG.widescreen ? 0:1; + int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); + int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); - int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); - int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; + int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); + int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; + + for(int i=0; i < pagesize; i++) + { + //------------------------ + // Index + //------------------------ + gameIndex[i] = GetGameIndex(i, rows, listOffset, gameCnt); - for (int i=0; i < pagesize; i++) { - //------------------------ - // Index - //------------------------ - gameIndex[i] = GetGameIndex(i, rows, listOffset, gameCnt); + //------------------------ + // Tooltip + //------------------------ + if( gameIndex[i] != -1 ) + titleTT[i] = new GuiTooltip(get_title(&gameList[gameIndex[i]]), THEME.tooltipAlpha); + else + titleTT[i] = new GuiTooltip(NULL, THEME.tooltipAlpha); - //------------------------ - // Tooltip - //------------------------ - if ( gameIndex[i] != -1 ) - titleTT[i] = new GuiTooltip(get_title(&gameList[gameIndex[i]]), THEME.tooltipAlpha); - else - titleTT[i] = new GuiTooltip(NULL, THEME.tooltipAlpha); - - //------------------------ - // ImageData - //------------------------ -// if( gameIndex[i] != -1 ) + //------------------------ + // ImageData + //------------------------ +// if( gameIndex[i] != -1 ) // cover[i] = LoadCoverImage(&gameList[gameIndex[i]], false /*bool Prefere3D*/); // else // cover[i] = new GuiImageData(NULL); - //------------------------ - // Image - //------------------------ - coverImg[i] = NULL; - if ( gameIndex[i] != -1 ) { - coverImg[i] = new GuiImageAsync(GameGridLoadCoverImage, &gameList[gameIndex[i]], sizeof(struct discHdr), &noCover); - if (coverImg[i]) { - coverImg[i]->SetWidescreen(CFG.widescreen); - // if ( rows == 2 ) coverImg[i]->SetScale(.6); //these are the numbers for 2 rows - // else if ( rows == 3 ) coverImg[i]->SetScale(.26); //these are the numbers for 3 rows - coverImg[i]->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); - coverImg[i]->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); - } - } - - //------------------------ - // GameButton - //------------------------ - game[i] = new GuiButton(VALUE4ROWS(rows, 160, 75, 35), VALUE4ROWS(rows, 224, 133, 68)); - game[i]->SetParent(this); - game[i]->SetImage(coverImg[i]); - game[i]->SetAlignment(ALIGN_TOP,ALIGN_LEFT); - game[i]->SetPosition(Pos[i][wsi][0]+THEME.gamegrid_x, Pos[i][wsi][1]+THEME.gamegrid_y); - game[i]->SetSkew(&Skew[i][0]); - game[i]->SetTrigger(trigA); - game[i]->SetSoundOver(btnSoundOver); - game[i]->SetSoundClick(btnSoundClick); - game[i]->SetRumble(false); - switch ((i*3)/pagesize) { - case 0: - game[i]->SetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); - break; - case 1: - game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); - break; - case 2: - game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); - break; - default: - break; - } - if (gameIndex[i] >= 0) { - game[i]->SetClickable(true); - game[i]->SetVisible(true); - } else { - game[i]->SetVisible(false); - game[i]->SetClickable(false); - // game[i]->RemoveSoundOver(); - } - } - Settings.gridRows = rows; - if (isInserted(bootDevice)) - cfg_save_global(); + //------------------------ + // Image + //------------------------ + coverImg[i] = NULL; + if( gameIndex[i] != -1 ) + { + coverImg[i] = new GuiImageAsync(GameGridLoadCoverImage, &gameList[gameIndex[i]], sizeof(struct discHdr), &noCover); + if(coverImg[i]) + { + coverImg[i]->SetWidescreen(CFG.widescreen); + // if ( rows == 2 ) coverImg[i]->SetScale(.6); //these are the numbers for 2 rows + // else if ( rows == 3 ) coverImg[i]->SetScale(.26); //these are the numbers for 3 rows + coverImg[i]->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); + coverImg[i]->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); + } + } + + //------------------------ + // GameButton + //------------------------ + game[i] = new GuiButton(VALUE4ROWS(rows, 160, 75, 35), VALUE4ROWS(rows, 224, 133, 68)); + game[i]->SetParent(this); + game[i]->SetImage(coverImg[i]); + game[i]->SetAlignment(ALIGN_TOP,ALIGN_LEFT); + game[i]->SetPosition(Pos[i][wsi][0]+THEME.gamegrid_x, Pos[i][wsi][1]+THEME.gamegrid_y); + game[i]->SetSkew(&Skew[i][0]); + game[i]->SetTrigger(trigA); + game[i]->SetSoundOver(btnSoundOver); + game[i]->SetSoundClick(btnSoundClick); + game[i]->SetRumble(false); + switch((i*3)/pagesize) + { + case 0: + game[i]->SetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); + break; + case 1: + game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); + break; + case 2: + game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); + break; + default: + break; + } + if(gameIndex[i] >= 0) + { + game[i]->SetClickable(true); + game[i]->SetVisible(true); + } + else + { + game[i]->SetVisible(false); + game[i]->SetClickable(false); + // game[i]->RemoveSoundOver(); + } + } + Settings.gridRows = rows; + if(isInserted(bootDevice)) + cfg_save_global(); } diff --git a/source/libwiigui/gui_gamegrid.h b/source/libwiigui/gui_gamegrid.h index f87005a3..7ff01d9a 100644 --- a/source/libwiigui/gui_gamegrid.h +++ b/source/libwiigui/gui_gamegrid.h @@ -4,58 +4,59 @@ #include "gui.h" #include "../usbloader/disc.h" class GuiImageAsync; -class GuiGameGrid : public GuiElement { -public: - GuiGameGrid(int w, int h, struct discHdr * l, int gameCnt, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); - ~GuiGameGrid(); - int FindMenuItem(int c, int d); - int GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); - int GetOffset(); - void Reload(struct discHdr * l, int count, int Rows, int ListOffset); - void ChangeRows(int n); -protected: - GuiImageData noCover; - int selectedItem; - int listOffset; - int pagesize; - int clickedItem; - int rows; - int goLeft; - int goRight; +class GuiGameGrid : public GuiElement +{ + public: + GuiGameGrid(int w, int h, struct discHdr * l, int gameCnt, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); + ~GuiGameGrid(); + int FindMenuItem(int c, int d); + int GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus(int f); + void Draw(); + void Update(GuiTrigger * t); + int GetOffset(); + void Reload(struct discHdr * l, int count, int Rows, int ListOffset); + void ChangeRows(int n); + protected: + GuiImageData noCover; + int selectedItem; + int listOffset; + int pagesize; + int clickedItem; + int rows; + int goLeft; + int goRight; - struct discHdr * gameList; - int gameCnt; + struct discHdr * gameList; + int gameCnt; - int * gameIndex; - GuiButton ** game; - GuiTooltip ** titleTT; - GuiImageAsync ** coverImg; + int * gameIndex; + GuiButton ** game; + GuiTooltip ** titleTT; + GuiImageAsync ** coverImg; + + + GuiButton * btnRight; + GuiButton * btnLeft; + GuiButton * btnRowUp; + GuiButton * btnRowDown; + GuiImage * btnLeftImg; + GuiImage * btnRightImg; - GuiButton * btnRight; - GuiButton * btnLeft; - GuiButton * btnRowUp; - GuiButton * btnRowDown; - - GuiImage * btnLeftImg; - GuiImage * btnRightImg; - - GuiImageData * imgLeft; - GuiImageData * imgRight; - - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigL; - GuiTrigger * trigR; - GuiTrigger * trigPlus; - GuiTrigger * trigMinus; - GuiTrigger * trig1; - GuiTrigger * trig2; + GuiImageData * imgLeft; + GuiImageData * imgRight; + + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigL; + GuiTrigger * trigR; + GuiTrigger * trigPlus; + GuiTrigger * trigMinus; + GuiTrigger * trig1; + GuiTrigger * trig2; }; #endif diff --git a/source/libwiigui/gui_image.cpp b/source/libwiigui/gui_image.cpp index 58381ce1..9816b50f 100644 --- a/source/libwiigui/gui_image.cpp +++ b/source/libwiigui/gui_image.cpp @@ -12,276 +12,300 @@ /** * Constructor for the GuiImage class. */ -GuiImage::GuiImage() { - image = NULL; - width = 0; - height = 0; - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_DATA; +GuiImage::GuiImage() +{ + image = NULL; + width = 0; + height = 0; + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_DATA; } -GuiImage::GuiImage(GuiImageData * img) { - if (img) { - image = img->GetImage(); - width = img->GetWidth(); - height = img->GetHeight(); - } else { - image = NULL; - width = 0; - height = 0; - } - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_DATA; +GuiImage::GuiImage(GuiImageData * img) +{ + if(img) + { + image = img->GetImage(); + width = img->GetWidth(); + height = img->GetHeight(); + } + else + { + image = NULL; + width = 0; + height = 0; + } + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_DATA; } -GuiImage::GuiImage(u8 * img, int w, int h) { +GuiImage::GuiImage(u8 * img, int w, int h) +{ image = img; - width = w; - height = h; - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_TEXTURE; + width = w; + height = h; + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_TEXTURE; } -GuiImage::GuiImage(int w, int h, GXColor c) { - image = (u8 *)memalign (32, w * h * 4); - width = w; - height = h; - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COLOR; +GuiImage::GuiImage(int w, int h, GXColor c) +{ + image = (u8 *)memalign (32, w * h * 4); + width = w; + height = h; + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COLOR; - if (!image) - return; + if(!image) + return; - int x, y; + int x, y; - for (y=0; y < h; y++) { - for (x=0; x < w; x++) { - this->SetPixel(x, y, c); - } - } - int len = w*h*4; - if (len%32) len += (32-len%32); - DCFlushRange(image, len); + for(y=0; y < h; y++) + { + for(x=0; x < w; x++) + { + this->SetPixel(x, y, c); + } + } + int len = w*h*4; + if(len%32) len += (32-len%32); + DCFlushRange(image, len); } -GuiImage::GuiImage(GuiImage &srcimage) : GuiElement() { - width = srcimage.GetWidth(); - height = srcimage.GetHeight(); +GuiImage::GuiImage(GuiImage &srcimage) : GuiElement() +{ + width = srcimage.GetWidth(); + height = srcimage.GetHeight(); int len = width * height * 4; - if (len%32) len += (32-len%32); + if(len%32) len += (32-len%32); image = (u8 *)memalign (32, len); - memcpy(image, srcimage.GetImage(), len); - DCFlushRange(image, len); - imageangle = srcimage.GetAngle(); - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COPY; + memcpy(image, srcimage.GetImage(), len); + DCFlushRange(image, len); + imageangle = srcimage.GetAngle(); + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COPY; } -GuiImage::GuiImage(GuiImage *srcimage) : GuiElement() { - width = srcimage->GetWidth(); - height = srcimage->GetHeight(); +GuiImage::GuiImage(GuiImage *srcimage) : GuiElement() +{ + width = srcimage->GetWidth(); + height = srcimage->GetHeight(); int len = width * height * 4; - if (len%32) len += (32-len%32); + if(len%32) len += (32-len%32); image = (u8 *)memalign (32, len); - memcpy(image, srcimage->GetImage(), len); - DCFlushRange(image, len); - imageangle = srcimage->GetAngle(); - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COPY; + memcpy(image, srcimage->GetImage(), len); + DCFlushRange(image, len); + imageangle = srcimage->GetAngle(); + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COPY; } -GuiImage &GuiImage::operator=(GuiImage &srcimage) { - if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { +GuiImage &GuiImage::operator=(GuiImage &srcimage) +{ + if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { free(image); image = NULL; } - width = srcimage.GetWidth(); - height = srcimage.GetHeight(); + width = srcimage.GetWidth(); + height = srcimage.GetHeight(); int len = width * height * 4; - if (len%32) len += (32-len%32); + if(len%32) len += (32-len%32); image = (u8 *)memalign (32, len); - memcpy(image, srcimage.GetImage(), len); - DCFlushRange(image, len); - imageangle = srcimage.GetAngle(); - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COPY; - return *this; + memcpy(image, srcimage.GetImage(), len); + DCFlushRange(image, len); + imageangle = srcimage.GetAngle(); + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COPY; + return *this; } /** * Destructor for the GuiImage class. */ -GuiImage::~GuiImage() { - if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free(image); +GuiImage::~GuiImage() +{ + if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { + free(image); image = NULL; - } + } } -u8 * GuiImage::GetImage() { - return image; +u8 * GuiImage::GetImage() +{ + return image; } -void GuiImage::SetImage(GuiImageData * img) { - LOCK(this); - if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free(image); - image = NULL; - } +void GuiImage::SetImage(GuiImageData * img) +{ + LOCK(this); + if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { + free(image); + image = NULL; + } - image = img->GetImage(); - width = img->GetWidth(); - height = img->GetHeight(); - imgType = IMAGE_DATA; + image = img->GetImage(); + width = img->GetWidth(); + height = img->GetHeight(); + imgType = IMAGE_DATA; } -void GuiImage::SetImage(u8 * img, int w, int h) { - LOCK(this); - if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free(image); - image = NULL; - } - image = img; - width = w; - height = h; - imgType = IMAGE_TEXTURE; +void GuiImage::SetImage(u8 * img, int w, int h) +{ + LOCK(this); + if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { + free(image); + image = NULL; + } + image = img; + width = w; + height = h; + imgType = IMAGE_TEXTURE; } -void GuiImage::SetAngle(float a) { - LOCK(this); - imageangle = a; +void GuiImage::SetAngle(float a) +{ + LOCK(this); + imageangle = a; } -float GuiImage::GetAngle() { - return imageangle; +float GuiImage::GetAngle() +{ + return imageangle; } -void GuiImage::SetTile(int t) { - LOCK(this); - tile = t; +void GuiImage::SetTile(int t) +{ + LOCK(this); + tile = t; } -void GuiImage::SetWidescreen(bool w) { - LOCK(this); - widescreen = w; +void GuiImage::SetWidescreen(bool w) +{ + LOCK(this); + widescreen = w; } -void GuiImage::SetParentAngle(bool a) { - LOCK(this); +void GuiImage::SetParentAngle(bool a) +{ + LOCK(this); parentangle = a; } -GXColor GuiImage::GetPixel(int x, int y) { - if (!image || this->GetWidth() <= 0 || x < 0 || y < 0) - return (GXColor) {0, 0, 0, 0}; +GXColor GuiImage::GetPixel(int x, int y) +{ + if(!image || this->GetWidth() <= 0 || x < 0 || y < 0) + return (GXColor){0, 0, 0, 0}; - u32 offset = (((y >> 2)<<4)*this->GetWidth()) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); - GXColor color; - color.a = *(image+offset); - color.r = *(image+offset+1); - color.g = *(image+offset+32); - color.b = *(image+offset+33); - return color; + u32 offset = (((y >> 2)<<4)*this->GetWidth()) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); + GXColor color; + color.a = *(image+offset); + color.r = *(image+offset+1); + color.g = *(image+offset+32); + color.b = *(image+offset+33); + return color; } -void GuiImage::SetPixel(int x, int y, GXColor color) { - LOCK(this); - if (!image || this->GetWidth() <= 0 || x < 0 || y < 0) - return; +void GuiImage::SetPixel(int x, int y, GXColor color) +{ + LOCK(this); + if(!image || this->GetWidth() <= 0 || x < 0 || y < 0) + return; - u32 offset = (((y >> 2)<<4)*this->GetWidth()) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); - *(image+offset) = color.a; - *(image+offset+1) = color.r; - *(image+offset+32) = color.g; - *(image+offset+33) = color.b; + u32 offset = (((y >> 2)<<4)*this->GetWidth()) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); + *(image+offset) = color.a; + *(image+offset+1) = color.r; + *(image+offset+32) = color.g; + *(image+offset+33) = color.b; } -void GuiImage::SetGrayscale(void) { +void GuiImage::SetGrayscale(void) +{ LOCK(this); GXColor color; u32 offset, gray; - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { + for(int x = 0; x < width; x++) { + for(int y = 0; y < height; y++) { offset = (((y >> 2)<<4)*width) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); color.r = *(image+offset+1); color.g = *(image+offset+32); @@ -296,130 +320,143 @@ void GuiImage::SetGrayscale(void) { } int len = width*height*4; - if (len%32) len += (32-len%32); - DCFlushRange(image, len); + if(len%32) len += (32-len%32); + DCFlushRange(image, len); } -void GuiImage::SetStripe(int s) { - LOCK(this); - stripe = s; +void GuiImage::SetStripe(int s) +{ + LOCK(this); + stripe = s; } -void GuiImage::SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4) { +void GuiImage::SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4) +{ - xx1 = XX1; - yy1 = YY1; - xx2 = XX2; - yy2 = YY2; - xx3 = XX3; - yy3 = YY3; - xx4 = XX4; - yy4 = YY4; + xx1 = XX1; + yy1 = YY1; + xx2 = XX2; + yy2 = YY2; + xx3 = XX3; + yy3 = YY3; + xx4 = XX4; + yy4 = YY4; } -void GuiImage::SetSkew(int *skew) { +void GuiImage::SetSkew(int *skew) +{ - xx1 = *skew++; - yy1 = *skew++; - xx2 = *skew++; - yy2 = *skew++; - xx3 = *skew++; - yy3 = *skew++; - xx4 = *skew++; - yy4 = *skew; + xx1 = *skew++; + yy1 = *skew++; + xx2 = *skew++; + yy2 = *skew++; + xx3 = *skew++; + yy3 = *skew++; + xx4 = *skew++; + yy4 = *skew; } -void GuiImage::ColorStripe(int shift) { - LOCK(this); - int x, y; - GXColor color; - int alt = 0; +void GuiImage::ColorStripe(int shift) +{ + LOCK(this); + int x, y; + GXColor color; + int alt = 0; - for (y=0; y < this->GetHeight(); y++) { - if (y % 3 == 0) - alt ^= 1; + for(y=0; y < this->GetHeight(); y++) + { + if(y % 3 == 0) + alt ^= 1; - for (x=0; x < this->GetWidth(); x++) { - color = GetPixel(x, y); + for(x=0; x < this->GetWidth(); x++) + { + color = GetPixel(x, y); - if (alt) { - if (color.r < 255-shift) - color.r += shift; - else - color.r = 255; - if (color.g < 255-shift) - color.g += shift; - else - color.g = 255; - if (color.b < 255-shift) - color.b += shift; - else - color.b = 255; + if(alt) + { + if(color.r < 255-shift) + color.r += shift; + else + color.r = 255; + if(color.g < 255-shift) + color.g += shift; + else + color.g = 255; + if(color.b < 255-shift) + color.b += shift; + else + color.b = 255; - color.a = 255; - } else { - if (color.r > shift) - color.r -= shift; - else - color.r = 0; - if (color.g > shift) - color.g -= shift; - else - color.g = 0; - if (color.b > shift) - color.b -= shift; - else - color.b = 0; + color.a = 255; + } + else + { + if(color.r > shift) + color.r -= shift; + else + color.r = 0; + if(color.g > shift) + color.g -= shift; + else + color.g = 0; + if(color.b > shift) + color.b -= shift; + else + color.b = 0; - color.a = 255; - } - SetPixel(x, y, color); - } - } + color.a = 255; + } + SetPixel(x, y, color); + } + } int len = width*height*4; - if (len%32) len += (32-len%32); - DCFlushRange(image, len); + if(len%32) len += (32-len%32); + DCFlushRange(image, len); } /** * Draw the button on screen */ -void GuiImage::Draw() { - LOCK(this); - if (!image || !this->IsVisible() || tile == 0) - return; +void GuiImage::Draw() +{ + LOCK(this); + if(!image || !this->IsVisible() || tile == 0) + return; - float currScale = this->GetScale(); - int currLeft = this->GetLeft(); + float currScale = this->GetScale(); + int currLeft = this->GetLeft(); float currAngleDyn = this->GetAngleDyn(); - if (currAngleDyn && parentangle) + if(currAngleDyn && parentangle) imageangle = currAngleDyn; - if (tile > 0) { - for (int i=0; iGetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1,yy1,xx2,yy2,xx3,yy3,xx4,yy4); - } else { - // temporary (maybe), used to correct offset for scaled images - if (scale != 1) - currLeft = currLeft - width/2 + (width*scale)/2; + if(tile > 0) + { + for(int i=0; iGetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1,yy1,xx2,yy2,xx3,yy3,xx4,yy4); + } + else + { + // temporary (maybe), used to correct offset for scaled images + if(scale != 1) + currLeft = currLeft - width/2 + (width*scale)/2; - Menu_DrawImg(currLeft, this->GetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1,yy1,xx2,yy2,xx3,yy3,xx4,yy4); - } + Menu_DrawImg(currLeft, this->GetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1,yy1,xx2,yy2,xx3,yy3,xx4,yy4); + } - if (stripe > 0) - for (int y=0; y < this->GetHeight(); y+=6) - Menu_DrawRectangle(currLeft,this->GetTop()+y,this->GetWidth(),3,(GXColor) {0, 0, 0, stripe},1); + if(stripe > 0) + for(int y=0; y < this->GetHeight(); y+=6) + Menu_DrawRectangle(currLeft,this->GetTop()+y,this->GetWidth(),3,(GXColor){0, 0, 0, stripe},1); - this->UpdateEffects(); + this->UpdateEffects(); } diff --git a/source/libwiigui/gui_image_async.cpp b/source/libwiigui/gui_image_async.cpp index 321ecb0d..a16f7363 100644 --- a/source/libwiigui/gui_image_async.cpp +++ b/source/libwiigui/gui_image_async.cpp @@ -14,34 +14,37 @@ #include "gui_image_async.h" static mutex_t debugLock = LWP_MUTEX_NULL; -void debug(int Line, const char* Format, ...) { - if (debugLock==0) LWP_MutexInit(&debugLock, false); +void debug(int Line, const char* Format, ...) +{ + if(debugLock==0) LWP_MutexInit(&debugLock, false); - LWP_MutexLock(debugLock); - - FILE *fp = fopen("SD:/debug.txt", "a"); - if (fp) { - char theTime[10]; - time_t rawtime = time(0); //this fixes code dump caused by the clock - struct tm * timeinfo = localtime (&rawtime); - strftime(theTime, sizeof(theTime), "%H:%M:%S", timeinfo); - char format[10+strlen(Format)+strlen(theTime)]; - sprintf(format, "%s %i - %s\n", theTime, Line, Format); - va_list va; - va_start(va, Format); - vfprintf(fp, format, va); - va_end(va); - fclose(fp); - } - LWP_MutexUnlock(debugLock); + LWP_MutexLock(debugLock); + + FILE *fp = fopen("SD:/debug.txt", "a"); + if(fp) + { + char theTime[10]; + time_t rawtime = time(0); //this fixes code dump caused by the clock + struct tm * timeinfo = localtime (&rawtime); + strftime(theTime, sizeof(theTime), "%H:%M:%S", timeinfo); + char format[10+strlen(Format)+strlen(theTime)]; + sprintf(format, "%s %i - %s\n", theTime, Line, Format); + va_list va; + va_start(va, Format); + vfprintf(fp, format, va); + va_end(va); + fclose(fp); + } + LWP_MutexUnlock(debugLock); } //#define DEBUG(format, ...) debug(__LINE__, format, ##__VA_ARGS__) -#define DEBUG(format, ...) +#define DEBUG(format, ...) -static void *memdup(const void* src, size_t len) { - void *dst = malloc(len); - if (dst) memcpy(dst, src, len); - return dst; +static void *memdup(const void* src, size_t len) +{ + void *dst = malloc(len); + if(dst) memcpy(dst, src, len); + return dst; } static std::vector List; static u32 ThreadCount = 0; @@ -51,123 +54,143 @@ static mutex_t InUseLock = LWP_MUTEX_NULL; static GuiImageAsync *InUse = NULL; static bool Quit = false; static bool CanSleep = true; -void *GuiImageAsyncThread(void *arg) { - while (!Quit) { - LWP_MutexLock(ListLock); - if (List.size()) { - LWP_MutexLock(InUseLock); +void *GuiImageAsyncThread(void *arg) +{ + while(!Quit) + { + LWP_MutexLock(ListLock); + if(List.size()) + { + LWP_MutexLock(InUseLock); - InUse = List.front(); - List.erase(List.begin()); + InUse = List.front(); + List.erase(List.begin()); - LWP_MutexUnlock(ListLock); + LWP_MutexUnlock(ListLock); - if (InUse) { - GuiImageData *data = InUse->callback(InUse->arg); - InUse->loadet_imgdata = data; - if (InUse->loadet_imgdata && InUse->loadet_imgdata->GetImage()) { - // InUse->SetImage(InUse->loadet_imgdata); can’t use here. There can occur a deadlock - // Sets the image directly without lock. This is not fine, but it prevents a deadlock - InUse->image = InUse->loadet_imgdata->GetImage(); - InUse->width = InUse->loadet_imgdata->GetWidth(); - InUse->height = InUse->loadet_imgdata->GetHeight(); - } - } - InUse = NULL; - LWP_MutexUnlock(InUseLock); - } else { - LWP_MutexUnlock(ListLock); - if (!Quit && CanSleep) - LWP_SuspendThread(Thread); - } - CanSleep = true; - } - Quit = false; - return NULL; + if(InUse) + { + GuiImageData *data = InUse->callback(InUse->arg); + InUse->loadet_imgdata = data; + if(InUse->loadet_imgdata && InUse->loadet_imgdata->GetImage()) + { + // InUse->SetImage(InUse->loadet_imgdata); can’t use here. There can occur a deadlock + // Sets the image directly without lock. This is not fine, but it prevents a deadlock + InUse->image = InUse->loadet_imgdata->GetImage(); + InUse->width = InUse->loadet_imgdata->GetWidth(); + InUse->height = InUse->loadet_imgdata->GetHeight(); + } + } + InUse = NULL; + LWP_MutexUnlock(InUseLock); + } + else + { + LWP_MutexUnlock(ListLock); + if(!Quit && CanSleep) + LWP_SuspendThread(Thread); + } + CanSleep = true; + } + Quit = false; + return NULL; } -static u32 GuiImageAsyncThreadInit() { - if (0 == ThreadCount++) { - CanSleep = false; - LWP_MutexInit(&ListLock, false); - LWP_MutexInit(&InUseLock, false); - LWP_CreateThread(&Thread, GuiImageAsyncThread, NULL, NULL, 0, 75); +static u32 GuiImageAsyncThreadInit() +{ + if(0 == ThreadCount++) + { + CanSleep = false; + LWP_MutexInit(&ListLock, false); + LWP_MutexInit(&InUseLock, false); + LWP_CreateThread(&Thread, GuiImageAsyncThread, NULL, NULL, 0, 75); // while(!CanSleep) // usleep(20); - } - return ThreadCount; + } + return ThreadCount; } -static u32 GuiImageAsyncThreadExit() { - if (--ThreadCount == 0) { - Quit = true; - LWP_ResumeThread(Thread); +static u32 GuiImageAsyncThreadExit() +{ + if(--ThreadCount == 0) + { + Quit = true; + LWP_ResumeThread(Thread); // while(Quit) // usleep(20); - LWP_JoinThread(Thread, NULL); - LWP_MutexDestroy(ListLock); - LWP_MutexDestroy(InUseLock); - Thread = LWP_THREAD_NULL; - ListLock = LWP_MUTEX_NULL; - InUseLock = LWP_MUTEX_NULL; - } - return ThreadCount; + LWP_JoinThread(Thread, NULL); + LWP_MutexDestroy(ListLock); + LWP_MutexDestroy(InUseLock); + Thread = LWP_THREAD_NULL; + ListLock = LWP_MUTEX_NULL; + InUseLock = LWP_MUTEX_NULL; + } + return ThreadCount; } -static void GuiImageAsyncThread_AddImage(GuiImageAsync* Image) { - LWP_MutexLock(ListLock); - List.push_back(Image); - LWP_MutexUnlock(ListLock); - CanSleep = false; +static void GuiImageAsyncThread_AddImage(GuiImageAsync* Image) +{ + LWP_MutexLock(ListLock); + List.push_back(Image); + LWP_MutexUnlock(ListLock); + CanSleep = false; // if(LWP_ThreadIsSuspended(Thread)) - LWP_ResumeThread(Thread); + LWP_ResumeThread(Thread); } -static void GuiImageAsyncThread_RemoveImage(GuiImageAsync* Image) { - LWP_MutexLock(ListLock); - for (std::vector::iterator iter=List.begin(); iter != List.end(); iter++) { - if (*iter == Image) { - List.erase(iter); - LWP_MutexUnlock(ListLock); - return; - } - } - if (InUse == Image) { - LWP_MutexLock(InUseLock); - LWP_MutexUnlock(InUseLock); - } - LWP_MutexUnlock(ListLock); +static void GuiImageAsyncThread_RemoveImage(GuiImageAsync* Image) +{ + LWP_MutexLock(ListLock); + for(std::vector::iterator iter=List.begin(); iter != List.end(); iter++) + { + if(*iter == Image) + { + List.erase(iter); + LWP_MutexUnlock(ListLock); + return; + } + } + if(InUse == Image) + { + LWP_MutexLock(InUseLock); + LWP_MutexUnlock(InUseLock); + } + LWP_MutexUnlock(ListLock); } /** * Constructor for the GuiImageAsync class. */ -GuiImageData *StdImageLoaderCallback(void *arg) { - return new GuiImageData((char*)arg, NULL); +GuiImageData *StdImageLoaderCallback(void *arg) +{ + return new GuiImageData((char*)arg, NULL); } GuiImageAsync::GuiImageAsync(const char *Filename, GuiImageData * PreloadImg) : - GuiImage(PreloadImg), - loadet_imgdata(NULL), - callback(StdImageLoaderCallback), - arg(strdup(Filename)) { - GuiImageAsyncThreadInit(); - GuiImageAsyncThread_AddImage(this); + GuiImage(PreloadImg), + loadet_imgdata(NULL), + callback(StdImageLoaderCallback), + arg(strdup(Filename)) +{ + GuiImageAsyncThreadInit(); + GuiImageAsyncThread_AddImage(this); } GuiImageAsync::GuiImageAsync(ImageLoaderCallback Callback, void *Arg, int ArgLen, GuiImageData * PreloadImg) : - GuiImage(PreloadImg), - loadet_imgdata(NULL), - callback(Callback), - arg(memdup(Arg, ArgLen)) { - DEBUG("Constructor %p", this); - GuiImageAsyncThreadInit(); - GuiImageAsyncThread_AddImage(this); + GuiImage(PreloadImg), + loadet_imgdata(NULL), + callback(Callback), + arg(memdup(Arg, ArgLen)) +{ +DEBUG("Constructor %p", this); + GuiImageAsyncThreadInit(); + GuiImageAsyncThread_AddImage(this); } -GuiImageAsync::~GuiImageAsync() { - GuiImageAsyncThread_RemoveImage(this); - GuiImageAsyncThreadExit(); - DEBUG("Deconstructor %p (loadet_imgdata=%p)", this, loadet_imgdata); - if (loadet_imgdata) delete loadet_imgdata; - if (arg) free(arg); +GuiImageAsync::~GuiImageAsync() +{ + GuiImageAsyncThread_RemoveImage(this); + GuiImageAsyncThreadExit(); +DEBUG("Deconstructor %p (loadet_imgdata=%p)", this, loadet_imgdata); + if(loadet_imgdata) delete loadet_imgdata; + if(arg) free(arg); } diff --git a/source/libwiigui/gui_image_async.h b/source/libwiigui/gui_image_async.h index 8c10a9f8..9c746b84 100644 --- a/source/libwiigui/gui_image_async.h +++ b/source/libwiigui/gui_image_async.h @@ -5,20 +5,21 @@ // when the image is destroied then will also the arg deleted with free() typedef GuiImageData * (*ImageLoaderCallback)(void *arg); -class GuiImageAsync : public GuiImage { +class GuiImageAsync : public GuiImage +{ public: - GuiImageAsync(const char *Filename, GuiImageData * PreloadImg); - GuiImageAsync(ImageLoaderCallback Callback, void *arg, int arglen, GuiImageData * PreloadImg); - ~GuiImageAsync(); + GuiImageAsync(const char *Filename, GuiImageData * PreloadImg); + GuiImageAsync(ImageLoaderCallback Callback, void *arg, int arglen, GuiImageData * PreloadImg); + ~GuiImageAsync(); private: - GuiImageData *loadet_imgdata; - friend void loader(GuiImageAsync *InUse); + GuiImageData *loadet_imgdata; +friend void loader(GuiImageAsync *InUse); - friend void Setter(GuiImageAsync *InUse); - friend void *GuiImageAsyncThread(void *arg); - ImageLoaderCallback callback; - void *arg; +friend void Setter(GuiImageAsync *InUse); + friend void *GuiImageAsyncThread(void *arg); + ImageLoaderCallback callback; + void *arg; }; diff --git a/source/libwiigui/gui_imagedata.cpp b/source/libwiigui/gui_imagedata.cpp index 67e1e275..562903b2 100644 --- a/source/libwiigui/gui_imagedata.cpp +++ b/source/libwiigui/gui_imagedata.cpp @@ -14,7 +14,8 @@ #include "gui.h" #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include @@ -32,251 +33,299 @@ extern "C" { extern int idiotFlag; extern char idiotChar[50]; -GuiImageData::GuiImageData(const u8 * img) { - data = NULL; - width = 0; - height = 0; +GuiImageData::GuiImageData(const u8 * img) +{ + data = NULL; + width = 0; + height = 0; - if (img) { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer(img); + if(img) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromBuffer(img); - if (!ctx) - return; + if(!ctx) + return; - int res = PNGU_GetImageProperties(ctx, &imgProp); - //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; + int res = PNGU_GetImageProperties(ctx, &imgProp); + //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if (res == PNGU_OK) { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if (len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if(res == PNGU_OK) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if(len%32) len += (32-len%32); + data = (u8 *)memalign (32, len); - if (data) { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if(data) + { + res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if (res == PNGU_OK) { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } else { - free(data); - data = NULL; - idiotFlag=1; - snprintf(idiotChar, sizeof(idiotChar), "%s", img); + if(res == PNGU_OK) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange(data, len); + } + else + { + free(data); + data = NULL; + idiotFlag=1; + snprintf(idiotChar, sizeof(idiotChar), "%s", img); - } - } - } - PNGU_ReleaseImageContext (ctx); - } + } + } + } + PNGU_ReleaseImageContext (ctx); + } } -GuiImageData::GuiImageData(const u8 * img, int imgSize) { - data = NULL; - width = 0; - height = 0; +GuiImageData::GuiImageData(const u8 * img, int imgSize) +{ + data = NULL; + width = 0; + height = 0; - if (img) { + if(img) + { if (img[0] == 0xFF && img[1] == 0xD8) { // IMAGE_JPEG LoadJpeg(img, imgSize); } - } + } } /** * Constructor for the GuiImageData class. */ -GuiImageData::GuiImageData(const char * imgPath, const u8 * buffer) { - data = NULL; - width = 0; - height = 0; +GuiImageData::GuiImageData(const char * imgPath, const u8 * buffer) +{ + data = NULL; + width = 0; + height = 0; - if (imgPath) { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); - //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; + if(imgPath) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); + //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if (ctx) { - int res = PNGU_GetImageProperties(ctx, &imgProp); + if(ctx) + { + int res = PNGU_GetImageProperties(ctx, &imgProp); - if (res == PNGU_OK) { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if (len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if(res == PNGU_OK) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if(len%32) len += (32-len%32); + data = (u8 *)memalign (32, len); - if (data) { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if(data) + { + res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if (res == PNGU_OK) { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } else { - free(data); - data = NULL; - idiotFlag=1; - snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } + if(res == PNGU_OK) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange(data, len); + } + else + { + free(data); + data = NULL; + idiotFlag=1; + snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); + } + } + } + PNGU_ReleaseImageContext (ctx); + } + } - if (!data) { //use buffer data instead - width = 0; - height = 0; - if (buffer) { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer(buffer); + if (!data) //use buffer data instead + { + width = 0; + height = 0; + if(buffer) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromBuffer(buffer); - if (!ctx) - return; + if(!ctx) + return; - int res = PNGU_GetImageProperties(ctx, &imgProp); + int res = PNGU_GetImageProperties(ctx, &imgProp); - if (res == PNGU_OK) { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if (len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if(res == PNGU_OK) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if(len%32) len += (32-len%32); + data = (u8 *)memalign (32, len); - if (data) { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if(data) + { + res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if (res == PNGU_OK) { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } else { - free(data); - data = NULL; - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } + if(res == PNGU_OK) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange(data, len); + } + else + { + free(data); + data = NULL; + } + } + } + PNGU_ReleaseImageContext (ctx); + } + } } /** * Constructor for the GuiImageData class. */ -GuiImageData::GuiImageData(const char *path, const char *file, const u8 *buffer, bool force_widescreen/*=false*/, const u8 *wbuffer/*=NULL*/) { - data = NULL; - width = 0; - height = 0; - char path_4_3[100]; - char path_16_9[100]; - char *imgPath; +GuiImageData::GuiImageData(const char *path, const char *file, const u8 *buffer, bool force_widescreen/*=false*/, const u8 *wbuffer/*=NULL*/) +{ + data = NULL; + width = 0; + height = 0; + char path_4_3[100]; + char path_16_9[100]; + char *imgPath; - snprintf(path_4_3, sizeof(path_4_3), "%s%s", path, file); - if (force_widescreen) { - snprintf(path_16_9, sizeof(path_16_9), "%sw%s", path, file); - imgPath = path_16_9; - if (wbuffer) - buffer = wbuffer; - } else - imgPath = path_4_3; + snprintf(path_4_3, sizeof(path_4_3), "%s%s", path, file); + if(force_widescreen) + { + snprintf(path_16_9, sizeof(path_16_9), "%sw%s", path, file); + imgPath = path_16_9; + if(wbuffer) + buffer = wbuffer; + } + else + imgPath = path_4_3; - for (;;) { - if (imgPath) { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); - //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; + for(;;) + { + if(imgPath) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); + //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if (ctx) { - int res = PNGU_GetImageProperties(ctx, &imgProp); + if(ctx) + { + int res = PNGU_GetImageProperties(ctx, &imgProp); - if (res == PNGU_OK) { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if (len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if(res == PNGU_OK) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if(len%32) len += (32-len%32); + data = (u8 *)memalign (32, len); - if (data) { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if(data) + { + res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if (res == PNGU_OK) { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } else { - free(data); - data = NULL; - idiotFlag=1; - snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } - if (data || imgPath == path_4_3) - break; - imgPath = path_4_3; - } + if(res == PNGU_OK) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange(data, len); + } + else + { + free(data); + data = NULL; + idiotFlag=1; + snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); + } + } + } + PNGU_ReleaseImageContext (ctx); + } + } + if(data || imgPath == path_4_3) + break; + imgPath = path_4_3; + } - if (!data) { //use buffer data instead - width = 0; - height = 0; - if (buffer) { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer(buffer); + if (!data) //use buffer data instead + { + width = 0; + height = 0; + if(buffer) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromBuffer(buffer); - if (!ctx) - return; + if(!ctx) + return; - int res = PNGU_GetImageProperties(ctx, &imgProp); + int res = PNGU_GetImageProperties(ctx, &imgProp); - if (res == PNGU_OK) { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if (len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if(res == PNGU_OK) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if(len%32) len += (32-len%32); + data = (u8 *)memalign (32, len); - if (data) { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if(data) + { + res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if (res == PNGU_OK) { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } else { - free(data); - data = NULL; - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } + if(res == PNGU_OK) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange(data, len); + } + else + { + free(data); + data = NULL; + } + } + } + PNGU_ReleaseImageContext (ctx); + } + } } /** * Destructor for the GuiImageData class. */ -GuiImageData::~GuiImageData() { - if (data) { - free(data); - data = NULL; - } +GuiImageData::~GuiImageData() +{ + if(data) + { + free(data); + data = NULL; + } } -u8 * GuiImageData::GetImage() { - return data; +u8 * GuiImageData::GetImage() +{ + return data; } -int GuiImageData::GetWidth() { - return width; +int GuiImageData::GetWidth() +{ + return width; } -int GuiImageData::GetHeight() { - return height; +int GuiImageData::GetHeight() +{ + return height; } -void GuiImageData::SetGrayscale(void) { +void GuiImageData::SetGrayscale(void) +{ GXColor color; u32 offset, gray; - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { + for(int x = 0; x < width; x++) { + for(int y = 0; y < height; y++) { offset = (((y >> 2)<<4)*width) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); color.r = *(data+offset+1); color.g = *(data+offset+32); @@ -292,64 +341,66 @@ void GuiImageData::SetGrayscale(void) { } // This function finds it's origin in GRRLIB, which can be found here: http://code.google.com/p/grrlib/ -void GuiImageData::LoadJpeg(const u8 *img, int imgSize) { - struct jpeg_decompress_struct cinfo; - struct jpeg_error_mgr jerr; +void GuiImageData::LoadJpeg(const u8 *img, int imgSize) +{ + struct jpeg_decompress_struct cinfo; + struct jpeg_error_mgr jerr; - int n = imgSize; + int n = imgSize; - while (n > 1) { - if (img[n - 1] == 0xff && img[n] == 0xd9) { - break; - } - n--; - } + while (n > 1) { + if (img[n - 1] == 0xff && img[n] == 0xd9) { + break; + } + n--; + } - jpeg_create_decompress(&cinfo); + jpeg_create_decompress(&cinfo); cinfo.err = jpeg_std_error(&jerr); cinfo.progress = NULL; jpeg_memory_src(&cinfo, img, n); jpeg_read_header(&cinfo, TRUE); - jpeg_calc_output_dimensions(&cinfo); + jpeg_calc_output_dimensions(&cinfo); - if (cinfo.output_width > new_width || cinfo.output_height > new_height) { - float factor = (cinfo.output_width > cinfo.output_height) ? (1.0 * cinfo.output_width) / new_width : (1.0 * cinfo.output_height) / new_height; - cinfo.scale_num = 1; - cinfo.scale_denom = factor; - cinfo.do_fancy_upsampling = true; - cinfo.do_block_smoothing = false; - cinfo.dct_method = JDCT_IFAST; - } + if (cinfo.output_width > new_width || cinfo.output_height > new_height) + { + float factor = (cinfo.output_width > cinfo.output_height) ? (1.0 * cinfo.output_width) / new_width : (1.0 * cinfo.output_height) / new_height; + cinfo.scale_num = 1; + cinfo.scale_denom = factor; + cinfo.do_fancy_upsampling = true; + cinfo.do_block_smoothing = false; + cinfo.dct_method = JDCT_IFAST; + } jpeg_start_decompress(&cinfo); - int rowsize = cinfo.output_width * cinfo.num_components; - unsigned char *tempBuffer = (unsigned char *) malloc(rowsize * cinfo.output_height); + int rowsize = cinfo.output_width * cinfo.num_components; + unsigned char *tempBuffer = (unsigned char *) malloc(rowsize * cinfo.output_height); JSAMPROW row_pointer[1]; - row_pointer[0] = (unsigned char*) malloc(rowsize); + row_pointer[0] = (unsigned char*) malloc(rowsize); size_t location = 0; while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, row_pointer, 1); - memcpy(tempBuffer + location, row_pointer[0], rowsize); - location += rowsize; + memcpy(tempBuffer + location, row_pointer[0], rowsize); + location += rowsize; } - int len = ((cinfo.output_width+3)>>2)*((cinfo.output_height+3)>>2)*32*2; + int len = ((cinfo.output_width+3)>>2)*((cinfo.output_height+3)>>2)*32*2; data = (u8 *) memalign(32, len); - RawTo4x4RGBA(tempBuffer, data, cinfo.output_width, cinfo.output_height); - DCFlushRange(data, len); + RawTo4x4RGBA(tempBuffer, data, cinfo.output_width, cinfo.output_height); + DCFlushRange(data, len); - width = cinfo.output_width; - height = cinfo.output_height; + width = cinfo.output_width; + height = cinfo.output_height; jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(row_pointer[0]); - free(tempBuffer); + free(tempBuffer); } /** @@ -360,7 +411,8 @@ void GuiImageData::LoadJpeg(const u8 *img, int imgSize) { * @param width * @param height */ -void GuiImageData::RawTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height) { +void GuiImageData::RawTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height) +{ unsigned int block; unsigned int i; unsigned int c; diff --git a/source/libwiigui/gui_keyboard.cpp b/source/libwiigui/gui_keyboard.cpp index d9710017..dbd01b94 100644 --- a/source/libwiigui/gui_keyboard.cpp +++ b/source/libwiigui/gui_keyboard.cpp @@ -18,657 +18,674 @@ */ unsigned int m; //const Key thekeys; -GuiKeyboard::GuiKeyboard(char * t, u32 max, int min, int lang) { - width = 540; - height = 400; - shift = 0; - caps = 0; - alt = 0; - alt2 = 0; - m = min; - int mode = lang; - selectable = true; - focus = 0; // allow focus - alignmentHor = ALIGN_CENTRE; - alignmentVert = ALIGN_MIDDLE; - kbtextmaxlen = max>sizeof(kbtextstr) ? sizeof(kbtextstr) : max; // limit max up to sizeof(kbtextstr) +GuiKeyboard::GuiKeyboard(char * t, u32 max, int min, int lang) +{ + width = 540; + height = 400; + shift = 0; + caps = 0; + alt = 0; + alt2 = 0; + m = min; + int mode = lang; + selectable = true; + focus = 0; // allow focus + alignmentHor = ALIGN_CENTRE; + alignmentVert = ALIGN_MIDDLE; + kbtextmaxlen = max>sizeof(kbtextstr) ? sizeof(kbtextstr) : max; // limit max up to sizeof(kbtextstr) // strlcpy(kbtextstr, t, kbtextmaxlen); - strncpy(kbtextstr, t, kbtextmaxlen); // strncpy is needed to fill the rest with \0 - kbtextstr[sizeof(kbtextstr)-1] = 0; // terminate with \0 - //QWERTY// - if (mode == 0) { - Key thekeys[4][11] = { - { - {'1','!'}, - {'2','@'}, - {'3','#'}, - {'4','$'}, - {'5','%'}, - {'6','^'}, - {'7','&'}, - {'8','*'}, - {'9','('}, - {'0',')'}, - {'\0','\0'} - }, - { - {'q','Q'}, - {'w','W'}, - {'e','E'}, - {'r','R'}, - {'t','T'}, - {'y','Y'}, - {'u','U'}, - {'i','I'}, - {'o','O'}, - {'p','P'}, - {'-','_'} - }, - { - {'a','A'}, - {'s','S'}, - {'d','D'}, - {'f','F'}, - {'g','G'}, - {'h','H'}, - {'j','J'}, - {'k','K'}, - {'l','L'}, - {':',';'}, - {'\'','"'} - }, + strncpy(kbtextstr, t, kbtextmaxlen); // strncpy is needed to fill the rest with \0 + kbtextstr[sizeof(kbtextstr)-1] = 0; // terminate with \0 + //QWERTY// + if (mode == 0){ + Key thekeys[4][11] = { + { + {'1','!'}, + {'2','@'}, + {'3','#'}, + {'4','$'}, + {'5','%'}, + {'6','^'}, + {'7','&'}, + {'8','*'}, + {'9','('}, + {'0',')'}, + {'\0','\0'} + }, + { + {'q','Q'}, + {'w','W'}, + {'e','E'}, + {'r','R'}, + {'t','T'}, + {'y','Y'}, + {'u','U'}, + {'i','I'}, + {'o','O'}, + {'p','P'}, + {'-','_'} + }, + { + {'a','A'}, + {'s','S'}, + {'d','D'}, + {'f','F'}, + {'g','G'}, + {'h','H'}, + {'j','J'}, + {'k','K'}, + {'l','L'}, + {':',';'}, + {'\'','"'} + }, - { - {'z','Z'}, - {'x','X'}, - {'c','C'}, - {'v','V'}, - {'b','B'}, - {'n','N'}, - {'m','M'}, - {',','<'}, - {'.','>'}, - {'/','?'}, - {'\0','\0'} - } - }; + { + {'z','Z'}, + {'x','X'}, + {'c','C'}, + {'v','V'}, + {'b','B'}, + {'n','N'}, + {'m','M'}, + {',','<'}, + {'.','>'}, + {'/','?'}, + {'\0','\0'} + } + }; - memcpy(keys, thekeys, sizeof(thekeys)); - } - //DVORAK// - if (mode == 1) { - Key thekeys[4][11] = { - { - {'1','!','\0'}, - {'2','@','\0'}, - {'3','#','\0'}, - {'4','$','\0'}, - {'5','%','\0'}, - {'6','^','\0'}, - {'7','&','\0'}, - {'8','*','\0'}, - {'9','(','\0'}, - {'0',')','\0'}, - {'\0','\0','\0'} - }, - { - {'\'','"','\0'}, - {',','<','\0'}, - {'.','>','\0'}, - {'p','P','\0'}, - {'y','Y','\0'}, - {'f','F','\0'}, - {'g','G','\0'}, - {'c','C','\0'}, - {'r','R','\0'}, - {'l','L','\0'}, - {'/','?','\0'} - }, - { - {'a','A','m'}, - {'o','O','m'}, - {'e','E','m'}, - {'u','U','m'}, - {'i','I','m'}, - {'d','D','m'}, - {'h','H','m'}, - {'t','T','m'}, - {'n','N','m'}, - {'s','S','m'}, - {'-','_','m'} - }, + memcpy(keys, thekeys, sizeof(thekeys));} + //DVORAK// + if (mode == 1){ + Key thekeys[4][11] = { + { + {'1','!','\0'}, + {'2','@','\0'}, + {'3','#','\0'}, + {'4','$','\0'}, + {'5','%','\0'}, + {'6','^','\0'}, + {'7','&','\0'}, + {'8','*','\0'}, + {'9','(','\0'}, + {'0',')','\0'}, + {'\0','\0','\0'} + }, + { + {'\'','"','\0'}, + {',','<','\0'}, + {'.','>','\0'}, + {'p','P','\0'}, + {'y','Y','\0'}, + {'f','F','\0'}, + {'g','G','\0'}, + {'c','C','\0'}, + {'r','R','\0'}, + {'l','L','\0'}, + {'/','?','\0'} + }, + { + {'a','A','m'}, + {'o','O','m'}, + {'e','E','m'}, + {'u','U','m'}, + {'i','I','m'}, + {'d','D','m'}, + {'h','H','m'}, + {'t','T','m'}, + {'n','N','m'}, + {'s','S','m'}, + {'-','_','m'} + }, - { - {';',':','\0'}, - {'q','Q','\0'}, - {'j','J','\0'}, - {'k','K','\0'}, - {'x','X','\0'}, - {'b','B','\0'}, - {'m','M','\0'}, - {'w','W','\0'}, - {'v','V','\0'}, - {'z','Z','\0'}, - {'\0','\0','\0'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys)); - } - //QWETRZ// - if (mode == 2) { - Key thekeys[4][11] = { - { - {'1','!','^','À'}, - {'2','"','²','à'}, - {'3','#','³','È'}, - {'4','$','«','è'}, - {'5','%','»','Ì'}, - {'6','&','„','ì'}, - {'7','/','”','Ò'}, - {'8','(','[','ò'}, - {'9',')',']','Ù'}, - {'0','=','§','ù'}, - {'ß','?','\'','Ý'} - }, - { - {'q','Q','@','Á'}, - {'w','W','\0','á'}, - {'e','E','€','É'}, - {'r','R','\0','é'}, - {'t','T','\0','Í'}, - {'z','Z','\0','í'}, - {'u','U','\0','Ó'}, - {'i','I','\0','ó'}, - {'o','O','\0','Ú'}, - {'p','P','\0','ú'}, - {'ü','Ü','\0','ý'} - }, - { - {'a','A','\0','Â'}, - {'s','S','\0','â'}, - {'d','D','\0','Ê'}, - {'f','F','\0','ê'}, - {'g','G','\0','Î'}, - {'h','H','\0','î'}, - {'j','J','\0','Ô'}, - {'k','K','\0','ô'}, - {'l','L','\0','Û'}, - {'ö','Ö','\0','û'}, - {'ä','Ä','\0','Ÿ'} - }, - { - {'<','>','|','Ã'}, - {'y','Y','\0','ã'}, - {'x','X','\0','Ñ'}, - {'c','C','ç','ñ'}, - {'v','V','©','Ï'}, - {'b','B','\0','ï'}, - {'n','N','\0','Õ'}, - {'m','M','µ','õ'}, - {',',';','\0','ÿ'}, - {'.',':','\0','\0'}, - {'-','_','\0','\0'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys)); - } - //AZERTY// - if (mode == 3) { - Key thekeys[4][11] = { - { - {'1','&','²','À'}, - {'2','~','³','é'}, - {'3','"','#','È'}, - {'4','`','«','ù'}, - {'5','(','[','Ì'}, - {'6','-','|','ì'}, - {'7','µ','»','è'}, - {'8','_','\'','ò'}, - {'9','+','^','ç'}, - {'0','=','@','à'}, - {'°',')',']','Ý'} - }, - { - {'a','A','Æ','Á'}, - {'z','Z','Œ','á'}, - {'e','E','€','É'}, - {'r','R','®','ë'}, - {'t','T','†','Í'}, - {'y','Y','ÿ','í'}, - {'u','U','Õ','Ó'}, - {'i','I','õ','Ò'}, - {'o','O','Ø','Ú'}, - {'p','P','ø','ú'}, - {'$','£','¤','ý'} - }, - { - {'q','Q','æ','Â'}, - {'s','S','œ','â'}, - {'d','D','\0','Ê'}, - {'f','F','ß','ê'}, - {'g','G','\0','Î'}, - {'h','H','\0','î'}, - {'j','J','\0','Ô'}, - {'k','K','\0','ô'}, - {'l','L','\0','Û'}, - {'m','M','\0','û'}, - {'*','%','¬','Ù'} - }, - { - {'<','>','\0','Ã'}, - {'w','W','\0','Ä'}, - {'x','X','\0','Ë'}, - {'c','C','©','Ç'}, - {'v','V','“','Ï'}, - {'b','B','”','ï'}, - {'n','N','\0','Ñ'}, - {'?',',','?','ñ'}, - {'.',';','.','ó'}, - {'/',':','/','ö'}, - {'§','!','!','Ö'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys)); - } - //QWERTY 2// - if (mode == 4) { - Key thekeys[4][11] = { - { - {'1','!','|','Á'}, - {'2','"','@','á'}, - {'3','·','#','À'}, - {'4','$','£','à'}, - {'5','%','~','É'}, - {'6','&','¬','é'}, - {'7','/','\'','È'}, - {'8','(','[','è'}, - {'9',')',']','Í'}, - {'0','=','¤','í'}, - {'¡','?','¿','Ï'} - }, - { - {'q','Q','\0','ï'}, - {'w','W','\0','Ó'}, - {'e','E','€','ó'}, - {'r','R','®','Ò'}, - {'t','T','†','ò'}, - {'y','Y','ÿ','Ú'}, - {'u','U','“','ú'}, - {'i','I','”','Ü'}, - {'o','O','Ø','ü'}, - {'p','P','ø','Ù'}, - {'+','*','\0','ù'} - }, - { - {'a','A','^','Ã'}, - {'s','S','²','ã'}, - {'d','D','³','Õ'}, - {'f','F','«','õ'}, - {'g','G','»','Ñ'}, - {'h','H','§','ñ'}, - {'j','J','µ','Ç'}, - {'k','K','¤','ç'}, - {'l','L','„','\0'}, - {'ñ','Ñ','+','\0'}, - {'ç','Ç','°','\0'} - }, - { - {'<','>','\0','Ä'}, - {'z','Z','\0','ä'}, - {'x','X','\0','Â'}, - {'c','C','©','â'}, - {'v','V','\0','å'}, - {'b','B','ß','Ë'}, - {'n','N','\0','ë'}, - {'m','M','\0','Ê'}, - {',',';','\0','ê'}, - {'.',':','\0','\0'}, - {'-','_','\0','\0'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys)); - } + { + {';',':','\0'}, + {'q','Q','\0'}, + {'j','J','\0'}, + {'k','K','\0'}, + {'x','X','\0'}, + {'b','B','\0'}, + {'m','M','\0'}, + {'w','W','\0'}, + {'v','V','\0'}, + {'z','Z','\0'}, + {'\0','\0','\0'} + } + }; + memcpy(keys, thekeys, sizeof(thekeys));} + //QWETRZ// + if (mode == 2){ + Key thekeys[4][11] = { + { + {'1','!','^','À'}, + {'2','"','²','à'}, + {'3','#','³','È'}, + {'4','$','«','è'}, + {'5','%','»','Ì'}, + {'6','&','„','ì'}, + {'7','/','”','Ò'}, + {'8','(','[','ò'}, + {'9',')',']','Ù'}, + {'0','=','§','ù'}, + {'ß','?','\'','Ý'} + }, + { + {'q','Q','@','Á'}, + {'w','W','\0','á'}, + {'e','E','€','É'}, + {'r','R','\0','é'}, + {'t','T','\0','Í'}, + {'z','Z','\0','í'}, + {'u','U','\0','Ó'}, + {'i','I','\0','ó'}, + {'o','O','\0','Ú'}, + {'p','P','\0','ú'}, + {'ü','Ü','\0','ý'} + }, + { + {'a','A','\0','Â'}, + {'s','S','\0','â'}, + {'d','D','\0','Ê'}, + {'f','F','\0','ê'}, + {'g','G','\0','Î'}, + {'h','H','\0','î'}, + {'j','J','\0','Ô'}, + {'k','K','\0','ô'}, + {'l','L','\0','Û'}, + {'ö','Ö','\0','û'}, + {'ä','Ä','\0','Ÿ'} + }, + { + {'<','>','|','Ã'}, + {'y','Y','\0','ã'}, + {'x','X','\0','Ñ'}, + {'c','C','ç','ñ'}, + {'v','V','©','Ï'}, + {'b','B','\0','ï'}, + {'n','N','\0','Õ'}, + {'m','M','µ','õ'}, + {',',';','\0','ÿ'}, + {'.',':','\0','\0'}, + {'-','_','\0','\0'} + } + }; + memcpy(keys, thekeys, sizeof(thekeys));} + //AZERTY// + if (mode == 3){ + Key thekeys[4][11] = { + { + {'1','&','²','À'}, + {'2','~','³','é'}, + {'3','"','#','È'}, + {'4','`','«','ù'}, + {'5','(','[','Ì'}, + {'6','-','|','ì'}, + {'7','µ','»','è'}, + {'8','_','\'','ò'}, + {'9','+','^','ç'}, + {'0','=','@','à'}, + {'°',')',']','Ý'} + }, + { + {'a','A','Æ','Á'}, + {'z','Z','Œ','á'}, + {'e','E','€','É'}, + {'r','R','®','ë'}, + {'t','T','†','Í'}, + {'y','Y','ÿ','í'}, + {'u','U','Õ','Ó'}, + {'i','I','õ','Ò'}, + {'o','O','Ø','Ú'}, + {'p','P','ø','ú'}, + {'$','£','¤','ý'} + }, + { + {'q','Q','æ','Â'}, + {'s','S','œ','â'}, + {'d','D','\0','Ê'}, + {'f','F','ß','ê'}, + {'g','G','\0','Î'}, + {'h','H','\0','î'}, + {'j','J','\0','Ô'}, + {'k','K','\0','ô'}, + {'l','L','\0','Û'}, + {'m','M','\0','û'}, + {'*','%','¬','Ù'} + }, + { + {'<','>','\0','Ã'}, + {'w','W','\0','Ä'}, + {'x','X','\0','Ë'}, + {'c','C','©','Ç'}, + {'v','V','“','Ï'}, + {'b','B','”','ï'}, + {'n','N','\0','Ñ'}, + {'?',',','?','ñ'}, + {'.',';','.','ó'}, + {'/',':','/','ö'}, + {'§','!','!','Ö'} + } + }; + memcpy(keys, thekeys, sizeof(thekeys));} + //QWERTY 2// + if (mode == 4){ + Key thekeys[4][11] = { + { + {'1','!','|','Á'}, + {'2','"','@','á'}, + {'3','·','#','À'}, + {'4','$','£','à'}, + {'5','%','~','É'}, + {'6','&','¬','é'}, + {'7','/','\'','È'}, + {'8','(','[','è'}, + {'9',')',']','Í'}, + {'0','=','¤','í'}, + {'¡','?','¿','Ï'} + }, + { + {'q','Q','\0','ï'}, + {'w','W','\0','Ó'}, + {'e','E','€','ó'}, + {'r','R','®','Ò'}, + {'t','T','†','ò'}, + {'y','Y','ÿ','Ú'}, + {'u','U','“','ú'}, + {'i','I','”','Ü'}, + {'o','O','Ø','ü'}, + {'p','P','ø','Ù'}, + {'+','*','\0','ù'} + }, + { + {'a','A','^','Ã'}, + {'s','S','²','ã'}, + {'d','D','³','Õ'}, + {'f','F','«','õ'}, + {'g','G','»','Ñ'}, + {'h','H','§','ñ'}, + {'j','J','µ','Ç'}, + {'k','K','¤','ç'}, + {'l','L','„','\0'}, + {'ñ','Ñ','+','\0'}, + {'ç','Ç','°','\0'} + }, + { + {'<','>','\0','Ä'}, + {'z','Z','\0','ä'}, + {'x','X','\0','Â'}, + {'c','C','©','â'}, + {'v','V','\0','å'}, + {'b','B','ß','Ë'}, + {'n','N','\0','ë'}, + {'m','M','\0','Ê'}, + {',',';','\0','ê'}, + {'.',':','\0','\0'}, + {'-','_','\0','\0'} + } + }; + memcpy(keys, thekeys, sizeof(thekeys));} + + keyTextbox = new GuiImageData(keyboard_textbox_png); + keyTextboxImg = new GuiImage(keyTextbox); + keyTextboxImg->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + keyTextboxImg->SetPosition(0, 40);//(0,0); + this->Append(keyTextboxImg); - keyTextbox = new GuiImageData(keyboard_textbox_png); - keyTextboxImg = new GuiImage(keyTextbox); - keyTextboxImg->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - keyTextboxImg->SetPosition(0, 40);//(0,0); - this->Append(keyTextboxImg); + kbText = new GuiText(kbtextstr, 20, (GXColor){0, 0, 0, 0xff}); + kbText->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + kbText->SetPosition(0, 53);//(0, 13); + this->Append(kbText); - kbText = new GuiText(kbtextstr, 20, (GXColor) {0, 0, 0, 0xff}); - kbText->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - kbText->SetPosition(0, 53);//(0, 13); - this->Append(kbText); + key = new GuiImageData(keyboard_key_png); + keyOver = new GuiImageData(keyboard_key_over_png); + keyMedium = new GuiImageData(keyboard_mediumkey_over_png); + keyMediumOver = new GuiImageData(keyboard_mediumkey_over_png); + keyLarge = new GuiImageData(keyboard_largekey_over_png); + keyLargeOver = new GuiImageData(keyboard_largekey_over_png); - key = new GuiImageData(keyboard_key_png); - keyOver = new GuiImageData(keyboard_key_over_png); - keyMedium = new GuiImageData(keyboard_mediumkey_over_png); - keyMediumOver = new GuiImageData(keyboard_mediumkey_over_png); - keyLarge = new GuiImageData(keyboard_largekey_over_png); - keyLargeOver = new GuiImageData(keyboard_largekey_over_png); - - keySoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - keySoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigB = new GuiTrigger; - trigB->SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + keySoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + keySoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigB = new GuiTrigger; + trigB->SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); int eurocheck = 0; - if (mode > 1) { - eurocheck = -20; + if(mode > 1) { + eurocheck = -20; } - keyBackImg = new GuiImage(keyMedium); - keyBackOverImg = new GuiImage(keyMediumOver); - if (mode == 3) { - keyBackText = new GuiText("Retour", 20, (GXColor) { 0, 0, 0, 0xff}); - } else { - keyBackText = new GuiText("Back", 20, (GXColor) {0, 0, 0, 0xff}); - } - //GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow); + keyBackImg = new GuiImage(keyMedium); + keyBackOverImg = new GuiImage(keyMediumOver); + if (mode == 3){ + keyBackText = new GuiText("Retour", 20, (GXColor){0, 0, 0, 0xff});} + else { + keyBackText = new GuiText("Back", 20, (GXColor){0, 0, 0, 0xff});} + //GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow); - //keyBack = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - keyBack = new GuiButton(keyBackImg, keyBackOverImg, 0, 3, 11*42+40+eurocheck, 0*42+120, trigA, keySoundOver, keySoundClick,1); - //keyBack->SetImage(keyBackImg); - //keyBack->SetImageOver(keyBackOverImg); - keyBack->SetLabel(keyBackText); - //keyBack->SetSoundOver(keySoundOver); - //keyBack->SetSoundClick(keySoundClick); - //keyBack->SetTrigger(trigA); - keyBack->SetTrigger(trigB); - if (mode > 1) { - keyBack->SetPosition(11*42+40+eurocheck, 0*42+120); - } else { - keyBack->SetPosition(10*42+40+eurocheck, 0*42+120); - }//(10*42+40, 0*42+80); - //keyBack->SetEffectGrow(); - this->Append(keyBack); + //keyBack = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + keyBack = new GuiButton(keyBackImg, keyBackOverImg, 0, 3, 11*42+40+eurocheck, 0*42+120, trigA, keySoundOver, keySoundClick,1); + //keyBack->SetImage(keyBackImg); + //keyBack->SetImageOver(keyBackOverImg); + keyBack->SetLabel(keyBackText); + //keyBack->SetSoundOver(keySoundOver); + //keyBack->SetSoundClick(keySoundClick); + //keyBack->SetTrigger(trigA); + keyBack->SetTrigger(trigB); + if (mode > 1){ + keyBack->SetPosition(11*42+40+eurocheck, 0*42+120);} + else{ + keyBack->SetPosition(10*42+40+eurocheck, 0*42+120);}//(10*42+40, 0*42+80); + //keyBack->SetEffectGrow(); + this->Append(keyBack); - keyClearImg = new GuiImage(keyMedium); - keyClearOverImg = new GuiImage(keyMediumOver); - if (mode == 3) { - keyClearText = new GuiText("Effacer", 20, (GXColor) {0, 0, 0, 0xff}); - } else { - keyClearText = new GuiText("Clear", 20, (GXColor) {0, 0, 0, 0xff}); - } - keyClear = new GuiButton(keyClearImg, keyClearOverImg, 0, 3, (10*42+40)+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keyClear = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyClear->SetImage(keyClearImg); - //keyClear->SetImageOver(keyClearOverImg); - keyClear->SetLabel(keyClearText); - //keyClear->SetSoundOver(keySoundOver); - //keyClear->SetSoundClick(keySoundClick); - //keyClear->SetTrigger(trigA); - //keyClear->SetPosition((10*42+40)+eurocheck, 4*42+120);//(10*42+40, 0*42+80); - //keyClear->SetEffectGrow(); - this->Append(keyClear); + keyClearImg = new GuiImage(keyMedium); + keyClearOverImg = new GuiImage(keyMediumOver); + if (mode == 3){ + keyClearText = new GuiText("Effacer", 20, (GXColor){0, 0, 0, 0xff});} + else { + keyClearText = new GuiText("Clear", 20, (GXColor){0, 0, 0, 0xff});} + keyClear = new GuiButton(keyClearImg, keyClearOverImg, 0, 3, (10*42+40)+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); + //keyClear = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyClear->SetImage(keyClearImg); + //keyClear->SetImageOver(keyClearOverImg); + keyClear->SetLabel(keyClearText); + //keyClear->SetSoundOver(keySoundOver); + //keyClear->SetSoundClick(keySoundClick); + //keyClear->SetTrigger(trigA); + //keyClear->SetPosition((10*42+40)+eurocheck, 4*42+120);//(10*42+40, 0*42+80); + //keyClear->SetEffectGrow(); + this->Append(keyClear); - keyAltImg = new GuiImage(keyMedium); - keyAltOverImg = new GuiImage(keyMediumOver); - keyAltText = new GuiText("Alt Gr", 20, (GXColor) {0, 0, 0, 0xff}); - keyAlt = new GuiButton(keyAltImg, keyAltOverImg, 0, 3, 84+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keyAlt = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyAlt->SetImage(keyAltImg); - //keyAlt->SetImageOver(keyAltOverImg); - keyAlt->SetLabel(keyAltText); - //keyAlt->SetSoundOver(keySoundOver); - //keyAlt->SetSoundClick(keySoundClick); - //keyAlt->SetTrigger(trigA); - //keyAlt->SetPosition(84+eurocheck, 4*42+120);//(10*42+40, 4*42+120); - //keyAlt->SetEffectGrow(); - if (mode > 1) { - this->Append(keyAlt); - } + keyAltImg = new GuiImage(keyMedium); + keyAltOverImg = new GuiImage(keyMediumOver); + keyAltText = new GuiText("Alt Gr", 20, (GXColor){0, 0, 0, 0xff}); + keyAlt = new GuiButton(keyAltImg, keyAltOverImg, 0, 3, 84+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); + //keyAlt = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyAlt->SetImage(keyAltImg); + //keyAlt->SetImageOver(keyAltOverImg); + keyAlt->SetLabel(keyAltText); + //keyAlt->SetSoundOver(keySoundOver); + //keyAlt->SetSoundClick(keySoundClick); + //keyAlt->SetTrigger(trigA); + //keyAlt->SetPosition(84+eurocheck, 4*42+120);//(10*42+40, 4*42+120); + //keyAlt->SetEffectGrow(); + if (mode > 1){this->Append(keyAlt);} - keyAlt2Img = new GuiImage(keyMedium); - keyAlt2OverImg = new GuiImage(keyMediumOver); - keyAlt2Text = new GuiText("Accent", 20, (GXColor) {0, 0, 0, 0xff}); - keyAlt2 = new GuiButton(keyAlt2Img, keyAlt2OverImg, 0, 3, (8*42+40)+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keyAlt2 = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyAlt2->SetImage(keyAlt2Img); - //keyAlt2->SetImageOver(keyAlt2OverImg); - keyAlt2->SetLabel(keyAlt2Text); - //keyAlt2->SetSoundOver(keySoundOver); - //keyAlt2->SetSoundClick(keySoundClick); - //keyAlt2->SetTrigger(trigA); - //keyAlt2->SetPosition((8*42+40)+eurocheck, 4*42+120);//(10*42+40, 4*42+120); - //keyAlt2->SetEffectGrow(); - if (mode > 1) { - this->Append(keyAlt2); - } + keyAlt2Img = new GuiImage(keyMedium); + keyAlt2OverImg = new GuiImage(keyMediumOver); + keyAlt2Text = new GuiText("Accent", 20, (GXColor){0, 0, 0, 0xff}); + keyAlt2 = new GuiButton(keyAlt2Img, keyAlt2OverImg, 0, 3, (8*42+40)+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); + //keyAlt2 = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyAlt2->SetImage(keyAlt2Img); + //keyAlt2->SetImageOver(keyAlt2OverImg); + keyAlt2->SetLabel(keyAlt2Text); + //keyAlt2->SetSoundOver(keySoundOver); + //keyAlt2->SetSoundClick(keySoundClick); + //keyAlt2->SetTrigger(trigA); + //keyAlt2->SetPosition((8*42+40)+eurocheck, 4*42+120);//(10*42+40, 4*42+120); + //keyAlt2->SetEffectGrow(); + if (mode > 1){this->Append(keyAlt2);} - keyCapsImg = new GuiImage(keyMedium); - keyCapsOverImg = new GuiImage(keyMediumOver); - keyCapsText = new GuiText("Caps", 20, (GXColor) {0, 0, 0, 0xff}); - keyCaps = new GuiButton(keyCapsImg, keyCapsOverImg, 0, 3, 0+eurocheck, 2*42+120, trigA, keySoundOver, keySoundClick,1); - //keyCaps = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyCaps->SetImage(keyCapsImg); - //keyCaps->SetImageOver(keyCapsOverImg); - keyCaps->SetLabel(keyCapsText); - //keyCaps->SetSoundOver(keySoundOver); - //keyCaps->SetSoundClick(keySoundClick); - //keyCaps->SetTrigger(trigA); - //keyCaps->SetPosition(0+eurocheck, 2*42+120);//(0, 2*42+80); - //keyCaps->SetEffectGrow(); - this->Append(keyCaps); + keyCapsImg = new GuiImage(keyMedium); + keyCapsOverImg = new GuiImage(keyMediumOver); + keyCapsText = new GuiText("Caps", 20, (GXColor){0, 0, 0, 0xff}); + keyCaps = new GuiButton(keyCapsImg, keyCapsOverImg, 0, 3, 0+eurocheck, 2*42+120, trigA, keySoundOver, keySoundClick,1); + //keyCaps = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyCaps->SetImage(keyCapsImg); + //keyCaps->SetImageOver(keyCapsOverImg); + keyCaps->SetLabel(keyCapsText); + //keyCaps->SetSoundOver(keySoundOver); + //keyCaps->SetSoundClick(keySoundClick); + //keyCaps->SetTrigger(trigA); + //keyCaps->SetPosition(0+eurocheck, 2*42+120);//(0, 2*42+80); + //keyCaps->SetEffectGrow(); + this->Append(keyCaps); - keyShiftImg = new GuiImage(keyMedium); - keyShiftOverImg = new GuiImage(keyMediumOver); - keyShiftText = new GuiText("Shift", 20, (GXColor) {0, 0, 0, 0xff}); - keyShift = new GuiButton(keyShiftImg, keyShiftOverImg, 0, 3, 21+eurocheck, 3*42+120, trigA, keySoundOver, keySoundClick,1); - //keyShift = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyShift->SetImage(keyShiftImg); - //keyShift->SetImageOver(keyShiftOverImg); - keyShift->SetLabel(keyShiftText); - //keyShift->SetSoundOver(keySoundOver); - //keyShift->SetSoundClick(keySoundClick); - //keyShift->SetTrigger(trigA); - //keyShift->SetPosition(21+eurocheck, 3*42+120);//(21, 3*42+80); - //keyShift->SetEffectGrow(); - this->Append(keyShift); + keyShiftImg = new GuiImage(keyMedium); + keyShiftOverImg = new GuiImage(keyMediumOver); + keyShiftText = new GuiText("Shift", 20, (GXColor){0, 0, 0, 0xff}); + keyShift = new GuiButton(keyShiftImg, keyShiftOverImg, 0, 3, 21+eurocheck, 3*42+120, trigA, keySoundOver, keySoundClick,1); + //keyShift = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyShift->SetImage(keyShiftImg); + //keyShift->SetImageOver(keyShiftOverImg); + keyShift->SetLabel(keyShiftText); + //keyShift->SetSoundOver(keySoundOver); + //keyShift->SetSoundClick(keySoundClick); + //keyShift->SetTrigger(trigA); + //keyShift->SetPosition(21+eurocheck, 3*42+120);//(21, 3*42+80); + //keyShift->SetEffectGrow(); + this->Append(keyShift); - keySpaceImg = new GuiImage(keyLarge); - keySpaceOverImg = new GuiImage(keyLargeOver); - keySpace = new GuiButton(keySpaceImg, keySpaceOverImg, 2, 3, 0+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keySpace = new GuiButton(keyLarge->GetWidth(), keyLarge->GetHeight()); - //keySpace->SetImage(keySpaceImg); - //keySpace->SetImageOver(keySpaceOverImg); - //keySpace->SetSoundOver(keySoundOver); - //keySpace->SetSoundClick(keySoundClick); - //keySpace->SetTrigger(trigA); - //keySpace->SetPosition(0+eurocheck, 4*42+120);//(0, 4*42+80); - //keySpace->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - //keySpace->SetEffectGrow(); - this->Append(keySpace); + keySpaceImg = new GuiImage(keyLarge); + keySpaceOverImg = new GuiImage(keyLargeOver); + keySpace = new GuiButton(keySpaceImg, keySpaceOverImg, 2, 3, 0+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); + //keySpace = new GuiButton(keyLarge->GetWidth(), keyLarge->GetHeight()); + //keySpace->SetImage(keySpaceImg); + //keySpace->SetImageOver(keySpaceOverImg); + //keySpace->SetSoundOver(keySoundOver); + //keySpace->SetSoundClick(keySoundClick); + //keySpace->SetTrigger(trigA); + //keySpace->SetPosition(0+eurocheck, 4*42+120);//(0, 4*42+80); + //keySpace->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + //keySpace->SetEffectGrow(); + this->Append(keySpace); - char txt[2] = { 0, 0 }; - for (int i=0; i<4; i++) { - for (int j=0; j<11; j++) { - if (keys[i][j].ch != '\0') { - keyImg[i][j] = new GuiImage(key); - keyImgOver[i][j] = new GuiImage(keyOver); - txt[0] = keys[i][j].ch; - keyTxt[i][j] = new GuiText(txt, 20, (GXColor) {0, 0, 0, 0xff}); - keyTxt[i][j]->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - keyTxt[i][j]->SetPosition(0, -10); - keyBtn[i][j] = new GuiButton(keyImg[i][j], keyImgOver[i][j], 0, 3, (j*42+21*i+40)+eurocheck, i*42+120, trigA, keySoundOver, keySoundClick,1); - //keyBtn[i][j] = new GuiButton(key->GetWidth(), key->GetHeight()); - //keyBtn[i][j]->SetImage(keyImg[i][j]); - //keyBtn[i][j]->SetImageOver(keyImgOver[i][j]); - //keyBtn[i][j]->SetSoundOver(keySoundOver); - //keyBtn[i][j]->SetSoundClick(keySoundClick); - //keyBtn[i][j]->SetTrigger(trigA); - keyBtn[i][j]->SetLabel(keyTxt[i][j]); - //keyBtn[i][j]->SetPosition((j*42+21*i+40)+eurocheck, i*42+120);//SetPosition(j*42+21*i+40, i*42+80); - //keyBtn[i][j]->SetEffectGrow(); - this->Append(keyBtn[i][j]); - } - } - } + char txt[2] = { 0, 0 }; + for(int i=0; i<4; i++) + { + for(int j=0; j<11; j++) + { + if(keys[i][j].ch != '\0') + { + keyImg[i][j] = new GuiImage(key); + keyImgOver[i][j] = new GuiImage(keyOver); + txt[0] = keys[i][j].ch; + keyTxt[i][j] = new GuiText(txt, 20, (GXColor){0, 0, 0, 0xff}); + keyTxt[i][j]->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + keyTxt[i][j]->SetPosition(0, -10); + keyBtn[i][j] = new GuiButton(keyImg[i][j], keyImgOver[i][j], 0, 3, (j*42+21*i+40)+eurocheck, i*42+120, trigA, keySoundOver, keySoundClick,1); + //keyBtn[i][j] = new GuiButton(key->GetWidth(), key->GetHeight()); + //keyBtn[i][j]->SetImage(keyImg[i][j]); + //keyBtn[i][j]->SetImageOver(keyImgOver[i][j]); + //keyBtn[i][j]->SetSoundOver(keySoundOver); + //keyBtn[i][j]->SetSoundClick(keySoundClick); + //keyBtn[i][j]->SetTrigger(trigA); + keyBtn[i][j]->SetLabel(keyTxt[i][j]); + //keyBtn[i][j]->SetPosition((j*42+21*i+40)+eurocheck, i*42+120);//SetPosition(j*42+21*i+40, i*42+80); + //keyBtn[i][j]->SetEffectGrow(); + this->Append(keyBtn[i][j]); + } + } + } } /** * Destructor for the GuiKeyboard class. */ -GuiKeyboard::~GuiKeyboard() { - delete kbText; - delete keyTextbox; - delete keyTextboxImg; - delete keyCapsText; - delete keyCapsImg; - delete keyCapsOverImg; - delete keyCaps; - delete keyShiftText; - delete keyShiftImg; - delete keyShiftOverImg; - delete keyShift; - if (keyAlt) { - delete keyAlt; - } - if (keyAlt2) { - delete keyAlt2; - } - delete keyBackText; - delete keyBackImg; - delete keyBackOverImg; - delete keyBack; - delete keySpaceImg; - delete keySpaceOverImg; - delete keySpace; - delete key; - delete keyOver; - delete keyMedium; - delete keyMediumOver; - delete keyLarge; - delete keyLargeOver; - delete keySoundOver; - delete keySoundClick; - delete trigA; - delete trigB; +GuiKeyboard::~GuiKeyboard() +{ + delete kbText; + delete keyTextbox; + delete keyTextboxImg; + delete keyCapsText; + delete keyCapsImg; + delete keyCapsOverImg; + delete keyCaps; + delete keyShiftText; + delete keyShiftImg; + delete keyShiftOverImg; + delete keyShift; + if (keyAlt) + {delete keyAlt;} + if (keyAlt2) + {delete keyAlt2;} + delete keyBackText; + delete keyBackImg; + delete keyBackOverImg; + delete keyBack; + delete keySpaceImg; + delete keySpaceOverImg; + delete keySpace; + delete key; + delete keyOver; + delete keyMedium; + delete keyMediumOver; + delete keyLarge; + delete keyLargeOver; + delete keySoundOver; + delete keySoundClick; + delete trigA; + delete trigB; - for (int i=0; i<4; i++) { - for (int j=0; j<11; j++) { - if (keys[i][j].ch != '\0') { - delete keyImg[i][j]; - delete keyImgOver[i][j]; - delete keyTxt[i][j]; - delete keyBtn[i][j]; - } - } - } + for(int i=0; i<4; i++) + { + for(int j=0; j<11; j++) + { + if(keys[i][j].ch != '\0') + { + delete keyImg[i][j]; + delete keyImgOver[i][j]; + delete keyTxt[i][j]; + delete keyBtn[i][j]; + } + } + } } -void GuiKeyboard::Update(GuiTrigger * t) { - LOCK(this); - if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) - return; +void GuiKeyboard::Update(GuiTrigger * t) +{ + LOCK(this); + if(_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) + return; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->Update(t); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->Update(t); } + catch (const std::exception& e) { } + } - bool changedShiftKey = false; - - if (keySpace->GetState() == STATE_CLICKED) { - if (strlen(kbtextstr) < kbtextmaxlen-1) { // -1 --> kbtextmaxlen means with terminating '\0' - kbtextstr[strlen(kbtextstr)] = ' '; - kbText->SetText(kbtextstr); - } - keySpace->SetState(STATE_SELECTED, t->chan); - } else if (keyBack->GetState() == STATE_CLICKED) { - if (strlen(kbtextstr) >(m)) { - kbtextstr[strlen(kbtextstr)-1] = 0; - kbText->SetText(kbtextstr); - } - keyBack->SetState(STATE_SELECTED, t->chan); - } else if (keyClear->GetState() == STATE_CLICKED) { - while (strlen(kbtextstr) >(m)) { - kbtextstr[strlen(kbtextstr)-1] = 0; - kbText->SetText(kbtextstr); - } - keyClear->SetState(STATE_SELECTED, t->chan); - } else if (keyShift->GetState() == STATE_CLICKED) { - changedShiftKey =true; - shift ^= 1; - if (alt) alt ^= 1; - if (alt2) alt2 ^= 1; - keyShift->SetState(STATE_SELECTED, t->chan); - } else if (keyAlt->GetState() == STATE_CLICKED) { - changedShiftKey =true; - alt ^= 1; - if (shift) shift ^= 1; - if (alt2) alt2 ^= 1; - keyAlt->SetState(STATE_SELECTED, t->chan); - } else if (keyAlt2->GetState() == STATE_CLICKED) { - changedShiftKey =true; - alt2 ^= 1; - if (shift) shift ^= 1; - if (alt) alt ^= 1; - keyAlt2->SetState(STATE_SELECTED, t->chan); - } else if (keyCaps->GetState() == STATE_CLICKED) { - changedShiftKey =true; - caps ^= 1; - keyCaps->SetState(STATE_SELECTED, t->chan); - } + bool changedShiftKey = false; + + if(keySpace->GetState() == STATE_CLICKED) + { + if(strlen(kbtextstr) < kbtextmaxlen-1) // -1 --> kbtextmaxlen means with terminating '\0' + { + kbtextstr[strlen(kbtextstr)] = ' '; + kbText->SetText(kbtextstr); + } + keySpace->SetState(STATE_SELECTED, t->chan); + } + else if(keyBack->GetState() == STATE_CLICKED) + { + if (strlen(kbtextstr) >(m)){ + kbtextstr[strlen(kbtextstr)-1] = 0; + kbText->SetText(kbtextstr); + } + keyBack->SetState(STATE_SELECTED, t->chan); + } + else if(keyClear->GetState() == STATE_CLICKED) + { + while (strlen(kbtextstr) >(m)){ + kbtextstr[strlen(kbtextstr)-1] = 0; + kbText->SetText(kbtextstr); + } + keyClear->SetState(STATE_SELECTED, t->chan); + } + else if(keyShift->GetState() == STATE_CLICKED) + { + changedShiftKey =true; + shift ^= 1; + if(alt) alt ^= 1; + if(alt2) alt2 ^= 1; + keyShift->SetState(STATE_SELECTED, t->chan); + } + else if(keyAlt->GetState() == STATE_CLICKED) + { + changedShiftKey =true; + alt ^= 1; + if(shift) shift ^= 1; + if(alt2) alt2 ^= 1; + keyAlt->SetState(STATE_SELECTED, t->chan); + } + else if(keyAlt2->GetState() == STATE_CLICKED) + { + changedShiftKey =true; + alt2 ^= 1; + if(shift) shift ^= 1; + if(alt) alt ^= 1; + keyAlt2->SetState(STATE_SELECTED, t->chan); + } + else if(keyCaps->GetState() == STATE_CLICKED) + { + changedShiftKey =true; + caps ^= 1; + keyCaps->SetState(STATE_SELECTED, t->chan); + } - bool update = false; + bool update = false; - char txt[2] = { 0, 0 }; + char txt[2] = { 0, 0 }; + + do + { + update = false; + for(int i=0; i<4; i++) + { + for(int j=0; j<11; j++) + { + if(keys[i][j].ch != '\0') + { + if(shift || caps) + txt[0] = keys[i][j].chShift; + else if(alt) + txt[0] = keys[i][j].chalt; + else if(alt2) + txt[0] = keys[i][j].chalt2; + else + txt[0] = keys[i][j].ch; - do { - update = false; - for (int i=0; i<4; i++) { - for (int j=0; j<11; j++) { - if (keys[i][j].ch != '\0') { - if (shift || caps) - txt[0] = keys[i][j].chShift; - else if (alt) - txt[0] = keys[i][j].chalt; - else if (alt2) - txt[0] = keys[i][j].chalt2; - else - txt[0] = keys[i][j].ch; + if(changedShiftKey) // change text only if needed + keyTxt[i][j]->SetText(txt); - if (changedShiftKey) // change text only if needed - keyTxt[i][j]->SetText(txt); + if(keyBtn[i][j]->GetState() == STATE_CLICKED) + { + if(strlen(kbtextstr) < kbtextmaxlen-1) // -1 --> kbtextmaxlen means with term. '\0' + { + kbtextstr[strlen(kbtextstr)] = txt[0]; + kbText->SetText(kbtextstr); + } + keyBtn[i][j]->SetState(STATE_SELECTED, t->chan); + + if(shift || alt || alt2) + { + if(shift) shift ^= 1; + if(alt) alt ^= 1; + if(alt2) alt2 ^= 1; + update = true; + changedShiftKey = true; + } + } + } + } + } + } while(update); - if (keyBtn[i][j]->GetState() == STATE_CLICKED) { - if (strlen(kbtextstr) < kbtextmaxlen-1) { // -1 --> kbtextmaxlen means with term. '\0' - kbtextstr[strlen(kbtextstr)] = txt[0]; - kbText->SetText(kbtextstr); - } - keyBtn[i][j]->SetState(STATE_SELECTED, t->chan); + kbText->SetPosition(0, 53); - if (shift || alt || alt2) { - if (shift) shift ^= 1; - if (alt) alt ^= 1; - if (alt2) alt2 ^= 1; - update = true; - changedShiftKey = true; - } - } - } - } - } - } while (update); + this->ToggleFocus(t); - kbText->SetPosition(0, 53); - - this->ToggleFocus(t); - - if (focus) { // only send actions to this window if it's in focus - // pad/joystick navigation - if (t->Right()) - this->MoveSelectionHor(1); - else if (t->Left()) - this->MoveSelectionHor(-1); - else if (t->Down()) - this->MoveSelectionVert(1); - else if (t->Up()) - this->MoveSelectionVert(-1); - } + if(focus) // only send actions to this window if it's in focus + { + // pad/joystick navigation + if(t->Right()) + this->MoveSelectionHor(1); + else if(t->Left()) + this->MoveSelectionHor(-1); + else if(t->Down()) + this->MoveSelectionVert(1); + else if(t->Up()) + this->MoveSelectionVert(-1); + } } diff --git a/source/libwiigui/gui_numpad.cpp b/source/libwiigui/gui_numpad.cpp index f1d51631..4970cbfc 100644 --- a/source/libwiigui/gui_numpad.cpp +++ b/source/libwiigui/gui_numpad.cpp @@ -16,164 +16,179 @@ /** * Constructor for the GuiNumpad class. */ - -#define SAFEFREE(p) if(p){free(p);p=NULL;} - -GuiNumpad::GuiNumpad(char * t, u32 max) { - width = 400; - height = 370; - selectable = true; - focus = 0; // allow focus - alignmentHor = ALIGN_CENTRE; - alignmentVert = ALIGN_MIDDLE; - kbtextmaxlen = max>sizeof(kbtextstr) ? sizeof(kbtextstr) : max; // limit max up to sizeof(kbtextstr) + + #define SAFEFREE(p) if(p){free(p);p=NULL;} + +GuiNumpad::GuiNumpad(char * t, u32 max) +{ + width = 400; + height = 370; + selectable = true; + focus = 0; // allow focus + alignmentHor = ALIGN_CENTRE; + alignmentVert = ALIGN_MIDDLE; + kbtextmaxlen = max>sizeof(kbtextstr) ? sizeof(kbtextstr) : max; // limit max up to sizeof(kbtextstr) // strlcpy(kbtextstr, t, kbtextmaxlen); - strncpy(kbtextstr, t, kbtextmaxlen); // strncpy is needed to fill the rest with \0 - kbtextstr[sizeof(kbtextstr)-1] = 0; // terminate with \0 + strncpy(kbtextstr, t, kbtextmaxlen); // strncpy is needed to fill the rest with \0 + kbtextstr[sizeof(kbtextstr)-1] = 0; // terminate with \0 - char thekeys[11] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '\0', '0' }; - memcpy(keys, thekeys, sizeof(thekeys)); + char thekeys[11] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '\0', '0' }; + memcpy(keys, thekeys, sizeof(thekeys)); + + keyTextbox = new GuiImageData(keyboard_textbox_png); + keyTextboxImg = new GuiImage(keyTextbox); + keyTextboxImg->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + keyTextboxImg->SetPosition(0, 40);//(0,0); + this->Append(keyTextboxImg); - keyTextbox = new GuiImageData(keyboard_textbox_png); - keyTextboxImg = new GuiImage(keyTextbox); - keyTextboxImg->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - keyTextboxImg->SetPosition(0, 40);//(0,0); - this->Append(keyTextboxImg); + kbText = new GuiText(kbtextstr, 20, (GXColor){0, 0, 0, 0xff}); + kbText->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + kbText->SetPosition(0, 53);//(0, 13); + kbText->SetPassChar('*'); + this->Append(kbText); - kbText = new GuiText(kbtextstr, 20, (GXColor) {0, 0, 0, 0xff}); - kbText->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - kbText->SetPosition(0, 53);//(0, 13); - kbText->SetPassChar('*'); - this->Append(kbText); + keyMedium = new GuiImageData(keyboard_mediumkey_over_png); + keyMediumOver = new GuiImageData(keyboard_mediumkey_over_png); - keyMedium = new GuiImageData(keyboard_mediumkey_over_png); - keyMediumOver = new GuiImageData(keyboard_mediumkey_over_png); + keySoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + keySoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigB = new GuiTrigger; + trigB->SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - keySoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - keySoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigB = new GuiTrigger; - trigB->SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + keyBackImg = new GuiImage(keyMedium); + keyBackOverImg = new GuiImage(keyMediumOver); + keyBackText = new GuiText("Back", 20, (GXColor){0, 0, 0, 0xff}); - keyBackImg = new GuiImage(keyMedium); - keyBackOverImg = new GuiImage(keyMediumOver); - keyBackText = new GuiText("Back", 20, (GXColor) {0, 0, 0, 0xff}); + keyBack = new GuiButton(keyBackImg, keyBackOverImg, ALIGN_CENTRE, ALIGN_MIDDLE, 90, 80, trigA, keySoundOver, keySoundClick,1); + keyBack->SetLabel(keyBackText); + keyBack->SetTrigger(trigB); + this->Append(keyBack); - keyBack = new GuiButton(keyBackImg, keyBackOverImg, ALIGN_CENTRE, ALIGN_MIDDLE, 90, 80, trigA, keySoundOver, keySoundClick,1); - keyBack->SetLabel(keyBackText); - keyBack->SetTrigger(trigB); - this->Append(keyBack); + keyClearImg = new GuiImage(keyMedium); + keyClearOverImg = new GuiImage(keyMediumOver); + keyClearText = new GuiText("Clear", 20, (GXColor){0, 0, 0, 0xff}); + keyClear = new GuiButton(keyClearImg, keyClearOverImg, ALIGN_CENTRE, ALIGN_MIDDLE, -90, 80, trigA, keySoundOver, keySoundClick,1); + keyClear->SetLabel(keyClearText); + this->Append(keyClear); - keyClearImg = new GuiImage(keyMedium); - keyClearOverImg = new GuiImage(keyMediumOver); - keyClearText = new GuiText("Clear", 20, (GXColor) {0, 0, 0, 0xff}); - keyClear = new GuiButton(keyClearImg, keyClearOverImg, ALIGN_CENTRE, ALIGN_MIDDLE, -90, 80, trigA, keySoundOver, keySoundClick,1); - keyClear->SetLabel(keyClearText); - this->Append(keyClear); + char txt[2] = { 0, 0 }; + for(int i=0; i<11; i++) + { + if (keys[i] != '\0') + { + int col = i % 3; + int row = i / 3; + + keyImg[i] = new GuiImage(keyMedium); + keyImgOver[i] = new GuiImage(keyMediumOver); + txt[0] = keys[i]; + keyTxt[i] = new GuiText(txt, 20, (GXColor){0, 0, 0, 0xff}); + keyTxt[i]->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + keyTxt[i]->SetPosition(0, -10); + keyBtn[i]= new GuiButton(keyImg[i], keyImgOver[i], ALIGN_CENTRE, ALIGN_MIDDLE, -90 + 90 * col, -70 + 50 * row, trigA, keySoundOver, keySoundClick, 1); + keyBtn[i]->SetLabel(keyTxt[i]); - char txt[2] = { 0, 0 }; - for (int i=0; i<11; i++) { - if (keys[i] != '\0') { - int col = i % 3; - int row = i / 3; - - keyImg[i] = new GuiImage(keyMedium); - keyImgOver[i] = new GuiImage(keyMediumOver); - txt[0] = keys[i]; - keyTxt[i] = new GuiText(txt, 20, (GXColor) {0, 0, 0, 0xff}); - keyTxt[i]->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - keyTxt[i]->SetPosition(0, -10); - keyBtn[i]= new GuiButton(keyImg[i], keyImgOver[i], ALIGN_CENTRE, ALIGN_MIDDLE, -90 + 90 * col, -70 + 50 * row, trigA, keySoundOver, keySoundClick, 1); - keyBtn[i]->SetLabel(keyTxt[i]); - - this->Append(keyBtn[i]); - } - } + this->Append(keyBtn[i]); + } + } } /** * Destructor for the GuiKeyboard class. */ -GuiNumpad::~GuiNumpad() { - SAFEFREE(kbText) - SAFEFREE(keyTextbox) - SAFEFREE(keyTextboxImg) - SAFEFREE(keyBackText) - SAFEFREE(keyBackImg) - SAFEFREE(keyBackOverImg) - SAFEFREE(keyBack) - SAFEFREE(keyClear) - SAFEFREE(keyClearImg) - SAFEFREE(keyClearOverImg) - SAFEFREE(keyClearText) - SAFEFREE(keyMedium) - SAFEFREE(keyMediumOver) - SAFEFREE(keySoundOver) - SAFEFREE(keySoundClick) - SAFEFREE(trigA) - SAFEFREE(trigB) +GuiNumpad::~GuiNumpad() +{ + SAFEFREE(kbText) + SAFEFREE(keyTextbox) + SAFEFREE(keyTextboxImg) + SAFEFREE(keyBackText) + SAFEFREE(keyBackImg) + SAFEFREE(keyBackOverImg) + SAFEFREE(keyBack) + SAFEFREE(keyClear) + SAFEFREE(keyClearImg) + SAFEFREE(keyClearOverImg) + SAFEFREE(keyClearText) + SAFEFREE(keyMedium) + SAFEFREE(keyMediumOver) + SAFEFREE(keySoundOver) + SAFEFREE(keySoundClick) + SAFEFREE(trigA) + SAFEFREE(trigB) - for (int i=0; i<11; i++) { - if (keys[i] != '\0') { - SAFEFREE(keyImg[i]) - SAFEFREE(keyImgOver[i]) - SAFEFREE(keyTxt[i]) - SAFEFREE(keyBtn[i]) - } - } + for(int i=0; i<11; i++) + { + if (keys[i] != '\0') + { + SAFEFREE(keyImg[i]) + SAFEFREE(keyImgOver[i]) + SAFEFREE(keyTxt[i]) + SAFEFREE(keyBtn[i]) + } + } } -void GuiNumpad::Update(GuiTrigger * t) { - LOCK(this); - if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) - return; +void GuiNumpad::Update(GuiTrigger * t) +{ + LOCK(this); + if(_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) + return; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->Update(t); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->Update(t); } + catch (const std::exception& e) { } + } - if (keyBack->GetState() == STATE_CLICKED) { - if (strlen(kbtextstr) > 0) { - kbtextstr[strlen(kbtextstr)-1] = 0; - kbText->SetText(kbtextstr); - } - keyBack->SetState(STATE_SELECTED, t->chan); - } else if (keyClear->GetState() == STATE_CLICKED) { - memset(kbtextstr, 0, sizeof(kbtextstr)); - kbText->SetText(kbtextstr); - keyClear->SetState(STATE_SELECTED, t->chan); - } + if(keyBack->GetState() == STATE_CLICKED) + { + if (strlen(kbtextstr) > 0){ + kbtextstr[strlen(kbtextstr)-1] = 0; + kbText->SetText(kbtextstr); + } + keyBack->SetState(STATE_SELECTED, t->chan); + } + else if(keyClear->GetState() == STATE_CLICKED) + { + memset(kbtextstr, 0, sizeof(kbtextstr)); + kbText->SetText(kbtextstr); + keyClear->SetState(STATE_SELECTED, t->chan); + } - char txt[2] = { 0, 0 }; - for (int i=0; i<11; i++) { - if (keys[i] != '\0') { - if (keyBtn[i]->GetState() == STATE_CLICKED) { - txt[0] = keys[i]; - if (strlen(kbtextstr) < kbtextmaxlen-1) { // -1 --> kbtextmaxlen means with term. '\0' - kbtextstr[strlen(kbtextstr)] = txt[0]; - kbText->SetText(kbtextstr); - } - keyBtn[i]->SetState(STATE_SELECTED, t->chan); - } - } - } + char txt[2] = { 0, 0 }; + for(int i=0; i<11; i++) + { + if (keys[i] != '\0') + { + if(keyBtn[i]->GetState() == STATE_CLICKED) + { + txt[0] = keys[i]; + if(strlen(kbtextstr) < kbtextmaxlen-1) // -1 --> kbtextmaxlen means with term. '\0' + { + kbtextstr[strlen(kbtextstr)] = txt[0]; + kbText->SetText(kbtextstr); + } + keyBtn[i]->SetState(STATE_SELECTED, t->chan); + } + } + } - kbText->SetPosition(0, 53); + kbText->SetPosition(0, 53); - this->ToggleFocus(t); + this->ToggleFocus(t); - if (focus) { // only send actions to this window if it's in focus - // pad/joystick navigation - if (t->Right()) - this->MoveSelectionHor(1); - else if (t->Left()) - this->MoveSelectionHor(-1); - else if (t->Down()) - this->MoveSelectionVert(1); - else if (t->Up()) - this->MoveSelectionVert(-1); - } + if(focus) // only send actions to this window if it's in focus + { + // pad/joystick navigation + if(t->Right()) + this->MoveSelectionHor(1); + else if(t->Left()) + this->MoveSelectionHor(-1); + else if(t->Down()) + this->MoveSelectionVert(1); + else if(t->Up()) + this->MoveSelectionVert(-1); + } } diff --git a/source/libwiigui/gui_optionbrowser.cpp b/source/libwiigui/gui_optionbrowser.cpp index 8e53c4e7..4775c7fc 100644 --- a/source/libwiigui/gui_optionbrowser.cpp +++ b/source/libwiigui/gui_optionbrowser.cpp @@ -21,319 +21,336 @@ static int scrollbaron, startat, loaded = 0; /** * Constructor for the GuiOptionBrowser class. */ -GuiOptionBrowser::GuiOptionBrowser(int w, int h, OptionList * l, const u8 *imagebg, int scrollon) { - width = w; - height = h; - options = l; - scrollbaron = scrollon; - selectable = true; - listOffset = this->FindMenuItem(-1, 1); - listChanged = true; // trigger an initial list update - selectedItem = 0; - focus = 1; // allow focus +GuiOptionBrowser::GuiOptionBrowser(int w, int h, OptionList * l, const u8 *imagebg, int scrollon) +{ + width = w; + height = h; + options = l; + scrollbaron = scrollon; + selectable = true; + listOffset = this->FindMenuItem(-1, 1); + listChanged = true; // trigger an initial list update + selectedItem = 0; + focus = 1; // allow focus - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); + trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - bgOptions = new GuiImageData(imagebg); - bgOptionsImg = new GuiImage(bgOptions); - bgOptionsImg->SetParent(this); - bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + bgOptions = new GuiImageData(imagebg); + bgOptionsImg = new GuiImage(bgOptions); + bgOptionsImg->SetParent(this); + bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - bgOptionsEntry = new GuiImageData(bg_options_entry_png); + bgOptionsEntry = new GuiImageData(bg_options_entry_png); if (scrollbaron == 1) { - scrollbar = new GuiImageData(scrollbar_png); - scrollbarImg = new GuiImage(scrollbar); - scrollbarImg->SetParent(this); - scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarImg->SetPosition(0, 4); + scrollbar = new GuiImageData(scrollbar_png); + scrollbarImg = new GuiImage(scrollbar); + scrollbarImg->SetParent(this); + scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + scrollbarImg->SetPosition(0, 4); - arrowDown = new GuiImageData(scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - arrowDownOver = new GuiImageData(scrollbar_arrowdown_png); - arrowDownOverImg = new GuiImage(arrowDownOver); - arrowUp = new GuiImageData(scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - arrowUpOver = new GuiImageData(scrollbar_arrowup_png); - arrowUpOverImg = new GuiImage(arrowUpOver); - scrollbarBox = new GuiImageData(scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); - scrollbarBoxOver = new GuiImageData(scrollbar_box_png); - scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); + arrowDown = new GuiImageData(scrollbar_arrowdown_png); + arrowDownImg = new GuiImage(arrowDown); + arrowDownOver = new GuiImageData(scrollbar_arrowdown_png); + arrowDownOverImg = new GuiImage(arrowDownOver); + arrowUp = new GuiImageData(scrollbar_arrowup_png); + arrowUpImg = new GuiImage(arrowUp); + arrowUpOver = new GuiImageData(scrollbar_arrowup_png); + arrowUpOverImg = new GuiImage(arrowUpOver); + scrollbarBox = new GuiImageData(scrollbar_box_png); + scrollbarBoxImg = new GuiImage(scrollbarBox); + scrollbarBoxOver = new GuiImageData(scrollbar_box_png); + scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetImageOver(arrowUpOverImg); - arrowUpBtn->SetImageHold(arrowUpOverImg); - arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - arrowUpBtn->SetPosition(width/2-18+7,-18); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetTrigger(trigA); - arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); + arrowUpBtn->SetParent(this); + arrowUpBtn->SetImage(arrowUpImg); + arrowUpBtn->SetImageOver(arrowUpOverImg); + arrowUpBtn->SetImageHold(arrowUpOverImg); + arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + arrowUpBtn->SetPosition(width/2-18+7,-18); + arrowUpBtn->SetSelectable(false); + arrowUpBtn->SetTrigger(trigA); + arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowUpBtn->SetSoundClick(btnSoundClick); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetImageOver(arrowDownOverImg); - arrowDownBtn->SetImageHold(arrowDownOverImg); - arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(width/2-18+7,18); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetTrigger(trigA); - arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowDownBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); + arrowDownBtn->SetParent(this); + arrowDownBtn->SetImage(arrowDownImg); + arrowDownBtn->SetImageOver(arrowDownOverImg); + arrowDownBtn->SetImageHold(arrowDownOverImg); + arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + arrowDownBtn->SetPosition(width/2-18+7,18); + arrowDownBtn->SetSelectable(false); + arrowDownBtn->SetTrigger(trigA); + arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowDownBtn->SetSoundClick(btnSoundClick); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); - scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); - scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); - scrollbarBoxBtn->SetMinY(0); - scrollbarBoxBtn->SetMaxY(height); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); + scrollbarBoxBtn->SetParent(this); + scrollbarBoxBtn->SetImage(scrollbarBoxImg); + scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); + scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); + scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + scrollbarBoxBtn->SetSelectable(false); + scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); + scrollbarBoxBtn->SetMinY(0); + scrollbarBoxBtn->SetMaxY(height); + scrollbarBoxBtn->SetHoldable(true); + scrollbarBoxBtn->SetTrigger(trigHeldA); } // optionBg = new GuiImage(bgOptionsEntry); - for (int i=0; iSetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionTxt[i]->SetPosition(24,0); + for(int i=0; iSetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + optionTxt[i]->SetPosition(24,0); - optionBg[i] = new GuiImage(bgOptionsEntry); + optionBg[i] = new GuiImage(bgOptionsEntry); - optionVal[i] = new GuiText(NULL, 20, (GXColor) {0, 0, 0, 0xff}); - optionVal[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionVal[i]->SetPosition(250,0); + optionVal[i] = new GuiText(NULL, 20, (GXColor){0, 0, 0, 0xff}); + optionVal[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + optionVal[i]->SetPosition(250,0); - optionBtn[i] = new GuiButton(width-28,GAMESELECTSIZE); - optionBtn[i]->SetParent(this); - optionBtn[i]->SetLabel(optionTxt[i], 0); - optionBtn[i]->SetLabel(optionVal[i], 1); - optionBtn[i]->SetImageOver(optionBg[i]); - optionBtn[i]->SetPosition(5,GAMESELECTSIZE*i+4); - optionBtn[i]->SetRumble(false); - optionBtn[i]->SetTrigger(trigA); - optionBtn[i]->SetSoundClick(btnSoundClick); - } + optionBtn[i] = new GuiButton(width-28,GAMESELECTSIZE); + optionBtn[i]->SetParent(this); + optionBtn[i]->SetLabel(optionTxt[i], 0); + optionBtn[i]->SetLabel(optionVal[i], 1); + optionBtn[i]->SetImageOver(optionBg[i]); + optionBtn[i]->SetPosition(5,GAMESELECTSIZE*i+4); + optionBtn[i]->SetRumble(false); + optionBtn[i]->SetTrigger(trigA); + optionBtn[i]->SetSoundClick(btnSoundClick); + } } /** * Constructor for the GuiOptionBrowser class. */ -GuiOptionBrowser::GuiOptionBrowser(int w, int h, OptionList * l, const char *themePath, const u8 *imagebg, int scrollon, int start) { - width = w; - height = h; - options = l; - startat = start; - loaded = 0; - scrollbaron = scrollon; - selectable = true; - listOffset = this->FindMenuItem(-1, 1); - selectedItem = 0; - focus = 1; // allow focus - char imgPath[100]; +GuiOptionBrowser::GuiOptionBrowser(int w, int h, OptionList * l, const char *themePath, const u8 *imagebg, int scrollon, int start) +{ + width = w; + height = h; + options = l; + startat = start; + loaded = 0; + scrollbaron = scrollon; + selectable = true; + listOffset = this->FindMenuItem(-1, 1); + selectedItem = 0; + focus = 1; // allow focus + char imgPath[100]; - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); + btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", themePath); - bgOptions = new GuiImageData(imgPath, imagebg); + snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", themePath); + bgOptions = new GuiImageData(imgPath, imagebg); - bgOptionsImg = new GuiImage(bgOptions); - bgOptionsImg->SetParent(this); - bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + bgOptionsImg = new GuiImage(bgOptions); + bgOptionsImg->SetParent(this); + bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); - bgOptionsEntry = new GuiImageData(imgPath, bg_options_entry_png); + snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); + bgOptionsEntry = new GuiImageData(imgPath, bg_options_entry_png); if (scrollbaron == 1) { - snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", themePath); - scrollbar = new GuiImageData(imgPath, scrollbar_png); - scrollbarImg = new GuiImage(scrollbar); - scrollbarImg->SetParent(this); - scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarImg->SetPosition(0, 4); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", themePath); + scrollbar = new GuiImageData(imgPath, scrollbar_png); + scrollbarImg = new GuiImage(scrollbar); + scrollbarImg->SetParent(this); + scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + scrollbarImg->SetPosition(0, 4); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", themePath); - arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownOverImg = new GuiImage(arrowDownOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); - arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpOverImg = new GuiImage(arrowUpOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); - scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); - scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", themePath); + arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownImg = new GuiImage(arrowDown); + arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownOverImg = new GuiImage(arrowDownOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); + arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpImg = new GuiImage(arrowUp); + arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpOverImg = new GuiImage(arrowUpOver); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); + scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); + scrollbarBoxImg = new GuiImage(scrollbarBox); + scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); + scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetImageOver(arrowUpOverImg); - arrowUpBtn->SetImageHold(arrowUpOverImg); - arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - arrowUpBtn->SetPosition(width/2-18+7,-18); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetTrigger(trigA); - arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); + arrowUpBtn->SetParent(this); + arrowUpBtn->SetImage(arrowUpImg); + arrowUpBtn->SetImageOver(arrowUpOverImg); + arrowUpBtn->SetImageHold(arrowUpOverImg); + arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + arrowUpBtn->SetPosition(width/2-18+7,-18); + arrowUpBtn->SetSelectable(false); + arrowUpBtn->SetTrigger(trigA); + arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowUpBtn->SetSoundClick(btnSoundClick); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetImageOver(arrowDownOverImg); - arrowDownBtn->SetImageHold(arrowDownOverImg); - arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(width/2-18+7,18); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetTrigger(trigA); - arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowDownBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); + arrowDownBtn->SetParent(this); + arrowDownBtn->SetImage(arrowDownImg); + arrowDownBtn->SetImageOver(arrowDownOverImg); + arrowDownBtn->SetImageHold(arrowDownOverImg); + arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + arrowDownBtn->SetPosition(width/2-18+7,18); + arrowDownBtn->SetSelectable(false); + arrowDownBtn->SetTrigger(trigA); + arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowDownBtn->SetSoundClick(btnSoundClick); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); - scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); - scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); - scrollbarBoxBtn->SetMinY(0); - scrollbarBoxBtn->SetMaxY(height-30); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); + scrollbarBoxBtn->SetParent(this); + scrollbarBoxBtn->SetImage(scrollbarBoxImg); + scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); + scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); + scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + scrollbarBoxBtn->SetSelectable(false); + scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); + scrollbarBoxBtn->SetMinY(0); + scrollbarBoxBtn->SetMaxY(height-30); + scrollbarBoxBtn->SetHoldable(true); + scrollbarBoxBtn->SetTrigger(trigHeldA); } // optionBg = new GuiImage(bgOptionsEntry); - for (int i=0; iname[i], 20, (GXColor) {0, 0, 0, 0xff}); - optionTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionTxt[i]->SetPosition(24,0); + for(int i=0; iname[i], 20, (GXColor){0, 0, 0, 0xff}); + optionTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + optionTxt[i]->SetPosition(24,0); - optionBg[i] = new GuiImage(bgOptionsEntry); + optionBg[i] = new GuiImage(bgOptionsEntry); - optionVal[i] = new GuiText(NULL, 20, (GXColor) {0, 0, 0, 0xff}); - optionVal[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionVal[i]->SetPosition(250,0); + optionVal[i] = new GuiText(NULL, 20, (GXColor){0, 0, 0, 0xff}); + optionVal[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + optionVal[i]->SetPosition(250,0); - optionBtn[i] = new GuiButton(width-28,GAMESELECTSIZE); - optionBtn[i]->SetParent(this); - optionBtn[i]->SetLabel(optionTxt[i], 0); - optionBtn[i]->SetLabel(optionVal[i], 1); - optionBtn[i]->SetImageOver(optionBg[i]); - optionBtn[i]->SetPosition(5,GAMESELECTSIZE*i+4); - optionBtn[i]->SetTrigger(trigA); - optionBtn[i]->SetSoundClick(btnSoundClick); - } + optionBtn[i] = new GuiButton(width-28,GAMESELECTSIZE); + optionBtn[i]->SetParent(this); + optionBtn[i]->SetLabel(optionTxt[i], 0); + optionBtn[i]->SetLabel(optionVal[i], 1); + optionBtn[i]->SetImageOver(optionBg[i]); + optionBtn[i]->SetPosition(5,GAMESELECTSIZE*i+4); + optionBtn[i]->SetTrigger(trigA); + optionBtn[i]->SetSoundClick(btnSoundClick); + } } /** * Destructor for the GuiOptionBrowser class. */ -GuiOptionBrowser::~GuiOptionBrowser() { +GuiOptionBrowser::~GuiOptionBrowser() +{ if (scrollbaron == 1) { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; - delete scrollbarImg; - delete arrowDownImg; - delete arrowDownOverImg; - delete arrowUpImg; - delete arrowUpOverImg; - delete scrollbarBoxImg; - delete scrollbarBoxOverImg; - delete scrollbar; - delete arrowDown; - delete arrowDownOver; - delete arrowUp; - delete arrowUpOver; - delete scrollbarBox; - delete scrollbarBoxOver; + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; + delete scrollbarImg; + delete arrowDownImg; + delete arrowDownOverImg; + delete arrowUpImg; + delete arrowUpOverImg; + delete scrollbarBoxImg; + delete scrollbarBoxOverImg; + delete scrollbar; + delete arrowDown; + delete arrowDownOver; + delete arrowUp; + delete arrowUpOver; + delete scrollbarBox; + delete scrollbarBoxOver; } delete bgOptionsImg; - delete bgOptions; - delete bgOptionsEntry; - loaded = 0; + delete bgOptions; + delete bgOptionsEntry; + loaded = 0; - delete trigA; - delete btnSoundClick; + delete trigA; + delete btnSoundClick; // delete optionBg; - for (int i=0; iSetPosition(x,0); +void GuiOptionBrowser::SetCol2Position(int x) +{ + LOCK(this); + for(int i=0; iSetPosition(x,0); } -void GuiOptionBrowser::SetFocus(int f) { - LOCK(this); - focus = f; +void GuiOptionBrowser::SetFocus(int f) +{ + LOCK(this); + focus = f; - for (int i=0; iResetState(); + for(int i=0; iResetState(); - if (f == 1) - optionBtn[selectedItem]->SetState(STATE_SELECTED); + if(f == 1) + optionBtn[selectedItem]->SetState(STATE_SELECTED); } -void GuiOptionBrowser::ResetState() { - LOCK(this); - if (state != STATE_DISABLED) { - state = STATE_DEFAULT; - stateChan = -1; - } +void GuiOptionBrowser::ResetState() +{ + LOCK(this); + if(state != STATE_DISABLED) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for (int i=0; iResetState(); - } + for(int i=0; iResetState(); + } } -int GuiOptionBrowser::GetClickedOption() { - int found = -1; - for (int i=0; iGetState() == STATE_CLICKED) { - optionBtn[i]->SetState(STATE_SELECTED); - found = optionIndex[i]; - break; - } - } - return found; +int GuiOptionBrowser::GetClickedOption() +{ + int found = -1; + for(int i=0; iGetState() == STATE_CLICKED) + { + optionBtn[i]->SetState(STATE_SELECTED); + found = optionIndex[i]; + break; + } + } + return found; } -int GuiOptionBrowser::GetSelectedOption() { - int found = -1; - for (int i=0; iGetState() == STATE_SELECTED) { - optionBtn[i]->SetState(STATE_SELECTED); - found = optionIndex[i]; - break; - } - } - return found; +int GuiOptionBrowser::GetSelectedOption() +{ + int found = -1; + for(int i=0; iGetState() == STATE_SELECTED) + { + optionBtn[i]->SetState(STATE_SELECTED); + found = optionIndex[i]; + break; + } + } + return found; } /**************************************************************************** @@ -342,269 +359,316 @@ int GuiOptionBrowser::GetSelectedOption() { * Help function to find the next visible menu item on the list ***************************************************************************/ -int GuiOptionBrowser::FindMenuItem(int currentItem, int direction) { - int nextItem = currentItem + direction; +int GuiOptionBrowser::FindMenuItem(int currentItem, int direction) +{ + int nextItem = currentItem + direction; - if (nextItem < 0 || nextItem >= options->length) - return -1; + if(nextItem < 0 || nextItem >= options->length) + return -1; - if (strlen(options->name[nextItem]) > 0) - return nextItem; - else - return FindMenuItem(nextItem, direction); + if(strlen(options->name[nextItem]) > 0) + return nextItem; + else + return FindMenuItem(nextItem, direction); } /** * Draw the button on screen */ -void GuiOptionBrowser::Draw() { - LOCK(this); - if (!this->IsVisible()) - return; +void GuiOptionBrowser::Draw() +{ + LOCK(this); + if(!this->IsVisible()) + return; - bgOptionsImg->Draw(); + bgOptionsImg->Draw(); - int next = listOffset; + int next = listOffset; - for (int i=0; i= 0) { - optionBtn[i]->Draw(); - next = this->FindMenuItem(next, 1); - } else - break; + for(int i=0; i= 0) + { + optionBtn[i]->Draw(); + next = this->FindMenuItem(next, 1); + } + else + break; + } + + if(scrollbaron == 1) { + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); } + this->UpdateEffects(); +} + + +void GuiOptionBrowser::TriggerUpdate() +{ + listChanged = true; +} + +void GuiOptionBrowser::Update(GuiTrigger * t) +{ + LOCK(this); + int next, prev, lang = options->length; + + //go to the last game selected + if ((loaded == 0) && (startat>0)) + { + + if (startat > (lang-9)){ + listOffset= (lang-9); + selectedItem=startat; + optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); + } + else if (startat < 9){ + selectedItem=startat; + optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); + } + else { + listOffset = (startat-4); + selectedItem=startat; + optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan);} + this->SetFocus(1); + loaded = 1; + } + + if(state == STATE_DISABLED || !t) + return; + + + // scrolldelay affects how fast the list scrolls + // when the arrows are clicked + float scrolldelay = 3.5; + if (scrollbaron == 1) { - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); + // update the location of the scroll box based on the position in the option list + + + arrowUpBtn->Update(t); + arrowDownBtn->Update(t); + scrollbarBoxBtn->Update(t); } - this->UpdateEffects(); -} + next = listOffset; + + if(listChanged) + { + for(int i=0; i= 0) + { + if(optionBtn[i]->GetState() == STATE_DISABLED) + { + optionBtn[i]->SetVisible(true); + optionBtn[i]->SetState(STATE_DEFAULT); + } + + optionTxt[i]->SetText(options->name[next]); + optionVal[i]->SetText(options->value[next]); + optionIndex[i] = next; + next = this->FindMenuItem(next, 1); + } + else + { + optionBtn[i]->SetVisible(false); + optionBtn[i]->SetState(STATE_DISABLED); + } + } + } + for(int i=0; iGetState() == STATE_SELECTED) + optionBtn[i]->ResetState(); + else if(i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) + optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); + } + + optionBtn[i]->Update(t); + + if(optionBtn[i]->GetState() == STATE_SELECTED) + { + selectedItem = i; + } + } + + // pad/joystick navigation + if(!focus) + return; // skip navigation + + if (scrollbaron == 1) { + + if (t->Down() || + arrowDownBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////down + arrowDownBtn->GetState() == STATE_HELD) + { + + next = this->FindMenuItem(optionIndex[selectedItem], 1); + + if(next >= 0) + { + if(selectedItem == PAGESIZE-1) + { + // move list down by 1 + listOffset = this->FindMenuItem(listOffset, 1); + } + else if(optionBtn[selectedItem+1]->IsVisible()) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); + selectedItem++; + } + scrollbarBoxBtn->Draw(); + usleep(10000 * scrolldelay); -void GuiOptionBrowser::TriggerUpdate() { - listChanged = true; -} + }WPAD_ScanPads(); + u8 cnt, buttons = NULL; + /* Get pressed buttons */ + for (cnt = 0; cnt < 4; cnt++) + buttons |= WPAD_ButtonsHeld(cnt); + if (buttons == WPAD_BUTTON_A) { -void GuiOptionBrowser::Update(GuiTrigger * t) { - LOCK(this); - int next, prev, lang = options->length; - - //go to the last game selected - if ((loaded == 0) && (startat>0)) { - - if (startat > (lang-9)) { - listOffset= (lang-9); - selectedItem=startat; - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); - } else if (startat < 9) { - selectedItem=startat; - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); } else { - listOffset = (startat-4); - selectedItem=startat; - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); - } - this->SetFocus(1); - loaded = 1; - } - - if (state == STATE_DISABLED || !t) - return; - - - // scrolldelay affects how fast the list scrolls - // when the arrows are clicked - float scrolldelay = 3.5; - - - if (scrollbaron == 1) { - // update the location of the scroll box based on the position in the option list - - - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); - } - next = listOffset; - - if (listChanged) { - for (int i=0; i= 0) { - if (optionBtn[i]->GetState() == STATE_DISABLED) { - optionBtn[i]->SetVisible(true); - optionBtn[i]->SetState(STATE_DEFAULT); - } - - optionTxt[i]->SetText(options->name[next]); - optionVal[i]->SetText(options->value[next]); - optionIndex[i] = next; - next = this->FindMenuItem(next, 1); - } else { - optionBtn[i]->SetVisible(false); - optionBtn[i]->SetState(STATE_DISABLED); - } - } - } - for (int i=0; iGetState() == STATE_SELECTED) - optionBtn[i]->ResetState(); - else if (i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); - } - - optionBtn[i]->Update(t); - - if (optionBtn[i]->GetState() == STATE_SELECTED) { - selectedItem = i; - } - } - - // pad/joystick navigation - if (!focus) - return; // skip navigation - - if (scrollbaron == 1) { - - if (t->Down() || - arrowDownBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////down - arrowDownBtn->GetState() == STATE_HELD) { - - next = this->FindMenuItem(optionIndex[selectedItem], 1); - - if (next >= 0) { - if (selectedItem == PAGESIZE-1) { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } else if (optionBtn[selectedItem+1]->IsVisible()) { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - - - } - WPAD_ScanPads(); - u8 cnt, buttons = NULL; - /* Get pressed buttons */ - for (cnt = 0; cnt < 4; cnt++) - buttons |= WPAD_ButtonsHeld(cnt); - if (buttons == WPAD_BUTTON_A) { - - } else { - arrowDownBtn->ResetState(); - - } - - } else if (t->Up() || - arrowUpBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////up - arrowUpBtn->GetState() == STATE_HELD) { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); - - if (prev >= 0) { - if (selectedItem == 0) { - // move list up by 1 - listOffset = prev; - } else { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - - - } - WPAD_ScanPads(); - u8 cnt, buttons = NULL; - /* Get pressed buttons */ - for (cnt = 0; cnt < 4; cnt++) - buttons |= WPAD_ButtonsHeld(cnt); - if (buttons == WPAD_BUTTON_A) { - - } else { - arrowUpBtn->ResetState(); - - } - } - - if (scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && options->length > PAGESIZE) { - scrollbarBoxBtn->SetPosition(width/2-18+7,0); - int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); - - listOffset = (position * lang)/180 - selectedItem; - - if (listOffset <= 0) { - listOffset = 0; - selectedItem = 0; - } else if (listOffset+PAGESIZE >= lang) { - listOffset = lang-PAGESIZE; - selectedItem = PAGESIZE-1; - } + arrowDownBtn->ResetState(); } + + } + else if(t->Up() || + arrowUpBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////up + arrowUpBtn->GetState() == STATE_HELD) + { + prev = this->FindMenuItem(optionIndex[selectedItem], -1); + + if(prev >= 0) + { + if(selectedItem == 0) + { + // move list up by 1 + listOffset = prev; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); + selectedItem--; + } + scrollbarBoxBtn->Draw(); + usleep(10000 * scrolldelay); + + + }WPAD_ScanPads(); + u8 cnt, buttons = NULL; + /* Get pressed buttons */ + for (cnt = 0; cnt < 4; cnt++) + buttons |= WPAD_ButtonsHeld(cnt); + if (buttons == WPAD_BUTTON_A) { + + } else { + arrowUpBtn->ResetState(); + + } + } + + if(scrollbarBoxBtn->GetState() == STATE_HELD && + scrollbarBoxBtn->GetStateChan() == t->chan && + t->wpad.ir.valid && options->length > PAGESIZE) + { + scrollbarBoxBtn->SetPosition(width/2-18+7,0); + int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); + + listOffset = (position * lang)/180 - selectedItem; + + if(listOffset <= 0) + { + listOffset = 0; + selectedItem = 0; + } + else if(listOffset+PAGESIZE >= lang) + { + listOffset = lang-PAGESIZE; + selectedItem = PAGESIZE-1; + } + + } int positionbar = 237*(listOffset + selectedItem) / lang; - if (positionbar > 216) - positionbar = 216; - scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); + if(positionbar > 216) + positionbar = 216; + scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); - if (t->Right()) { - if (listOffset < lang && lang > PAGESIZE) { - listOffset =listOffset+ PAGESIZE; - if (listOffset+PAGESIZE >= lang) - listOffset = lang-PAGESIZE; - } - } else if (t->Left()) { - if (listOffset > 0) { - listOffset =listOffset- PAGESIZE; - if (listOffset < 0) - listOffset = 0; - } - } + if(t->Right()) + { + if(listOffset < lang && lang > PAGESIZE) + { + listOffset =listOffset+ PAGESIZE; + if(listOffset+PAGESIZE >= lang) + listOffset = lang-PAGESIZE; + } + } + else if(t->Left()) + { + if(listOffset > 0) + { + listOffset =listOffset- PAGESIZE; + if(listOffset < 0) + listOffset = 0; + } + } } else { - if (t->Down()) { - next = this->FindMenuItem(optionIndex[selectedItem], 1); + if(t->Down()) + { + next = this->FindMenuItem(optionIndex[selectedItem], 1); - if (next >= 0) { - if (selectedItem == PAGESIZE-1) { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - listChanged = true; - } else if (optionBtn[selectedItem+1]->IsVisible()) { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - } - } else if (t->Up()) { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); + if(next >= 0) + { + if(selectedItem == PAGESIZE-1) + { + // move list down by 1 + listOffset = this->FindMenuItem(listOffset, 1); + listChanged = true; + } + else if(optionBtn[selectedItem+1]->IsVisible()) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); + selectedItem++; + } + } + } + else if(t->Up()) + { + prev = this->FindMenuItem(optionIndex[selectedItem], -1); - if (prev >= 0) { - if (selectedItem == 0) { - // move list up by 1 - listOffset = prev; - listChanged = true; - } else { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - } - } + if(prev >= 0) + { + if(selectedItem == 0) + { + // move list up by 1 + listOffset = prev; + listChanged = true; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); + selectedItem--; + } + } + } } - if (updateCB) - updateCB(this); + if(updateCB) + updateCB(this); } diff --git a/source/libwiigui/gui_searchbar.cpp b/source/libwiigui/gui_searchbar.cpp index ea9fda62..12d0007a 100644 --- a/source/libwiigui/gui_searchbar.cpp +++ b/source/libwiigui/gui_searchbar.cpp @@ -8,148 +8,160 @@ extern GuiWindow * mainWindow; -class cSearchButton { +class cSearchButton +{ public: - cSearchButton(wchar_t *Char, GuiImageData *keyImageData, GuiImageData *keyOverImageData, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick) - : - wchar(*Char), - image(keyImageData), - imageOver(keyOverImageData), - text(NULL, 20, (GXColor) {0, 0, 0, 0xff}), - button(&image, &imageOver, ALIGN_LEFT, ALIGN_TOP, x, y, trig, sndOver, sndClick, 1) { - text.SetText(Char); - button.SetLabel(&text); - } - wchar_t wchar; - GuiImage image; - GuiImage imageOver; - GuiText text; - GuiButton button; + cSearchButton(wchar_t *Char, GuiImageData *keyImageData, GuiImageData *keyOverImageData, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick) + : + wchar(*Char), + image(keyImageData), + imageOver(keyOverImageData), + text(NULL, 20, (GXColor){0, 0, 0, 0xff}), + button(&image, &imageOver, ALIGN_LEFT, ALIGN_TOP, x, y, trig, sndOver, sndClick, 1) + { + text.SetText(Char); + button.SetLabel(&text); + } + wchar_t wchar; + GuiImage image; + GuiImage imageOver; + GuiText text; + GuiButton button; private: }; GuiSearchBar::GuiSearchBar(const wchar_t *SearchChars) - : - inSide(0), - text(NULL, 22, (GXColor) {0, 0, 0, 255}), - buttons(0), - keyImageData(keyboard_key_png), - keyOverImageData(keyboard_key_over_png), - sndOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume), - sndClick(button_click_pcm, button_click_pcm_size, Settings.sfxvolume) { - char imgPath[100]; - trig.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); +: +inSide(0), +text(NULL, 22, (GXColor) {0, 0, 0, 255}), +buttons(0), +keyImageData(keyboard_key_png), +keyOverImageData(keyboard_key_over_png), +sndOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume), +sndClick(button_click_pcm, button_click_pcm_size, Settings.sfxvolume) +{ + char imgPath[100]; + trig.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - cnt = wcslen(SearchChars); - buttons = new cSearchButton*[cnt]; - - wchar_t charstr[2] = {0, 0}; - int lines = (cnt+9)/10; - int buttonsPerLine = (cnt+lines-1)/lines; - width = 10+buttonsPerLine*42+10; - int x_start=10, x=0, y_start=10+42, y=0; - if (width < 200) { - x_start += (200-width)>>1; - width=200; - } - for (int i=0; i= buttonsPerLine) x=0; - if (x == 0) y++; - charstr[0] = SearchChars[i]; - buttons[i] = new cSearchButton(charstr, &keyImageData, &keyOverImageData, x_start+x*42, y_start-42+y*42, &trig, &sndOver, &sndClick); - this->Append(&(buttons[i]->button)); - } - height = 10+42+y*42+10; + cnt = wcslen(SearchChars); + buttons = new cSearchButton*[cnt]; + + wchar_t charstr[2] = {0, 0}; + int lines = (cnt+9)/10; + int buttonsPerLine = (cnt+lines-1)/lines; + width = 10+buttonsPerLine*42+10; + int x_start=10, x=0, y_start=10+42, y=0; + if(width < 200) { x_start += (200-width)>>1; width=200; } + for(int i=0; i= buttonsPerLine) x=0; + if(x == 0) y++; + charstr[0] = SearchChars[i]; + buttons[i] = new cSearchButton(charstr, &keyImageData, &keyOverImageData, x_start+x*42, y_start-42+y*42, &trig, &sndOver, &sndClick); + this->Append(&(buttons[i]->button)); + } + height = 10+42+y*42+10; - text.SetText(gameFilter); - text.SetPosition(10, 15); - text.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - text.SetWidescreen(CFG.widescreen); - text.SetMaxWidth(width-(10+2*42+10), GuiText::SCROLL); - this->Append(&text); + text.SetText(gameFilter); + text.SetPosition(10, 15); + text.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + text.SetWidescreen(CFG.widescreen); + text.SetMaxWidth(width-(10+2*42+10), GuiText::SCROLL); + this->Append(&text); snprintf(imgPath, sizeof(imgPath), "%skeyboard_backspace_over.png", CFG.theme_path); - imgBacspaceBtn = new GuiImageData(imgPath, keyboard_backspace_over_png); - BacspaceBtnImg_Over = new GuiImage(imgBacspaceBtn); - BacspaceBtnImg = new GuiImage(BacspaceBtnImg_Over); - BacspaceBtnImg->SetGrayscale(); - BacspaceBtn = new GuiButton(BacspaceBtnImg,BacspaceBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -52, 10, &trig, &sndOver, &sndClick,1); - this->Append(BacspaceBtn); - + imgBacspaceBtn = new GuiImageData(imgPath, keyboard_backspace_over_png); + BacspaceBtnImg_Over = new GuiImage(imgBacspaceBtn); + BacspaceBtnImg = new GuiImage(BacspaceBtnImg_Over); BacspaceBtnImg->SetGrayscale(); + BacspaceBtn = new GuiButton(BacspaceBtnImg,BacspaceBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -52, 10, &trig, &sndOver, &sndClick,1); + this->Append(BacspaceBtn); + snprintf(imgPath, sizeof(imgPath), "%skeyboard_clear_over.png", CFG.theme_path); - imgClearBtn = new GuiImageData(imgPath, keyboard_clear_over_png); - ClearBtnImg_Over = new GuiImage(imgClearBtn); - ClearBtnImg = new GuiImage(ClearBtnImg_Over); - ClearBtnImg->SetGrayscale(); - ClearBtn = new GuiButton(ClearBtnImg,ClearBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -10, 10, &trig, &sndOver, &sndClick,1); - this->Append(ClearBtn); - + imgClearBtn = new GuiImageData(imgPath, keyboard_clear_over_png); + ClearBtnImg_Over = new GuiImage(imgClearBtn); + ClearBtnImg = new GuiImage(ClearBtnImg_Over); ClearBtnImg->SetGrayscale(); + ClearBtn = new GuiButton(ClearBtnImg,ClearBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -10, 10, &trig, &sndOver, &sndClick,1); + this->Append(ClearBtn); + // SetPosition(100,100); } -GuiSearchBar::~GuiSearchBar() { - if (buttons) { - for (int i=0; iSetState(STATE_DEFAULT); + delete BacspaceBtn; + delete BacspaceBtnImg; + delete BacspaceBtnImg_Over; + delete imgBacspaceBtn; + if(inSide) + mainWindow->SetState(STATE_DEFAULT); } -void GuiSearchBar::Draw() { - Menu_DrawRectangle(this->GetLeft(),this->GetTop(),width, height,(GXColor) {0, 0, 0, 0xa0},1); - Menu_DrawRectangle(this->GetLeft()+10,this->GetTop()+15,width-(10+2*42+10), 22,(GXColor) {255, 255, 255, 255},1); - GuiWindow::Draw(); +void GuiSearchBar::Draw() +{ + Menu_DrawRectangle(this->GetLeft(),this->GetTop(),width, height,(GXColor){0, 0, 0, 0xa0},1); + Menu_DrawRectangle(this->GetLeft()+10,this->GetTop()+15,width-(10+2*42+10), 22,(GXColor){255, 255, 255, 255},1); + GuiWindow::Draw(); } -void GuiSearchBar::Update(GuiTrigger * t) { - LOCK(this); - if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) - return; - // cursor - if (t->wpad.ir.valid && state != STATE_DISABLED) { - if (this->IsInside(t->wpad.ir.x, t->wpad.ir.y)) { - if (inSide == 0) { - mainWindow->SetState(STATE_DISABLED); - this->SetState(STATE_DEFAULT); - } - inSide |= 1 << t->chan; - } else if (inSide) { - inSide &= ~(1 << t->chan); - if (inSide == 0) - mainWindow->SetState(STATE_DEFAULT); - } - } - GuiWindow::Update(t); +void GuiSearchBar::Update(GuiTrigger * t) +{ + LOCK(this); + if(_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) + return; + // cursor + if(t->wpad.ir.valid && state != STATE_DISABLED) + { + if(this->IsInside(t->wpad.ir.x, t->wpad.ir.y)) + { + if(inSide == 0) + { + mainWindow->SetState(STATE_DISABLED); + this->SetState(STATE_DEFAULT); + } + inSide |= 1 << t->chan; + } + else if(inSide) + { + inSide &= ~(1 << t->chan); + if(inSide == 0) + mainWindow->SetState(STATE_DEFAULT); + } + } + GuiWindow::Update(t); } -wchar_t GuiSearchBar::GetClicked() { - if (buttons) { - for (int i=0; ibutton.GetState() == STATE_CLICKED) { - buttons[i]->button.ResetState(); - return buttons[i]->wchar; - } - } - } - if (BacspaceBtn->GetState() == STATE_CLICKED) - return 8; - if (ClearBtn->GetState() == STATE_CLICKED) - return 7; - - return 0; +wchar_t GuiSearchBar::GetClicked() +{ + if(buttons) + { + for(int i=0; ibutton.GetState() == STATE_CLICKED) + { + buttons[i]->button.ResetState(); + return buttons[i]->wchar; + } + } + } + if(BacspaceBtn->GetState() == STATE_CLICKED) + return 8; + if(ClearBtn->GetState() == STATE_CLICKED) + return 7; + + return 0; } /* diff --git a/source/libwiigui/gui_searchbar.h b/source/libwiigui/gui_searchbar.h index 7e8bbdbf..920a05c2 100644 --- a/source/libwiigui/gui_searchbar.h +++ b/source/libwiigui/gui_searchbar.h @@ -4,34 +4,35 @@ class cSearchButton; -class GuiSearchBar : public GuiWindow { +class GuiSearchBar : public GuiWindow +{ public: - GuiSearchBar(const wchar_t *SearchChars); - ~GuiSearchBar(); - void Draw(); - void Update(GuiTrigger * t); - wchar_t GetClicked(); + GuiSearchBar(const wchar_t *SearchChars); + ~GuiSearchBar(); + void Draw(); + void Update(GuiTrigger * t); + wchar_t GetClicked(); private: - u16 inSide; - - GuiText text; - - GuiImageData* imgBacspaceBtn; - GuiImage* BacspaceBtnImg; - GuiImage* BacspaceBtnImg_Over; - GuiButton* BacspaceBtn; - - GuiImageData* imgClearBtn; - GuiImage* ClearBtnImg; - GuiImage* ClearBtnImg_Over; - GuiButton* ClearBtn; - - cSearchButton **buttons; - int cnt; - GuiImageData keyImageData; - GuiImageData keyOverImageData; - GuiTrigger trig; - GuiSound sndOver; - GuiSound sndClick; + u16 inSide; + + GuiText text; + + GuiImageData* imgBacspaceBtn; + GuiImage* BacspaceBtnImg; + GuiImage* BacspaceBtnImg_Over; + GuiButton* BacspaceBtn; + + GuiImageData* imgClearBtn; + GuiImage* ClearBtnImg; + GuiImage* ClearBtnImg_Over; + GuiButton* ClearBtn; + + cSearchButton **buttons; + int cnt; + GuiImageData keyImageData; + GuiImageData keyOverImageData; + GuiTrigger trig; + GuiSound sndOver; + GuiSound sndClick; }; diff --git a/source/libwiigui/gui_sound.cpp b/source/libwiigui/gui_sound.cpp index d1968cdd..e565296a 100644 --- a/source/libwiigui/gui_sound.cpp +++ b/source/libwiigui/gui_sound.cpp @@ -28,28 +28,31 @@ ***************************************************************/ GuiSoundDecoder::DecoderListEntry *GuiSoundDecoder::DecoderList = NULL; -GuiSoundDecoder::DecoderListEntry &GuiSoundDecoder::RegisterDecoder(DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc) { - if (Decoder.fnc != fnc) { - Decoder.fnc = fnc; - Decoder.next = DecoderList; - DecoderList = &Decoder; - } - return Decoder; +GuiSoundDecoder::DecoderListEntry &GuiSoundDecoder::RegisterDecoder(DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc) +{ + if(Decoder.fnc != fnc) + { + Decoder.fnc = fnc; + Decoder.next = DecoderList; + DecoderList = &Decoder; + } + return Decoder; } -GuiSoundDecoder *GuiSoundDecoder::GetDecoder(const u8 * snd, u32 len, bool snd_is_allocated) { - for (DecoderListEntry *de = DecoderList; de; de=de->next) { - GuiSoundDecoder *d = NULL; - try { - d = de->fnc(snd, len, snd_is_allocated); - } catch (const char *error) { - gprintf("%s", error); - } catch (...) {} - if (d) return d; - } - return NULL; +GuiSoundDecoder *GuiSoundDecoder::GetDecoder(const u8 * snd, u32 len, bool snd_is_allocated) +{ + for(DecoderListEntry *de = DecoderList; de; de=de->next) + { + GuiSoundDecoder *d = NULL; + try{ d = de->fnc(snd, len, snd_is_allocated); } + catch(const char *error){ + gprintf("%s", error); } + catch(...){} + if(d) return d; + } + return NULL; } - + /*************************************************************** * * D E C O D E R – T H R E A D @@ -63,22 +66,26 @@ static lwp_t GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; static bool GuiSoundDecoderThreadRunning = false; static bool GuiSoundDecoderDataRquested = false; -void *GuiSoundDecoderThread(void *args) { - GuiSoundDecoderThreadRunning = true; - do { - if (GuiSoundDecoderDataRquested) { - GuiSoundDecoderDataRquested = false; - GuiSound **players = GuiSoundPlayer; - for ( int i = 0; i < 16; ++i , ++players) { - GuiSound *player = *players; - if (player) - player->DecoderCallback(); - } - } - if (!GuiSoundDecoderDataRquested) - usleep(50); - } while (GuiSoundDecoderThreadRunning); - return 0; +void *GuiSoundDecoderThread(void *args) +{ + GuiSoundDecoderThreadRunning = true; + do + { + if(GuiSoundDecoderDataRquested) + { + GuiSoundDecoderDataRquested = false; + GuiSound **players = GuiSoundPlayer; + for( int i = 0; i < 16; ++i , ++players) + { + GuiSound *player = *players; + if(player) + player->DecoderCallback(); + } + } + if(!GuiSoundDecoderDataRquested) + usleep(50); + } while(GuiSoundDecoderThreadRunning); + return 0; } /*************************************************************** @@ -88,11 +95,13 @@ void *GuiSoundDecoderThread(void *args) { * ***************************************************************/ -void GuiSoundPlayerCallback(s32 Voice) { - if (Voice >= 0 && Voice < 16 && GuiSoundPlayer[Voice]) { - GuiSoundPlayer[Voice]->PlayerCallback(); - GuiSoundDecoderDataRquested = true; - } +void GuiSoundPlayerCallback(s32 Voice) +{ + if(Voice >= 0 && Voice < 16 && GuiSoundPlayer[Voice]) + { + GuiSoundPlayer[Voice]->PlayerCallback(); + GuiSoundDecoderDataRquested = true; + } } /*************************************************************** @@ -101,60 +110,67 @@ void GuiSoundPlayerCallback(s32 Voice) { * Decoder for Raw-PCM-Datas (16bit Stereo 48kHz) * ***************************************************************/ -class GuiSoundDecoderRAW : public GuiSoundDecoder { +class GuiSoundDecoderRAW : public GuiSoundDecoder +{ protected: - GuiSoundDecoderRAW(const u8 * snd, u32 len, bool snd_is_allocated) { - pcm_start = snd; - is_allocated = snd_is_allocated; - pcm_end = pcm_start+len; - pos = pcm_start; - is_running = false; + GuiSoundDecoderRAW(const u8 * snd, u32 len, bool snd_is_allocated) + { + pcm_start = snd; + is_allocated = snd_is_allocated; + pcm_end = pcm_start+len; + pos = pcm_start; + is_running = false; } public: - ~GuiSoundDecoderRAW() { - while (is_running) usleep(50); - if (is_allocated) delete [] pcm_start; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - try { - return new GuiSoundDecoderRAW(snd, len, snd_is_allocated); - } catch (...) {} - return NULL; - } - s32 GetFormat() { - return VOICE_STEREO_16BIT; - } - s32 GetSampleRate() { - return 48000; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) { - if (pos >= pcm_end) - return 0; // EOF + ~GuiSoundDecoderRAW() + { + while(is_running) usleep(50); + if(is_allocated) delete [] pcm_start; + } + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) + { + try { return new GuiSoundDecoderRAW(snd, len, snd_is_allocated); } + catch(...) {} + return NULL; + } + s32 GetFormat() + { + return VOICE_STEREO_16BIT; + } + s32 GetSampleRate() + { + return 48000; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) + { + if(pos >= pcm_end) + return 0; // EOF - is_running = true; - if (pos + buffer_size > pcm_end) - buffer_size = pcm_end-pos; - memcpy(buffer, pos, buffer_size); - pos += buffer_size; - is_running = false; - return buffer_size; - } - int Rewind() { - pos = pcm_start; - return 0; - } + is_running = true; + if(pos + buffer_size > pcm_end) + buffer_size = pcm_end-pos; + memcpy(buffer, pos, buffer_size); + pos += buffer_size; + is_running = false; + return buffer_size; + } + int Rewind() + { + pos = pcm_start; + return 0; + } private: - const u8 *pcm_start; - const u8 *pcm_end; - bool is_allocated; - const u8 *pos; - bool is_running; + const u8 *pcm_start; + const u8 *pcm_end; + bool is_allocated; + const u8 *pos; + bool is_running; }; @@ -171,131 +187,145 @@ static int GuiSoundCount = 0; /** * Constructor for the GuiSound class. */ -GuiSound::GuiSound(const u8 *s, int l, int v/*=100*/, bool r/*=true*/, bool a/*=false*/) { - if (GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL) { - LWP_CreateThread(&GuiSoundDecoderThreadHandle,GuiSoundDecoderThread,NULL,NULL,32*1024,80); - } - voice = -1; - play_buffer[0] = (u8*)memalign(32, BUFFER_SIZE*3); // tripple-buffer first is played - play_buffer[1] = play_buffer[0] + BUFFER_SIZE; // second is waiting - play_buffer[2] = play_buffer[1] + BUFFER_SIZE; // third is decoding - buffer_nr = 0; // current playbuffer - buffer_pos = 0; // current idx to write in buffer - buffer_ready = false; - buffer_eof = false; - loop = false; // play looped - volume = v; // volume - decoder = NULL; - if (play_buffer[0]) // playbuffer ok - Load(s, l, r, a); +GuiSound::GuiSound(const u8 *s, int l, int v/*=100*/, bool r/*=true*/, bool a/*=false*/) +{ + if(GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL) + { + LWP_CreateThread(&GuiSoundDecoderThreadHandle,GuiSoundDecoderThread,NULL,NULL,32*1024,80); + } + voice = -1; + play_buffer[0] = (u8*)memalign(32, BUFFER_SIZE*3); // tripple-buffer first is played + play_buffer[1] = play_buffer[0] + BUFFER_SIZE; // second is waiting + play_buffer[2] = play_buffer[1] + BUFFER_SIZE; // third is decoding + buffer_nr = 0; // current playbuffer + buffer_pos = 0; // current idx to write in buffer + buffer_ready = false; + buffer_eof = false; + loop = false; // play looped + volume = v; // volume + decoder = NULL; + if(play_buffer[0]) // playbuffer ok + Load(s, l, r, a); } -bool GuiSound::Load(const u8 *s, int l, bool r/*=false*/, bool a/*=false*/) { - Stop(); - if (!play_buffer[0]) return false; - GuiSoundDecoder *newDecoder = GuiSoundDecoder::GetDecoder(s, l, a); - if (!newDecoder && r) newDecoder = GuiSoundDecoderRAW::Create(s, l, a); - if (newDecoder) { - delete decoder; - decoder = newDecoder; - return true; - } else if (a) - delete [] s; - return false; +bool GuiSound::Load(const u8 *s, int l, bool r/*=false*/, bool a/*=false*/) +{ + Stop(); + if(!play_buffer[0]) return false; + GuiSoundDecoder *newDecoder = GuiSoundDecoder::GetDecoder(s, l, a); + if(!newDecoder && r) newDecoder = GuiSoundDecoderRAW::Create(s, l, a); + if(newDecoder) + { + delete decoder; + decoder = newDecoder; + return true; + } + else if(a) + delete [] s; + return false; } -GuiSound::GuiSound(const char *p, int v/*=100*/) { - if (GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL) { - LWP_CreateThread(&GuiSoundDecoderThreadHandle,GuiSoundDecoderThread,NULL,NULL,32*1024,80); - } - voice = -1; - play_buffer[0] = (u8*)memalign(32, BUFFER_SIZE*3); // tripple-buffer first is played - play_buffer[1] = play_buffer[0] + BUFFER_SIZE; // second is waiting - play_buffer[2] = play_buffer[1] + BUFFER_SIZE; // third is decoding - buffer_nr = 0; // current playbuffer - buffer_pos = 0; // current idx to write in buffer - buffer_ready = false; - buffer_eof = false; - loop = false; // play looped - volume = v; // volume - decoder = NULL; - if (play_buffer[0]) // playbuffer ok - Load(p); +GuiSound::GuiSound(const char *p, int v/*=100*/) +{ + if(GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL) + { + LWP_CreateThread(&GuiSoundDecoderThreadHandle,GuiSoundDecoderThread,NULL,NULL,32*1024,80); + } + voice = -1; + play_buffer[0] = (u8*)memalign(32, BUFFER_SIZE*3); // tripple-buffer first is played + play_buffer[1] = play_buffer[0] + BUFFER_SIZE; // second is waiting + play_buffer[2] = play_buffer[1] + BUFFER_SIZE; // third is decoding + buffer_nr = 0; // current playbuffer + buffer_pos = 0; // current idx to write in buffer + buffer_ready = false; + buffer_eof = false; + loop = false; // play looped + volume = v; // volume + decoder = NULL; + if(play_buffer[0]) // playbuffer ok + Load(p); } -bool GuiSound::Load(const char *p) { - Stop(); // stop playing - if (!play_buffer[0]) return false; +bool GuiSound::Load(const char *p) +{ + Stop(); // stop playing + if(!play_buffer[0]) return false; + + bool ret = false; + voice = -2; // -2 marks loading from file + u32 filesize = 0; + u8 *buffer = NULL; + size_t result; - bool ret = false; - voice = -2; // -2 marks loading from file - u32 filesize = 0; - u8 *buffer = NULL; - size_t result; + FILE * pFile = fopen (p, "rb"); + if(pFile) + { + // get file size: + fseek (pFile , 0 , SEEK_END); + filesize = ftell (pFile); + fseek (pFile , 0 , SEEK_SET); - FILE * pFile = fopen (p, "rb"); - if (pFile) { - // get file size: - fseek (pFile , 0 , SEEK_END); - filesize = ftell (pFile); - fseek (pFile , 0 , SEEK_SET); - - // allocate memory to contain the whole file: - buffer = new(std::nothrow) u8[filesize]; - if (buffer) { - // copy the file into the buffer: - result = fread (buffer, 1, filesize, pFile); - if (result == filesize) - ret= Load(buffer, filesize, false, true); - else - delete [] buffer; - } - fclose (pFile); - } - return ret; + // allocate memory to contain the whole file: + buffer = new(std::nothrow) u8[filesize]; + if (buffer) + { + // copy the file into the buffer: + result = fread (buffer, 1, filesize, pFile); + if (result == filesize) + ret= Load(buffer, filesize, false, true); + else + delete [] buffer; + } + fclose (pFile); + } + return ret; } /** * Destructor for the GuiSound class. */ -GuiSound::~GuiSound() { - if (!loop) while (voice >= 0) usleep(50); - Stop(); - if (--GuiSoundCount == 0 && GuiSoundDecoderThreadHandle != LWP_THREAD_NULL) { - GuiSoundDecoderThreadRunning = false; - LWP_JoinThread(GuiSoundDecoderThreadHandle,NULL); - GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; - } - delete decoder; - free(play_buffer[0]); +GuiSound::~GuiSound() +{ + if(!loop) while(voice >= 0) usleep(50); + Stop(); + if(--GuiSoundCount == 0 && GuiSoundDecoderThreadHandle != LWP_THREAD_NULL) + { + GuiSoundDecoderThreadRunning = false; + LWP_JoinThread(GuiSoundDecoderThreadHandle,NULL); + GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; + } + delete decoder; + free(play_buffer[0]); } -void GuiSound::Play() { - Stop(); // stop playing if it played - if (!play_buffer[0]) return; - if (!decoder) return; // no decoder or no play_buffer -> no playing - // initialize the buffer - buffer_nr = 0; // allways starts with buffer 0 - buffer_pos = 0; // reset position - buffer_ready = false; - buffer_eof = false; - decoder->Rewind(); // play from begin - DecoderCallback(); // fill first buffer; - if (!buffer_ready || buffer_eof) // if first buffer not ready -> no play - return; - voice = ASND_GetFirstUnusedVoice(); - if (voice >= 0) { - s32 vol = (255*volume)/100; - s32 format = decoder->GetFormat(); - s32 samplerate = decoder->GetSampleRate(); - s32 first_pos = buffer_pos; - // switch to next buffer - buffer_nr = 1; - buffer_pos = 0; - buffer_ready = false; - buffer_eof = false; - DecoderCallback(); // fill second buffer; - GuiSoundPlayer[voice] = this; // activate Callbacks for this voice - // Play the voice - ASND_SetVoice(voice, format, samplerate, 0, play_buffer[0], first_pos, vol, vol, GuiSoundPlayerCallback); - } +void GuiSound::Play() +{ + Stop(); // stop playing if it played + if(!play_buffer[0]) return; + if(!decoder) return; // no decoder or no play_buffer -> no playing + // initialize the buffer + buffer_nr = 0; // allways starts with buffer 0 + buffer_pos = 0; // reset position + buffer_ready = false; + buffer_eof = false; + decoder->Rewind(); // play from begin + DecoderCallback(); // fill first buffer; + if(!buffer_ready || buffer_eof) // if first buffer not ready -> no play + return; + voice = ASND_GetFirstUnusedVoice(); + if(voice >= 0) + { + s32 vol = (255*volume)/100; + s32 format = decoder->GetFormat(); + s32 samplerate = decoder->GetSampleRate(); + s32 first_pos = buffer_pos; + // switch to next buffer + buffer_nr = 1; + buffer_pos = 0; + buffer_ready = false; + buffer_eof = false; + DecoderCallback(); // fill second buffer; + GuiSoundPlayer[voice] = this; // activate Callbacks for this voice + // Play the voice + ASND_SetVoice(voice, format, samplerate, 0, play_buffer[0], first_pos, vol, vol, GuiSoundPlayerCallback); + } } /* int GuiSound::PlayOggFile(char * path) @@ -305,86 +335,106 @@ int GuiSound::PlayOggFile(char * path) return 1; } */ -void GuiSound::Stop() { - if (voice < 0) return ; - GuiSoundPlayer[voice] = NULL; // disable Callbacks - SND_StopVoice(voice); - voice = -1; +void GuiSound::Stop() +{ + if(voice < 0) return ; + GuiSoundPlayer[voice] = NULL; // disable Callbacks + SND_StopVoice(voice); + voice = -1; } -void GuiSound::Pause() { - if (voice < 0) return ; - ASND_PauseVoice(voice, 1); +void GuiSound::Pause() +{ + if(voice < 0) return ; + ASND_PauseVoice(voice, 1); } -void GuiSound::Resume() { - if (voice < 0) return ; - ASND_PauseVoice(voice, 0); +void GuiSound::Resume() +{ + if(voice < 0) return ; + ASND_PauseVoice(voice, 0); } -bool GuiSound::IsPlaying() { - return voice >= 0; +bool GuiSound::IsPlaying() +{ + return voice >= 0; } -void GuiSound::SetVolume(int vol) { - volume = vol; - if (voice < 0) return ; - int newvol = 255*(volume/100.0); - ASND_ChangeVolumeVoice(voice, newvol, newvol); +void GuiSound::SetVolume(int vol) +{ + volume = vol; + if(voice < 0) return ; + int newvol = 255*(volume/100.0); + ASND_ChangeVolumeVoice(voice, newvol, newvol); } -void GuiSound::SetLoop(bool l) { - loop = l; +void GuiSound::SetLoop(bool l) +{ + loop = l; } -void GuiSound::DecoderCallback() { - if (buffer_ready || buffer_eof) // if buffer ready or EOF -> nothing - return; - bool error=false; - while (buffer_pos < BUFFER_SIZE) { - int ret = decoder->Read(&play_buffer[buffer_nr][buffer_pos], BUFFER_SIZE-buffer_pos); - if (ret > 0) - buffer_pos += ret; // ok -> fill the buffer more - else if (ret == 0) { // EOF from decoder - if (loop) - decoder->Rewind(); // if loop -> rewind and fill the buffer more - else if (buffer_pos) - break; // has data in buffer -> play the buffer - else - buffer_eof = true; // no data in buffer -> return EOF - return; - } else if (ret < 0) { // an ERROR - if (buffer_pos) - break; // has data in buffer -> play the buffer - else if (loop) { - if (!error) { // if no prev error - decoder->Rewind(); // if loop -> rewind - error = true; // set error-state - continue; // and fill the buffer more - } - buffer_eof = true; // has prev error -> error in first block -> return EOF - return; - } else { - buffer_eof = true; // no loop -> return EOF - return; - } - } - error = false; // clear error-state - } - buffer_ready = true; +void GuiSound::DecoderCallback() +{ + if(buffer_ready || buffer_eof) // if buffer ready or EOF -> nothing + return; + bool error=false; + while(buffer_pos < BUFFER_SIZE) + { + int ret = decoder->Read(&play_buffer[buffer_nr][buffer_pos], BUFFER_SIZE-buffer_pos); + if(ret > 0) + buffer_pos += ret; // ok -> fill the buffer more + else if(ret == 0) // EOF from decoder + { + if(loop) + decoder->Rewind(); // if loop -> rewind and fill the buffer more + else if(buffer_pos) + break; // has data in buffer -> play the buffer + else + buffer_eof = true; // no data in buffer -> return EOF + return; + } + else if(ret < 0) // an ERROR + { + if(buffer_pos) + break; // has data in buffer -> play the buffer + else if(loop) + { + if(!error) // if no prev error + { + decoder->Rewind(); // if loop -> rewind + error = true; // set error-state + continue; // and fill the buffer more + } + buffer_eof = true; // has prev error -> error in first block -> return EOF + return; + } + else + { + buffer_eof = true; // no loop -> return EOF + return; + } + } + error = false; // clear error-state + } + buffer_ready = true; } -void GuiSound::PlayerCallback() { - if (buffer_eof) { // if EOF - if (ASND_TestPointer(voice, play_buffer[(buffer_nr+2)%3])==0) // test prev. Buffer - Stop(); - } else if (buffer_ready) { // if buffer ready - if (ASND_AddVoice(voice, play_buffer[buffer_nr], buffer_pos)==SND_OK) { // add buffer - // next buffer - buffer_nr = (buffer_nr+1)%3; - buffer_pos = 0; - buffer_ready= false; - buffer_eof = false; - } - } +void GuiSound::PlayerCallback() +{ + if(buffer_eof) // if EOF + { + if(ASND_TestPointer(voice, play_buffer[(buffer_nr+2)%3])==0) // test prev. Buffer + Stop(); + } + else if(buffer_ready) // if buffer ready + { + if(ASND_AddVoice(voice, play_buffer[buffer_nr], buffer_pos)==SND_OK) // add buffer + { + // next buffer + buffer_nr = (buffer_nr+1)%3; + buffer_pos = 0; + buffer_ready= false; + buffer_eof = false; + } + } } diff --git a/source/libwiigui/gui_sound_decoder.h b/source/libwiigui/gui_sound_decoder.h index 1048ea11..dd62bea3 100644 --- a/source/libwiigui/gui_sound_decoder.h +++ b/source/libwiigui/gui_sound_decoder.h @@ -19,76 +19,86 @@ class GuiSoundDecoder; typedef GuiSoundDecoder *(*GuiSoundDecoderCreate)(const u8 * snd, u32 len, bool snd_is_allocated); -class GuiSoundDecoder { +class GuiSoundDecoder +{ protected: - GuiSoundDecoder() {}; // Constructors must protected so it can create only with Init(...); + GuiSoundDecoder(){}; // Constructors must protected so it can create only with Init(...); public: - virtual ~GuiSoundDecoder() {}; - // begin API - // --------- - // each Decoder must have an own static Create(...) fnc - // static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated); - virtual s32 GetFormat()=0; - virtual s32 GetSampleRate()=0; - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - virtual int Read(u8 * buffer, int buffer_size)=0; - // set the stream to the start - virtual int Rewind()=0; - // ------- - // end API - - - struct DecoderListEntry { - GuiSoundDecoderCreate fnc; - DecoderListEntry *next; - }; - static DecoderListEntry &RegisterDecoder(DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc); - static GuiSoundDecoder *GetDecoder(const u8 * snd, u32 len, bool snd_is_allocated); + virtual ~GuiSoundDecoder(){}; + // begin API + // --------- + // each Decoder must have an own static Create(...) fnc + // static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated); + virtual s32 GetFormat()=0; + virtual s32 GetSampleRate()=0; + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + virtual int Read(u8 * buffer, int buffer_size)=0; + // set the stream to the start + virtual int Rewind()=0; + // ------- + // end API + + + struct DecoderListEntry + { + GuiSoundDecoderCreate fnc; + DecoderListEntry *next; + }; + static DecoderListEntry &RegisterDecoder(DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc); + static GuiSoundDecoder *GetDecoder(const u8 * snd, u32 len, bool snd_is_allocated); private: - static DecoderListEntry *DecoderList; - GuiSoundDecoder(GuiSoundDecoder&); // no copy + static DecoderListEntry *DecoderList; + GuiSoundDecoder(GuiSoundDecoder&); // no copy }; #define BIG_ENDIAN_HOST 1 // Wii PPC is a Big-Endian-Host #if BIG_ENDIAN_HOST -inline uint16_t be16(const uint8_t *p8) { - return *((uint16_t*)p8); +inline uint16_t be16(const uint8_t *p8) +{ + return *((uint16_t*)p8); } -inline uint32_t be32(const uint8_t *p8) { - return *((uint32_t*)p8); +inline uint32_t be32(const uint8_t *p8) +{ + return *((uint32_t*)p8); } -inline uint16_t le16(const uint8_t *p8) { - uint16_t ret = p8[1]<<8 | p8[0]; - return ret; +inline uint16_t le16(const uint8_t *p8) +{ + uint16_t ret = p8[1]<<8 | p8[0]; + return ret; } -inline uint32_t le32(const uint8_t *p8) { - uint32_t ret = p8[3]<<24 | p8[2]<<16 | p8[1]<<8 | p8[0]; - return ret; +inline uint32_t le32(const uint8_t *p8) +{ + uint32_t ret = p8[3]<<24 | p8[2]<<16 | p8[1]<<8 | p8[0]; + return ret; } #elif LITTLE_ENDIAN_HOST -inline uint16_t be16(const uint8_t *p8) { - uint16_t ret = p8[0]<<8 | p8[1]; - return ret; +inline uint16_t be16(const uint8_t *p8) +{ + uint16_t ret = p8[0]<<8 | p8[1]; + return ret; } -inline uint32_t be32(const uint8_t *p8) { - uint32_t ret = p8[0]<<24 | p8[1]<<16 | p8[2]<<8 | p8[3]; - return ret; +inline uint32_t be32(const uint8_t *p8) +{ + uint32_t ret = p8[0]<<24 | p8[1]<<16 | p8[2]<<8 | p8[3]; + return ret; } -inline uint16_t le16(const uint8_t *p8) { - return *((uint16_t*)p8); +inline uint16_t le16(const uint8_t *p8) +{ + return *((uint16_t*)p8); } -inline uint32_t le32(const uint8_t *p8) { - return *((uint32_t*)p8); +inline uint32_t le32(const uint8_t *p8) +{ + return *((uint32_t*)p8); } #else -#error "BIG_ENDIAN_HOST or LITTLE_ENDIAN_HOST not setted" + #error "BIG_ENDIAN_HOST or LITTLE_ENDIAN_HOST not setted" #endif /* XXX_ENDIAN_HOST */ #define be16inc(p8) (p8+=2, be16(p8-2)) diff --git a/source/libwiigui/gui_sound_decoder_aiff.cpp b/source/libwiigui/gui_sound_decoder_aiff.cpp index ba393804..688ceadb 100644 --- a/source/libwiigui/gui_sound_decoder_aiff.cpp +++ b/source/libwiigui/gui_sound_decoder_aiff.cpp @@ -24,129 +24,142 @@ # define UnsignedToFloat(u) (((double)((long)(u - 2147483647L - 1))) + 2147483648.0) -static double ConvertFromIeeeExtended(const u8* bytes) { - double f; - int expon; - u32 hiMant, loMant; +static double ConvertFromIeeeExtended(const u8* bytes) +{ + double f; + int expon; + u32 hiMant, loMant; - expon = ((bytes[0] & 0x7F) << 8) | (bytes[1] & 0xFF); - hiMant = ((unsigned long)(bytes[2] & 0xFF) << 24) - | ((unsigned long)(bytes[3] & 0xFF) << 16) - | ((unsigned long)(bytes[4] & 0xFF) << 8) - | ((unsigned long)(bytes[5] & 0xFF)); - loMant = ((unsigned long)(bytes[6] & 0xFF) << 24) - | ((unsigned long)(bytes[7] & 0xFF) << 16) - | ((unsigned long)(bytes[8] & 0xFF) << 8) - | ((unsigned long)(bytes[9] & 0xFF)); + expon = ((bytes[0] & 0x7F) << 8) | (bytes[1] & 0xFF); + hiMant = ((unsigned long)(bytes[2] & 0xFF) << 24) + | ((unsigned long)(bytes[3] & 0xFF) << 16) + | ((unsigned long)(bytes[4] & 0xFF) << 8) + | ((unsigned long)(bytes[5] & 0xFF)); + loMant = ((unsigned long)(bytes[6] & 0xFF) << 24) + | ((unsigned long)(bytes[7] & 0xFF) << 16) + | ((unsigned long)(bytes[8] & 0xFF) << 8) + | ((unsigned long)(bytes[9] & 0xFF)); - if (expon == 0 && hiMant == 0 && loMant == 0) - f = 0; - else { - if (expon == 0x7FFF) - f = HUGE_VAL; - else { - expon -= 16383; - f = ldexp(UnsignedToFloat(hiMant), expon-=31); - f += ldexp(UnsignedToFloat(loMant), expon-=32); - } - } + if (expon == 0 && hiMant == 0 && loMant == 0) + f = 0; + else + { + if (expon == 0x7FFF) + f = HUGE_VAL; + else + { + expon -= 16383; + f = ldexp(UnsignedToFloat(hiMant), expon-=31); + f += ldexp(UnsignedToFloat(loMant), expon-=32); + } + } - if (bytes[0] & 0x80) - return -f; - else - return f; + if (bytes[0] & 0x80) + return -f; + else + return f; } // ------ -class GuiSoundDecoderAIFF : public GuiSoundDecoder { +class GuiSoundDecoderAIFF : public GuiSoundDecoder +{ protected: - GuiSoundDecoderAIFF(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - length =len; - is_allocated = snd_is_allocated; - is_running = false; + GuiSoundDecoderAIFF(const u8 * snd, u32 len, bool snd_is_allocated) + { + sound = snd; + length =len; + is_allocated = snd_is_allocated; + is_running = false; - const u8 *in_ptr = sound; + const u8 *in_ptr = sound; - if (be32inc(in_ptr) != 0x464F524D /*'FORM'*/) throw("No FORM chunk"); - if (be32inc(in_ptr)+8 != len) throw("wrong Size"); - if (be32inc(in_ptr) != 0x41494646 /*'AIFF'*/) throw("No AIFF chunk"); + if(be32inc(in_ptr) != 0x464F524D /*'FORM'*/) throw("No FORM chunk"); + if(be32inc(in_ptr)+8 != len) throw("wrong Size"); + if(be32inc(in_ptr) != 0x41494646 /*'AIFF'*/) throw("No AIFF chunk"); - while (in_ptr+8 < sound+len) { - u32 chunk_id = be32inc(in_ptr); - u32 chunk_size = be32inc(in_ptr); - const u8 *chunk_start = in_ptr; - switch (chunk_id) { - case 0x434F4D4D /*'COMM'*/: - channelCount = be16inc(in_ptr); - in_ptr += 4; // skip numSampleFrames - bytePerSample = (be16inc(in_ptr)+7)/8; - if (bytePerSample < 1 && bytePerSample > 2) throw("wrong bits per Sample"); - sampleRate = ConvertFromIeeeExtended(in_ptr); - break; - case 0x53534E44 /*'SSND'*/: - pcm_start = in_ptr + 8; - pcm_end = chunk_start+chunk_size; - break; - } - in_ptr = chunk_start+chunk_size; - } - currentPos = pcm_start; - } + while(in_ptr+8 < sound+len) + { + u32 chunk_id = be32inc(in_ptr); + u32 chunk_size = be32inc(in_ptr); + const u8 *chunk_start = in_ptr; + switch(chunk_id) + { + case 0x434F4D4D /*'COMM'*/: + channelCount = be16inc(in_ptr); + in_ptr += 4; // skip numSampleFrames + bytePerSample = (be16inc(in_ptr)+7)/8; + if(bytePerSample < 1 && bytePerSample > 2) throw("wrong bits per Sample"); + sampleRate = ConvertFromIeeeExtended(in_ptr); + break; + case 0x53534E44 /*'SSND'*/: + pcm_start = in_ptr + 8; + pcm_end = chunk_start+chunk_size; + break; + } + in_ptr = chunk_start+chunk_size; + } + currentPos = pcm_start; + } public: - ~GuiSoundDecoderAIFF() { - while (is_running) usleep(50); - if (is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - if (snd && len>12 && snd[0]=='F' && snd[1]=='O' && snd[2]=='R' && snd[3]=='M' - && snd[8]=='A' && snd[9]=='I' && snd[10]=='F' && snd[11]=='F') - return new GuiSoundDecoderAIFF(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() { - if (bytePerSample == 2) - return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - else - return channelCount==2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; - } - s32 GetSampleRate() { - return sampleRate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) { - if (currentPos >= pcm_end) - return 0; // EOF + ~GuiSoundDecoderAIFF() + { + while(is_running) usleep(50); + if(is_allocated) delete [] sound; + } + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) + { + if(snd && len>12 && snd[0]=='F' && snd[1]=='O' && snd[2]=='R' && snd[3]=='M' + && snd[8]=='A' && snd[9]=='I' && snd[10]=='F' && snd[11]=='F') + return new GuiSoundDecoderAIFF(snd, len, snd_is_allocated); + return NULL; + } + s32 GetFormat() + { + if(bytePerSample == 2) + return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + else + return channelCount==2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; + } + s32 GetSampleRate() + { + return sampleRate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) + { + if(currentPos >= pcm_end) + return 0; // EOF - is_running = true; - if (currentPos + buffer_size > pcm_end) - buffer_size = pcm_end-currentPos; - memcpy(buffer, currentPos, buffer_size); - currentPos += buffer_size; - is_running = false; - return buffer_size; - } - int Rewind() { - while (is_running) usleep(50); - currentPos = pcm_start; - return 0; - } + is_running = true; + if(currentPos + buffer_size > pcm_end) + buffer_size = pcm_end-currentPos; + memcpy(buffer, currentPos, buffer_size); + currentPos += buffer_size; + is_running = false; + return buffer_size; + } + int Rewind() + { + while(is_running) usleep(50); + currentPos = pcm_start; + return 0; + } private: - const u8 *sound; - u32 length; - bool is_allocated; - bool is_running; + const u8 *sound; + u32 length; + bool is_allocated; + bool is_running; - u32 sampleRate; - u16 channelCount; - u16 bytePerSample; - const u8 *pcm_start; - const u8 *pcm_end; - const u8 *currentPos; + u32 sampleRate; + u16 channelCount; + u16 bytePerSample; + const u8 *pcm_start; + const u8 *pcm_end; + const u8 *currentPos; }; REGISTER_GUI_SOUND_DECODER(GuiSoundDecoderAIFF); diff --git a/source/libwiigui/gui_sound_decoder_bns.cpp b/source/libwiigui/gui_sound_decoder_bns.cpp index e1d7f1c7..e21029bd 100644 --- a/source/libwiigui/gui_sound_decoder_bns.cpp +++ b/source/libwiigui/gui_sound_decoder_bns.cpp @@ -21,210 +21,236 @@ -class chanel_t { +class chanel_t +{ public: - void Reset() { - currentPos = startPos; - hist1 = hist2 = 0; - } - int DecodeNextBlock() { - int Offset = 0; - if (currentPos == loopStart) { - loop_hist1 = hist1; - loop_hist2 = hist2; - } - if (loop && currentPos >= endPos) { - currentPos = loopStart; - hist1 = loop_hist1; - hist2 = loop_hist2; - Offset = loopOffset; + void Reset() + { + currentPos = startPos; + hist1 = hist2 = 0; + } + int DecodeNextBlock() + { + int Offset = 0; + if(currentPos == loopStart) + { + loop_hist1 = hist1; + loop_hist2 = hist2; + } + if(loop && currentPos >= endPos) + { + currentPos = loopStart; + hist1 = loop_hist1; + hist2 = loop_hist2; + Offset = loopOffset; - } + } + + if(currentPos+8 <= endPos) + { + u16 index = (*currentPos >> 4) & 0x07; + s32 scale = 1 << (*currentPos++ & 0x0F); + for(int i = 0; i < 14; i+=2) + { + nibbles[i] = ((s8)*currentPos) >> 4; + nibbles[i+1] = ((s8)((*currentPos++) << 4)) >> 4; + } + for(int i = 0; i < 14; ++i) + { + s32 sample = (scale * nibbles[i])<<11; + sample += coEfficients[index * 2] * hist1; + sample += coEfficients[index * 2 + 1] * hist2; + sample += 1024; + sample = sample >> 11; + if(sample > 32767) + sample = 32767; + else if(sample < -32768) + sample = -32768; + pcm[i] = sample; - if (currentPos+8 <= endPos) { - u16 index = (*currentPos >> 4) & 0x07; - s32 scale = 1 << (*currentPos++ & 0x0F); - for (int i = 0; i < 14; i+=2) { - nibbles[i] = ((s8)*currentPos) >> 4; - nibbles[i+1] = ((s8)((*currentPos++) << 4)) >> 4; - } - for (int i = 0; i < 14; ++i) { - s32 sample = (scale * nibbles[i])<<11; - sample += coEfficients[index * 2] * hist1; - sample += coEfficients[index * 2 + 1] * hist2; - sample += 1024; - sample = sample >> 11; - if (sample > 32767) - sample = 32767; - else if (sample < -32768) - sample = -32768; - pcm[i] = sample; - - hist2 = hist1; - hist1 = sample; - } - return Offset; - } - return -1; - } - - const u8* startPos; - const u8* endPos; - const u8* currentPos; - s16 coEfficients[16]; - s16 nibbles[14]; - s16 pcm[14]; - s16 hist1; - s16 hist2; - bool loop; - const u8* loopStart; - u16 loopOffset; - s16 loop_hist1; - s16 loop_hist2; + hist2 = hist1; + hist1 = sample; + } + return Offset; + } + return -1; + } + + const u8* startPos; + const u8* endPos; + const u8* currentPos; + s16 coEfficients[16]; + s16 nibbles[14]; + s16 pcm[14]; + s16 hist1; + s16 hist2; + bool loop; + const u8* loopStart; + u16 loopOffset; + s16 loop_hist1; + s16 loop_hist2; }; -class GuiSoundDecoderBNS : public GuiSoundDecoder { +class GuiSoundDecoderBNS : public GuiSoundDecoder +{ protected: - GuiSoundDecoderBNS(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - is_running = false; - is_allocated = snd_is_allocated; + GuiSoundDecoderBNS(const u8 * snd, u32 len, bool snd_is_allocated) + { + sound = snd; + is_running = false; + is_allocated = snd_is_allocated; - const u8 *in_ptr = sound; + const u8 *in_ptr = sound; + + ///////////////// + // READ HEADER // + ///////////////// + if(be32inc(in_ptr) != 0x424E5320 /*'BNS '*/) throw("Not a BNS"); - ///////////////// - // READ HEADER // - ///////////////// - if (be32inc(in_ptr) != 0x424E5320 /*'BNS '*/) throw("Not a BNS"); + in_ptr += 4; // skip 4 byte - in_ptr += 4; // skip 4 byte + u32 bnssize = be32inc(in_ptr); + if(bnssize != len) throw("Wrong size"); - u32 bnssize = be32inc(in_ptr); - if (bnssize != len) throw("Wrong size"); + in_ptr += 4; // skip unknown1 - in_ptr += 4; // skip unknown1 + const u8* infoStart = sound + be32inc(in_ptr); + in_ptr+=4; // skip const u8* infoEnd = infoStart + be32inc(in_ptr); - const u8* infoStart = sound + be32inc(in_ptr); - in_ptr+=4; // skip const u8* infoEnd = infoStart + be32inc(in_ptr); + channel[0].startPos = sound + be32inc(in_ptr) + 8; + channel[0].endPos = channel[0].startPos + be32inc(in_ptr) - 8; - channel[0].startPos = sound + be32inc(in_ptr) + 8; - channel[0].endPos = channel[0].startPos + be32inc(in_ptr) - 8; + /////////////// + // READ INFO // + /////////////// + in_ptr = infoStart + 8; // skip 'INFO' and Infosize + + in_ptr++; // skip u8 codeType = *in_ptr++; - /////////////// - // READ INFO // - /////////////// - in_ptr = infoStart + 8; // skip 'INFO' and Infosize + channel[0].loop = channel[1].loop = *in_ptr++; // u8 loopFlag; + + channelCount = *in_ptr++; - in_ptr++; // skip u8 codeType = *in_ptr++; + in_ptr++; // skip unknown byte - channel[0].loop = channel[1].loop = *in_ptr++; // u8 loopFlag; + sampleRate = be16inc(in_ptr); - channelCount = *in_ptr++; + in_ptr+=2; // skip unknown word + + u32 loopStart = be32inc(in_ptr); + channel[0].loopStart = channel[0].startPos + ((loopStart/14)*8);//LoopPos to BlockStart + channel[1].loopStart = channel[1].startPos + ((loopStart/14)*8); + channel[0].loopOffset = channel[1].loopOffset = loopStart%14; - in_ptr++; // skip unknown byte + in_ptr+=4; // skip u32 SampleCount = be32inc(in_ptr); - sampleRate = be16inc(in_ptr); + in_ptr+=24; // skip unknown Bytes - in_ptr+=2; // skip unknown word + if(channelCount == 2) + { + in_ptr+=4; // skip unknown long + u32 ChannelSplit = be32inc(in_ptr); - u32 loopStart = be32inc(in_ptr); - channel[0].loopStart = channel[0].startPos + ((loopStart/14)*8);//LoopPos to BlockStart - channel[1].loopStart = channel[1].startPos + ((loopStart/14)*8); - channel[0].loopOffset = channel[1].loopOffset = loopStart%14; + in_ptr+=8; // skip 2x unknown long + + channel[1].endPos = channel[0].endPos; + channel[0].endPos = channel[1].startPos = channel[0].startPos + ChannelSplit; - in_ptr+=4; // skip u32 SampleCount = be32inc(in_ptr); - - in_ptr+=24; // skip unknown Bytes - - if (channelCount == 2) { - in_ptr+=4; // skip unknown long - u32 ChannelSplit = be32inc(in_ptr); - - in_ptr+=8; // skip 2x unknown long - - channel[1].endPos = channel[0].endPos; - channel[0].endPos = channel[1].startPos = channel[0].startPos + ChannelSplit; - - channel[1].loopStart = channel[1].startPos + (channel[0].loopStart - channel[0].startPos); - } - for (int a = 0; a < 16; a++) { - channel[0].coEfficients[a] = (s16)be16inc(in_ptr); - } - if (channelCount == 2) { - in_ptr+=16; // skip 16 byte - for (int a = 0; a < 16; a++) { - channel[1].coEfficients[a] = (s16)be16inc(in_ptr); - } - } - channel[0].Reset(); - channel[1].Reset(); - currentBlockPos = 14; + channel[1].loopStart = channel[1].startPos + (channel[0].loopStart - channel[0].startPos); + } + for (int a = 0; a < 16; a++) + { + channel[0].coEfficients[a] = (s16)be16inc(in_ptr); + } + if(channelCount == 2) + { + in_ptr+=16; // skip 16 byte + for (int a = 0; a < 16; a++) + { + channel[1].coEfficients[a] = (s16)be16inc(in_ptr); + } + } + channel[0].Reset(); + channel[1].Reset(); + currentBlockPos = 14; } public: - ~GuiSoundDecoderBNS() { - while (is_running) usleep(50); - if (is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - if (snd && len>4 && snd[0]=='B' && snd[1]=='N' && snd[2]=='S' && snd[3]==' ') - return new GuiSoundDecoderBNS(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() { - return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - } - s32 GetSampleRate() { - return sampleRate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) { - is_running = true; - u8 *write_pos = buffer; - u8 *write_end = buffer+buffer_size; - - for (;;) { - if (currentBlockPos >= 14) { - int Offset = channel[0].DecodeNextBlock(); - if (Offset<0 || (channelCount == 2 && channel[1].DecodeNextBlock()<0) ) { - is_running = false; - return write_pos-buffer; - } - currentBlockPos = Offset; - } - for (;currentBlockPos < 14; ++currentBlockPos) { - if (write_pos >= write_end) { - is_running = false; - return write_pos-buffer; - } - *((s16*)write_pos) = channel[0].pcm[currentBlockPos]; - write_pos+=2; - if (channelCount==2) { // stereo - *((s16*)write_pos) = channel[1].pcm[currentBlockPos]; - write_pos+=2; - } - } - } - is_running = false; - return 0; - } - int Rewind() { - channel[0].Reset(); - channel[1].Reset(); - currentBlockPos = 14; - return 0; - } + ~GuiSoundDecoderBNS() + { + while(is_running) usleep(50); + if(is_allocated) delete [] sound; + } + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) + { + if(snd && len>4 && snd[0]=='B' && snd[1]=='N' && snd[2]=='S' && snd[3]==' ') + return new GuiSoundDecoderBNS(snd, len, snd_is_allocated); + return NULL; + } + s32 GetFormat() + { + return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + } + s32 GetSampleRate() + { + return sampleRate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) + { + is_running = true; + u8 *write_pos = buffer; + u8 *write_end = buffer+buffer_size; + + for(;;) + { + if(currentBlockPos >= 14) + { + int Offset = channel[0].DecodeNextBlock(); + if(Offset<0 || (channelCount == 2 && channel[1].DecodeNextBlock()<0) ) + { + is_running = false; + return write_pos-buffer; + } + currentBlockPos = Offset; + } + for(;currentBlockPos < 14; ++currentBlockPos) + { + if(write_pos >= write_end) + { + is_running = false; + return write_pos-buffer; + } + *((s16*)write_pos) = channel[0].pcm[currentBlockPos]; + write_pos+=2; + if(channelCount==2) // stereo + { + *((s16*)write_pos) = channel[1].pcm[currentBlockPos]; + write_pos+=2; + } + } + } + is_running = false; + return 0; + } + int Rewind() + { + channel[0].Reset(); + channel[1].Reset(); + currentBlockPos = 14; + return 0; + } private: - const u8 *sound; - bool is_allocated; - bool is_running; - chanel_t channel[2]; - u16 currentBlockPos; - u16 channelCount; - u32 sampleRate; + const u8 *sound; + bool is_allocated; + bool is_running; + chanel_t channel[2]; + u16 currentBlockPos; + u16 channelCount; + u32 sampleRate; // u16 loopOffset; // u16 bytePerSample; // const u8 *soundDataStart; diff --git a/source/libwiigui/gui_sound_decoder_mpg.cpp b/source/libwiigui/gui_sound_decoder_mpg.cpp index 253e6e86..fa3031c8 100644 --- a/source/libwiigui/gui_sound_decoder_mpg.cpp +++ b/source/libwiigui/gui_sound_decoder_mpg.cpp @@ -22,15 +22,16 @@ #include "gui_sound_decoder.h" -static inline s16 FixedToShort(mad_fixed_t Fixed) { - /* Clipping */ - if (Fixed>=MAD_F_ONE) - return(SHRT_MAX); - if (Fixed<=-MAD_F_ONE) - return(-SHRT_MAX); +static inline s16 FixedToShort(mad_fixed_t Fixed) +{ + /* Clipping */ + if(Fixed>=MAD_F_ONE) + return(SHRT_MAX); + if(Fixed<=-MAD_F_ONE) + return(-SHRT_MAX); - Fixed=Fixed>>(MAD_F_FRACBITS-15); - return((s16)Fixed); + Fixed=Fixed>>(MAD_F_FRACBITS-15); + return((s16)Fixed); } #define ADMA_BUFFERSIZE (8192) @@ -38,155 +39,176 @@ static inline s16 FixedToShort(mad_fixed_t Fixed) { // http://www.fr-an.de/fragen/v06/02_01.htm -class GuiSoundDecoderMPG : public GuiSoundDecoder { +class GuiSoundDecoderMPG : public GuiSoundDecoder +{ protected: - GuiSoundDecoderMPG(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - length = len; - is_allocated = snd_is_allocated; - // Init mad-structures - mad_stream_init(&madStream); - mad_stream_buffer(&madStream, sound, length); - mad_frame_init(&madFrame); - mad_synth_init(&madSynth); - madSynthPcmPos = 0; - mad_timer_reset(&madTimer); - guardBuffer = NULL; - is_running = false; + GuiSoundDecoderMPG(const u8 * snd, u32 len, bool snd_is_allocated) + { + sound = snd; + length = len; + is_allocated = snd_is_allocated; + // Init mad-structures + mad_stream_init(&madStream); + mad_stream_buffer(&madStream, sound, length); + mad_frame_init(&madFrame); + mad_synth_init(&madSynth); + madSynthPcmPos = 0; + mad_timer_reset(&madTimer); + guardBuffer = NULL; + is_running = false; - // decode first Frame - if (DecodeFirstFrame()) { - mad_synth_finish(&madSynth); - mad_frame_finish(&madFrame); - mad_stream_finish(&madStream); - throw("Stream Error"); - } - } + // decode first Frame + if(DecodeFirstFrame()) + { + mad_synth_finish(&madSynth); + mad_frame_finish(&madFrame); + mad_stream_finish(&madStream); + throw("Stream Error"); + } + } public: - ~GuiSoundDecoderMPG() { - while (is_running) usleep(50); - mad_synth_finish(&madSynth); - mad_frame_finish(&madFrame); - mad_stream_finish(&madStream); - delete [] guardBuffer; - if (is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - struct mad_stream madStream; - struct mad_header madHeader; - mad_stream_init(&madStream); - mad_stream_buffer(&madStream, snd, len); - mad_header_init(&madHeader); - s32 ret = mad_header_decode(&madHeader, &madStream); - if (ret == 0 || madStream.error==MAD_ERROR_LOSTSYNC) { // LOSTSYNC in first call is ok - int i; - for (i=0; i<4 && mad_header_decode(&madHeader, &madStream)==0; i++); - if ( i == 4 ) { - mad_header_finish(&madHeader); - mad_stream_finish(&madStream); - return new GuiSoundDecoderMPG(snd, len, snd_is_allocated); - } - } - mad_header_finish(&madHeader); - mad_stream_finish(&madStream); - return NULL; - } - s32 GetFormat() { - return MAD_NCHANNELS(&madFrame.header)==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - } - s32 GetSampleRate() { - return madFrame.header.samplerate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) { - is_running = true; - if (MAD_NCHANNELS(&madFrame.header)==2) // stereo - buffer_size &= ~0x0003; // make size to a kind of 4 - else - buffer_size &= ~0x0001; // make size to a kind of 2 - u8 *write_pos = buffer; - u8 *write_end = buffer+buffer_size; + ~GuiSoundDecoderMPG() + { + while(is_running) usleep(50); + mad_synth_finish(&madSynth); + mad_frame_finish(&madFrame); + mad_stream_finish(&madStream); + delete [] guardBuffer; + if(is_allocated) delete [] sound; + } + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) + { + struct mad_stream madStream; + struct mad_header madHeader; + mad_stream_init(&madStream); + mad_stream_buffer(&madStream, snd, len); + mad_header_init(&madHeader); + s32 ret = mad_header_decode(&madHeader, &madStream); + if(ret == 0 || madStream.error==MAD_ERROR_LOSTSYNC) // LOSTSYNC in first call is ok + { + int i; + for(i=0; i<4 && mad_header_decode(&madHeader, &madStream)==0; i++); + if( i == 4 ) + { + mad_header_finish(&madHeader); + mad_stream_finish(&madStream); + return new GuiSoundDecoderMPG(snd, len, snd_is_allocated); + } + } + mad_header_finish(&madHeader); + mad_stream_finish(&madStream); + return NULL; + } + s32 GetFormat() + { + return MAD_NCHANNELS(&madFrame.header)==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + } + s32 GetSampleRate() + { + return madFrame.header.samplerate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) + { + is_running = true; + if(MAD_NCHANNELS(&madFrame.header)==2) // stereo + buffer_size &= ~0x0003; // make size to a kind of 4 + else + buffer_size &= ~0x0001; // make size to a kind of 2 + u8 *write_pos = buffer; + u8 *write_end = buffer+buffer_size; + + for(;;) + { + for(;madSynthPcmPos < madSynth.pcm.length; ++madSynthPcmPos) + { + if(write_pos >= write_end) + { + is_running = false; + return write_pos-buffer; + } + *((s16*)write_pos) = FixedToShort(madSynth.pcm.samples[0][madSynthPcmPos]); write_pos+=2; + if(MAD_NCHANNELS(&madFrame.header)==2) // stereo + { + *((s16*)write_pos) = FixedToShort(madSynth.pcm.samples[1][madSynthPcmPos]); write_pos+=2; + } + } - for (;;) { - for (;madSynthPcmPos < madSynth.pcm.length; ++madSynthPcmPos) { - if (write_pos >= write_end) { - is_running = false; - return write_pos-buffer; - } - *((s16*)write_pos) = FixedToShort(madSynth.pcm.samples[0][madSynthPcmPos]); - write_pos+=2; - if (MAD_NCHANNELS(&madFrame.header)==2) { // stereo - *((s16*)write_pos) = FixedToShort(madSynth.pcm.samples[1][madSynthPcmPos]); - write_pos+=2; - } - } - - madStream.error = MAD_ERROR_NONE; - if (mad_frame_decode(&madFrame,&madStream)) { - if (MAD_RECOVERABLE(madStream.error)) { - if (madStream.error!=MAD_ERROR_LOSTSYNC || !guardBuffer) - continue; - } else if (madStream.error==MAD_ERROR_BUFLEN) { - if (!guardBuffer) { - u32 guardLen = (madStream.bufend-madStream.next_frame); - guardBuffer = new(std::nothrow) u8[guardLen + MAD_BUFFER_GUARD]; - if (guardBuffer) { - memcpy(guardBuffer, madStream.next_frame, guardLen); - memset(guardBuffer+guardLen, 0, MAD_BUFFER_GUARD); - mad_stream_buffer(&madStream, guardBuffer, guardLen + MAD_BUFFER_GUARD); - continue; - } - } - } - break; - } - mad_timer_add(&madTimer,madFrame.header.duration); - mad_synth_frame(&madSynth,&madFrame); - madSynthPcmPos = 0; - } - is_running = false; - return write_pos-buffer; - } - int Rewind() { - while (is_running) usleep(50); - delete [] guardBuffer; - guardBuffer = NULL; - mad_stream_buffer(&madStream, sound, length); - mad_synth_finish(&madSynth); - mad_synth_init(&madSynth); - madSynthPcmPos = 0; - mad_timer_reset(&madTimer); - // decode first Frame - return DecodeFirstFrame(); - } + madStream.error = MAD_ERROR_NONE; + if(mad_frame_decode(&madFrame,&madStream)) + { + if(MAD_RECOVERABLE(madStream.error)) + { + if(madStream.error!=MAD_ERROR_LOSTSYNC || !guardBuffer) + continue; + } + else if(madStream.error==MAD_ERROR_BUFLEN) + { + if(!guardBuffer) + { + u32 guardLen = (madStream.bufend-madStream.next_frame); + guardBuffer = new(std::nothrow) u8[guardLen + MAD_BUFFER_GUARD]; + if(guardBuffer) + { + memcpy(guardBuffer, madStream.next_frame, guardLen); + memset(guardBuffer+guardLen, 0, MAD_BUFFER_GUARD); + mad_stream_buffer(&madStream, guardBuffer, guardLen + MAD_BUFFER_GUARD); + continue; + } + } + } + break; + } + mad_timer_add(&madTimer,madFrame.header.duration); + mad_synth_frame(&madSynth,&madFrame); + madSynthPcmPos = 0; + } + is_running = false; + return write_pos-buffer; + } + int Rewind() + { + while(is_running) usleep(50); + delete [] guardBuffer; guardBuffer = NULL; + mad_stream_buffer(&madStream, sound, length); + mad_synth_finish(&madSynth); + mad_synth_init(&madSynth); + madSynthPcmPos = 0; + mad_timer_reset(&madTimer); + // decode first Frame + return DecodeFirstFrame(); + } private: - int DecodeFirstFrame() { - for (;;) { - madStream.error = MAD_ERROR_NONE; - if (mad_frame_decode(&madFrame,&madStream)) { - if (MAD_RECOVERABLE(madStream.error)) - continue; - else - return -1; - } - mad_timer_add(&madTimer,madFrame.header.duration); - mad_synth_frame(&madSynth,&madFrame); - return 0; - } - } - const u8 *sound; - u32 length; - bool is_allocated; - struct mad_stream madStream; - struct mad_frame madFrame; - struct mad_synth madSynth; - u16 madSynthPcmPos; - mad_timer_t madTimer; - u8 *guardBuffer; - bool is_running; + int DecodeFirstFrame() + { + for(;;) + { + madStream.error = MAD_ERROR_NONE; + if(mad_frame_decode(&madFrame,&madStream)) + { + if(MAD_RECOVERABLE(madStream.error)) + continue; + else + return -1; + } + mad_timer_add(&madTimer,madFrame.header.duration); + mad_synth_frame(&madSynth,&madFrame); + return 0; + } + } + const u8 *sound; + u32 length; + bool is_allocated; + struct mad_stream madStream; + struct mad_frame madFrame; + struct mad_synth madSynth; + u16 madSynthPcmPos; + mad_timer_t madTimer; + u8 *guardBuffer; + bool is_running; }; REGISTER_GUI_SOUND_DECODER(GuiSoundDecoderMPG); diff --git a/source/libwiigui/gui_sound_decoder_ogg.cpp b/source/libwiigui/gui_sound_decoder_ogg.cpp index 7ac2962b..94b6ce7b 100644 --- a/source/libwiigui/gui_sound_decoder_ogg.cpp +++ b/source/libwiigui/gui_sound_decoder_ogg.cpp @@ -19,66 +19,76 @@ #include "gui_sound_decoder.h" -class GuiSoundDecoderOGG : public GuiSoundDecoder { +class GuiSoundDecoderOGG : public GuiSoundDecoder +{ protected: - GuiSoundDecoderOGG(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - is_allocated = snd_is_allocated; - ogg_fd = mem_open((char *)snd, len); - if (ogg_fd < 0) throw("mem open failed"); + GuiSoundDecoderOGG(const u8 * snd, u32 len, bool snd_is_allocated) + { + sound = snd; + is_allocated = snd_is_allocated; + ogg_fd = mem_open((char *)snd, len); + if(ogg_fd < 0) throw("mem open failed"); - if (ov_open((FILE*)&ogg_fd, &ogg_file, NULL, 0) < 0) { - mem_close(ogg_fd); - throw("ogg open failed"); - } - ogg_info = ov_info(&ogg_file, -1); - bitstream = 0; - is_running = false; + if (ov_open((FILE*)&ogg_fd, &ogg_file, NULL, 0) < 0) + { + mem_close(ogg_fd); + throw("ogg open failed"); + } + ogg_info = ov_info(&ogg_file, -1); + bitstream = 0; + is_running = false; } public: - ~GuiSoundDecoderOGG() { - while (is_running) usleep(50); - ov_clear(&ogg_file); - if (is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - if (snd && len>4 && snd[0]=='O' && snd[1]=='g' && snd[2]=='g' && snd[3]=='S') - return new GuiSoundDecoderOGG(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() { - return ogg_info->channels==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - } - s32 GetSampleRate() { - return ogg_info->rate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) { - is_running = true; - int ret = ov_read(&ogg_file, (char *)buffer, buffer_size, &bitstream); - if (ret < 0) { - /* error in the stream. Not a problem, just reporting it in - case we (the app) cares. In this case, we don't. */ - if (ret != OV_HOLE) - ret = 0; // we says EOF - } - is_running = false; - return ret; - } - int Rewind() { - return ov_time_seek(&ogg_file, 0); - } + ~GuiSoundDecoderOGG() + { + while(is_running) usleep(50); + ov_clear(&ogg_file); + if(is_allocated) delete [] sound; + } + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) + { + if(snd && len>4 && snd[0]=='O' && snd[1]=='g' && snd[2]=='g' && snd[3]=='S') + return new GuiSoundDecoderOGG(snd, len, snd_is_allocated); + return NULL; + } + s32 GetFormat() + { + return ogg_info->channels==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + } + s32 GetSampleRate() + { + return ogg_info->rate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) + { + is_running = true; + int ret = ov_read(&ogg_file, (char *)buffer, buffer_size, &bitstream); + if (ret < 0) + { + /* error in the stream. Not a problem, just reporting it in + case we (the app) cares. In this case, we don't. */ + if (ret != OV_HOLE) + ret = 0; // we says EOF + } + is_running = false; + return ret; + } + int Rewind() + { + return ov_time_seek(&ogg_file, 0); + } private: - const u8 *sound; - bool is_allocated; - int ogg_fd; - OggVorbis_File ogg_file; - vorbis_info *ogg_info; - int bitstream; - bool is_running; + const u8 *sound; + bool is_allocated; + int ogg_fd; + OggVorbis_File ogg_file; + vorbis_info *ogg_info; + int bitstream; + bool is_running; }; REGISTER_GUI_SOUND_DECODER(GuiSoundDecoderOGG); diff --git a/source/libwiigui/gui_sound_decoder_wav.cpp b/source/libwiigui/gui_sound_decoder_wav.cpp index 1819657d..234366d2 100644 --- a/source/libwiigui/gui_sound_decoder_wav.cpp +++ b/source/libwiigui/gui_sound_decoder_wav.cpp @@ -19,200 +19,219 @@ #include "gui_sound_decoder.h" -typedef struct { - u32 cueID; - u32 len; - u32 loops; +typedef struct +{ + u32 cueID; + u32 len; + u32 loops; }plst_t; -typedef struct { - const u8 *start; - const u8 *end; - u32 loops; +typedef struct +{ + const u8 *start; + const u8 *end; + u32 loops; }playlist_t; -class GuiSoundDecoderWAV : public GuiSoundDecoder { +class GuiSoundDecoderWAV : public GuiSoundDecoder +{ protected: - GuiSoundDecoderWAV(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - is_running = false; - is_allocated = snd_is_allocated; + GuiSoundDecoderWAV(const u8 * snd, u32 len, bool snd_is_allocated) + { + sound = snd; + is_running = false; + is_allocated = snd_is_allocated; - const u8 *in_ptr = sound; + const u8 *in_ptr = sound; + + if(be32inc(in_ptr) != 0x52494646 /*'RIFF' (WAV)*/) throw("Not a WAV"); - if (be32inc(in_ptr) != 0x52494646 /*'RIFF' (WAV)*/) throw("Not a WAV"); + u32 riffsize = le32inc(in_ptr); + if(riffsize > (len-8)) throw("Wrong size"); - u32 riffsize = le32inc(in_ptr); - if (riffsize > (len-8)) throw("Wrong size"); + if(be32inc(in_ptr) != 0x57415645 /*'WAVE'*/) throw("No WAVE-Tag"); - if (be32inc(in_ptr) != 0x57415645 /*'WAVE'*/) throw("No WAVE-Tag"); + if(be32inc(in_ptr) != 0x666D7420 /*'fmt '*/) throw("No fmt-Tag"); - if (be32inc(in_ptr) != 0x666D7420 /*'fmt '*/) throw("No fmt-Tag"); + u32 fmtLen = le32inc(in_ptr); - u32 fmtLen = le32inc(in_ptr); + if(le16inc(in_ptr) != 1) throw("Not PCM data"); - if (le16inc(in_ptr) != 1) throw("Not PCM data"); + channelCount = le16inc(in_ptr); + if(channelCount < 1 || channelCount > 2) throw("only mono or stereo"); + + sampleRate = le32inc(in_ptr); + + in_ptr += 6; // skip and + + bytePerSample = (le16inc(in_ptr)+7)/8; + if(bytePerSample < 1 || bytePerSample > 2) throw("only 1-16 bit/Sample"); + + in_ptr += fmtLen-16; - channelCount = le16inc(in_ptr); - if (channelCount < 1 || channelCount > 2) throw("only mono or stereo"); + if(be32inc(in_ptr) != 0x64617461 /*'data'*/) throw("No data-Tag"); + - sampleRate = le32inc(in_ptr); + soundDataStart = in_ptr+4; + soundDataEnd = soundDataStart + le32(in_ptr); - in_ptr += 6; // skip and + in_ptr = soundDataEnd; - bytePerSample = (le16inc(in_ptr)+7)/8; - if (bytePerSample < 1 || bytePerSample > 2) throw("only 1-16 bit/Sample"); + std::map cue; + std::vectorplst; - in_ptr += fmtLen-16; - - if (be32inc(in_ptr) != 0x64617461 /*'data'*/) throw("No data-Tag"); - - - soundDataStart = in_ptr+4; - soundDataEnd = soundDataStart + le32(in_ptr); - - in_ptr = soundDataEnd; - - std::map cue; - std::vectorplst; - - if (((u32)in_ptr) & 0x0001UL) in_ptr++; - while ((in_ptr+4) < (sound + riffsize)) { - u32 tag = be32inc(in_ptr); - switch (tag) { - case 0x63756520 /*'cue '*/: - in_ptr += 4; // skip size - for (u32 count = le32inc(in_ptr); count>0; count--) { - u32 ID = be32inc(in_ptr); - in_ptr += 4; // skip dwPosition - if (be32inc(in_ptr) == 0x64617461 /*'data'*/) { - in_ptr += 8; // skip chunkStart - dwBlockStart - cue[ID] = le32inc(in_ptr); - } else - in_ptr += 12; // skip chunkStart - SammpleOffset - } - break; - case 0x706C7374 /*' plst'*/: - in_ptr += 4; // skip size - for (u32 count = le32inc(in_ptr); count>0; count--) - plst.push_back((plst_t) { - le32inc(in_ptr), le32inc(in_ptr), le32inc(in_ptr) - } - ); - break; - default: - in_ptr -= 2; - break; - } - } - for (std::vector::iterator i = plst.begin(); i != plst.end(); ++i) { - const u8 *start = soundDataStart + cue[i->cueID]; - const u8 *end = soundDataStart + (i->len*bytePerSample*channelCount); - u32 loops = i->loops; - playlist.push_back((playlist_t) { - start,end,loops - } - ); - } - if (playlist.size() == 0) { - playlist.push_back((playlist_t) { - soundDataStart, soundDataEnd, 1 - } - ); - } - Rewind(); - } + if(((u32)in_ptr) & 0x0001UL) in_ptr++; + while((in_ptr+4) < (sound + riffsize)) + { + u32 tag = be32inc(in_ptr); + switch(tag) + { + case 0x63756520 /*'cue '*/: + in_ptr += 4; // skip size + for(u32 count = le32inc(in_ptr); count>0; count--) + { + u32 ID = be32inc(in_ptr); + in_ptr += 4; // skip dwPosition + if(be32inc(in_ptr) == 0x64617461 /*'data'*/) + { + in_ptr += 8; // skip chunkStart - dwBlockStart + cue[ID] = le32inc(in_ptr); + } + else + in_ptr += 12; // skip chunkStart - SammpleOffset + } + break; + case 0x706C7374 /*' plst'*/: + in_ptr += 4; // skip size + for(u32 count = le32inc(in_ptr); count>0; count--) + plst.push_back((plst_t){le32inc(in_ptr), le32inc(in_ptr), le32inc(in_ptr)}); + break; + default: + in_ptr -= 2; + break; + } + } + for(std::vector::iterator i = plst.begin(); i != plst.end(); ++i) + { + const u8 *start = soundDataStart + cue[i->cueID]; + const u8 *end = soundDataStart + (i->len*bytePerSample*channelCount); + u32 loops = i->loops; + playlist.push_back((playlist_t){start,end,loops}); + } + if(playlist.size() == 0) + { + playlist.push_back((playlist_t){soundDataStart, soundDataEnd, 1}); + } + Rewind(); + } public: - ~GuiSoundDecoderWAV() { - while (is_running) usleep(50); - if (is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - if (snd && len>4 && snd[0]=='R' && snd[1]=='I' && snd[2]=='F' && snd[3]=='F' - && snd[8]=='W' && snd[9]=='A' && snd[10]=='V' && snd[11]=='E') - return new GuiSoundDecoderWAV(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() { - if (bytePerSample == 2) - return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - else - return channelCount==2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; - } - s32 GetSampleRate() { - return sampleRate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) { - is_running = true; - u8 *write_pos = buffer; - u8 *write_end = buffer+buffer_size; - - for (;;) { - while (currentPos < currentEnd) { - if (write_pos >= write_end) { - is_running = false; - return write_pos-buffer; - } - if (bytePerSample == 2) { - *((s16*)write_pos) = le16inc(currentPos); - write_pos+=2; - if (channelCount==2) { // stereo - *((s16*)write_pos) = le16inc(currentPos); - write_pos+=2; - } - } else { - *write_pos++ = *currentPos++; - if (channelCount==2) // stereo - *write_pos++ = *currentPos++; - } - } - if (currentLoops>1) { - currentLoops--; - currentPos = currentStart; - continue; - } - if (currentPlaylist != playlist.end()) - currentPlaylist++; - if (currentPlaylist != playlist.end()) { - currentStart = currentPos = currentPlaylist->start; - currentEnd = currentPlaylist->end; - currentLoops = currentPlaylist->loops; - continue; - } else { - is_running = false; - return write_pos-buffer; - } - } - is_running = false; - return 0; - } - int Rewind() { - currentPlaylist = playlist.begin(); - currentStart = currentPos = currentPlaylist->start; - currentEnd = currentPlaylist->end; - currentLoops = currentPlaylist->loops; - return 0; - } + ~GuiSoundDecoderWAV() + { + while(is_running) usleep(50); + if(is_allocated) delete [] sound; + } + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) + { + if(snd && len>4 && snd[0]=='R' && snd[1]=='I' && snd[2]=='F' && snd[3]=='F' + && snd[8]=='W' && snd[9]=='A' && snd[10]=='V' && snd[11]=='E') + return new GuiSoundDecoderWAV(snd, len, snd_is_allocated); + return NULL; + } + s32 GetFormat() + { + if(bytePerSample == 2) + return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + else + return channelCount==2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; + } + s32 GetSampleRate() + { + return sampleRate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) + { + is_running = true; + u8 *write_pos = buffer; + u8 *write_end = buffer+buffer_size; + + for(;;) + { + while(currentPos < currentEnd) + { + if(write_pos >= write_end) + { + is_running = false; + return write_pos-buffer; + } + if(bytePerSample == 2) + { + *((s16*)write_pos) = le16inc(currentPos); + write_pos+=2; + if(channelCount==2) // stereo + { + *((s16*)write_pos) = le16inc(currentPos); + write_pos+=2; + } + } + else + { + *write_pos++ = *currentPos++; + if(channelCount==2) // stereo + *write_pos++ = *currentPos++; + } + } + if(currentLoops>1) + { + currentLoops--; + currentPos = currentStart; + continue; + } + if(currentPlaylist != playlist.end()) + currentPlaylist++; + if(currentPlaylist != playlist.end()) + { + currentStart = currentPos = currentPlaylist->start; + currentEnd = currentPlaylist->end; + currentLoops = currentPlaylist->loops; + continue; + } + else + { + is_running = false; + return write_pos-buffer; + } + } + is_running = false; + return 0; + } + int Rewind() + { + currentPlaylist = playlist.begin(); + currentStart = currentPos = currentPlaylist->start; + currentEnd = currentPlaylist->end; + currentLoops = currentPlaylist->loops; + return 0; + } private: - const u8 *sound; - bool is_allocated; - bool is_running; - - u16 channelCount; - u32 sampleRate; - u16 bytePerSample; - const u8 *soundDataStart; - const u8 *soundDataEnd; - std::vector playlist; - std::vector::iterator currentPlaylist; - const u8 *currentStart; - const u8 *currentEnd; - u32 currentLoops; - const u8 *currentPos; - + const u8 *sound; + bool is_allocated; + bool is_running; + + u16 channelCount; + u32 sampleRate; + u16 bytePerSample; + const u8 *soundDataStart; + const u8 *soundDataEnd; + std::vector playlist; + std::vector::iterator currentPlaylist; + const u8 *currentStart; + const u8 *currentEnd; + u32 currentLoops; + const u8 *currentPos; + }; REGISTER_GUI_SOUND_DECODER(GuiSoundDecoderWAV); diff --git a/source/libwiigui/gui_text.cpp b/source/libwiigui/gui_text.cpp index d6b89d2e..b3fa8e92 100644 --- a/source/libwiigui/gui_text.cpp +++ b/source/libwiigui/gui_text.cpp @@ -11,7 +11,7 @@ #include "gui.h" static int presetSize = 0; -static GXColor presetColor = (GXColor) {255, 255, 255, 255}; +static GXColor presetColor = (GXColor){255, 255, 255, 255}; static int presetMaxWidth = 0; static int presetWrapMode = GuiText::WRAP; static u16 presetStyle = FTGX_NULL; @@ -21,453 +21,522 @@ static int presetAlignmentVert = 0; /** * Constructor for the GuiText class. */ -GuiText::GuiText(const char * t, int s, GXColor c) { - text = NULL; - size = s; - color = c; - alpha = c.a; - style = FTGX_JUSTIFY_CENTER | FTGX_ALIGN_MIDDLE; - maxWidth = 0; - wrapMode = GuiText::WRAP; - scrollPos1 = 0; - scrollPos2 = 0; - scrollDelay = 0; - font = NULL; - widescreen = 0; //added - firstLine = 1; - numLines = -1; - totalLines = 1; - passChar = 0; +GuiText::GuiText(const char * t, int s, GXColor c) +{ + text = NULL; + size = s; + color = c; + alpha = c.a; + style = FTGX_JUSTIFY_CENTER | FTGX_ALIGN_MIDDLE; + maxWidth = 0; + wrapMode = GuiText::WRAP; + scrollPos1 = 0; + scrollPos2 = 0; + scrollDelay = 0; + font = NULL; + widescreen = 0; //added + firstLine = 1; + numLines = -1; + totalLines = 1; + passChar = 0; - alignmentHor = ALIGN_CENTRE; - alignmentVert = ALIGN_MIDDLE; + alignmentHor = ALIGN_CENTRE; + alignmentVert = ALIGN_MIDDLE; - if (t) - text = FreeTypeGX::charToWideChar((char *)t); + if(t) + text = FreeTypeGX::charToWideChar((char *)t); } /** * Constructor for the GuiText class, uses presets */ -GuiText::GuiText(const char * t) { - text = NULL; - size = presetSize; - color = presetColor; - alpha = presetColor.a; - style = presetStyle; - maxWidth = presetMaxWidth; - wrapMode = presetWrapMode; - scrollPos1 = 0; - scrollPos2 = 0; - scrollDelay = 0; - font = NULL; - widescreen = 0; //added - firstLine = 1; - numLines = -1; - totalLines = 1; +GuiText::GuiText(const char * t) +{ + text = NULL; + size = presetSize; + color = presetColor; + alpha = presetColor.a; + style = presetStyle; + maxWidth = presetMaxWidth; + wrapMode = presetWrapMode; + scrollPos1 = 0; + scrollPos2 = 0; + scrollDelay = 0; + font = NULL; + widescreen = 0; //added + firstLine = 1; + numLines = -1; + totalLines = 1; - alignmentHor = presetAlignmentHor; - alignmentVert = presetAlignmentVert; + alignmentHor = presetAlignmentHor; + alignmentVert = presetAlignmentVert; - if (t) - text = FreeTypeGX::charToWideChar((char *)t); + if(t) + text = FreeTypeGX::charToWideChar((char *)t); } /** * Destructor for the GuiText class. */ -GuiText::~GuiText() { - if (text) { - delete [] text; - text = NULL; - } +GuiText::~GuiText() +{ + if(text) + { + delete [] text; + text = NULL; + } } -void GuiText::SetNumLines(int n) { - numLines = n; +void GuiText::SetNumLines(int n) +{ + numLines = n; } -void GuiText::SetFirstLine(int n) { - firstLine = n; +void GuiText::SetFirstLine(int n) +{ + firstLine = n; } -int GuiText::GetNumLines() { - return numLines; +int GuiText::GetNumLines() +{ + return numLines; } -int GuiText::GetFirstLine() { - return firstLine; +int GuiText::GetFirstLine() +{ + return firstLine; } -int GuiText::GetTotalLines() { - return totalLines; +int GuiText::GetTotalLines() +{ + return totalLines; } -int GuiText::GetLineHeight(int n) { - int newSize = size*this->GetScale(); - int lineheight = newSize + 6; - - if (numLines <0) - return totalLines*lineheight+newSize; - - else return numLines*lineheight+newSize; +int GuiText::GetLineHeight(int n) +{ + int newSize = size*this->GetScale(); + int lineheight = newSize + 6; + + if (numLines <0) + return totalLines*lineheight+newSize; + + else return numLines*lineheight+newSize; } -void GuiText::SetText(const char * t) { - LOCK(this); - if (text) - delete [] text; - text = NULL; +void GuiText::SetText(const char * t) +{ + LOCK(this); + if(text) + delete [] text; + text = NULL; - if (t) { - text = FreeTypeGX::charToWideChar((char *)t); - - if (passChar != 0) { - for (u8 i = 0; i < wcslen(text); i++) { - text[i] = passChar; - } - } - } - scrollPos2 = 0; - scrollDelay = 0; + if(t) { + text = FreeTypeGX::charToWideChar((char *)t); + + if (passChar != 0) { + for (u8 i = 0; i < wcslen(text); i++) { + text[i] = passChar; + } + } + } + scrollPos2 = 0; + scrollDelay = 0; } -void GuiText::SetTextf(const char *format, ...) { - char *tmp=0; - va_list va; - va_start(va, format); - if ((vasprintf(&tmp, format, va)>=0) && tmp) { - this->SetText(tmp); - free(tmp); - } - va_end(va); +void GuiText::SetTextf(const char *format, ...) +{ + char *tmp=0; + va_list va; + va_start(va, format); + if((vasprintf(&tmp, format, va)>=0) && tmp) + { + this->SetText(tmp); + free(tmp); + } + va_end(va); } -void GuiText::SetText(const wchar_t * t) { - LOCK(this); - if (text) - delete [] text; - text = NULL; +void GuiText::SetText(const wchar_t * t) +{ + LOCK(this); + if(text) + delete [] text; + text = NULL; - if (t) { - int len = wcslen(t); - text = new wchar_t[len+1]; - if (text) { - wcscpy(text, t); - } - - if (passChar != 0) { - for (u8 i = 0; i < wcslen(text); i++) { - text[i] = passChar; - } - } - } - scrollPos2 = 0; - scrollDelay = 0; + if(t) + { + int len = wcslen(t); + text = new wchar_t[len+1]; + if(text) { + wcscpy(text, t); + } + + if (passChar != 0) { + for (u8 i = 0; i < wcslen(text); i++) { + text[i] = passChar; + } + } + } + scrollPos2 = 0; + scrollDelay = 0; } -void GuiText::SetPresets(int sz, GXColor c, int w, int wrap, u16 s, int h, int v) { - presetSize = sz; - presetColor = c; - presetMaxWidth = w; - presetWrapMode = wrap; - presetStyle = s; - presetAlignmentHor = h; - presetAlignmentVert = v; +void GuiText::SetPresets(int sz, GXColor c, int w, int wrap, u16 s, int h, int v) +{ + presetSize = sz; + presetColor = c; + presetMaxWidth = w; + presetWrapMode = wrap; + presetStyle = s; + presetAlignmentHor = h; + presetAlignmentVert = v; } -void GuiText::SetFontSize(int s) { - LOCK(this); - size = s; +void GuiText::SetFontSize(int s) +{ + LOCK(this); + size = s; } -void GuiText::SetMaxWidth(int w, short m/*=GuiText::WRAP*/) { - LOCK(this); - maxWidth = w; - wrapMode = m; +void GuiText::SetMaxWidth(int w, short m/*=GuiText::WRAP*/) +{ + LOCK(this); + maxWidth = w; + wrapMode = m; } -void GuiText::SetColor(GXColor c) { - LOCK(this); - color = c; - alpha = c.a; +void GuiText::SetColor(GXColor c) +{ + LOCK(this); + color = c; + alpha = c.a; } -void GuiText::SetStyle(u16 s, u16 m/*=0xffff*/) { - LOCK(this); - style &= ~m; - style |= s & m; +void GuiText::SetStyle(u16 s, u16 m/*=0xffff*/) +{ + LOCK(this); + style &= ~m; + style |= s & m; } -void GuiText::SetAlignment(int hor, int vert) { - LOCK(this); - style = FTGX_NULL; +void GuiText::SetAlignment(int hor, int vert) +{ + LOCK(this); + style = FTGX_NULL; - switch (hor) { - case ALIGN_LEFT: - style |= FTGX_JUSTIFY_LEFT; - break; - case ALIGN_RIGHT: - style |= FTGX_JUSTIFY_RIGHT; - break; - default: - style |= FTGX_JUSTIFY_CENTER; - break; - } - switch (vert) { - case ALIGN_TOP: - style |= FTGX_ALIGN_TOP; - break; - case ALIGN_BOTTOM: - style |= FTGX_ALIGN_BOTTOM; - break; - default: - style |= FTGX_ALIGN_MIDDLE; - break; - } + switch(hor) + { + case ALIGN_LEFT: + style |= FTGX_JUSTIFY_LEFT; + break; + case ALIGN_RIGHT: + style |= FTGX_JUSTIFY_RIGHT; + break; + default: + style |= FTGX_JUSTIFY_CENTER; + break; + } + switch(vert) + { + case ALIGN_TOP: + style |= FTGX_ALIGN_TOP; + break; + case ALIGN_BOTTOM: + style |= FTGX_ALIGN_BOTTOM; + break; + default: + style |= FTGX_ALIGN_MIDDLE; + break; + } - alignmentHor = hor; - alignmentVert = vert; + alignmentHor = hor; + alignmentVert = vert; } /** * Set a password character */ -void GuiText::SetPassChar(wchar_t p) { - LOCK(this); - passChar = p; +void GuiText::SetPassChar(wchar_t p) +{ + LOCK(this); + passChar = p; } /** * Set the Font */ -void GuiText::SetFont(FreeTypeGX *f) { - LOCK(this); - font = f; +void GuiText::SetFont(FreeTypeGX *f) +{ + LOCK(this); + font = f; } -int GuiText::GetTextWidth() { - LOCK(this); - if (!text) - return 0; +int GuiText::GetTextWidth() +{ + LOCK(this); + if(!text) + return 0; + + int newSize = size*this->GetScale(); - int newSize = size*this->GetScale(); - - (font ? font : fontSystem)->changeSize(newSize, widescreen ? newSize*0.8 : 0); - return (font ? font : fontSystem)->getWidth(text); + (font ? font : fontSystem)->changeSize(newSize, widescreen ? newSize*0.8 : 0); + return (font ? font : fontSystem)->getWidth(text); } -void GuiText::SetWidescreen(bool w) { - LOCK(this); - widescreen = w; +void GuiText::SetWidescreen(bool w) +{ + LOCK(this); + widescreen = w; } /** * Draw the text on screen */ -void GuiText::Draw() { - LOCK(this); - if (!text) - return; +void GuiText::Draw() +{ + LOCK(this); + if(!text) + return; - if (!this->IsVisible()) - return; + if(!this->IsVisible()) + return; - GXColor c = color; - c.a = this->GetAlpha(); + GXColor c = color; + c.a = this->GetAlpha(); - int newSize = size*this->GetScale(); + int newSize = size*this->GetScale(); - (font ? font : fontSystem)->changeSize(newSize, widescreen ? newSize*0.8 : 0); - int voffset = 0; + (font ? font : fontSystem)->changeSize(newSize, widescreen ? newSize*0.8 : 0); + int voffset = 0; // if(alignmentVert == ALIGN_MIDDLE) // voffset = -newSize/2 + 2; - if (maxWidth > 0 && (font ? font : fontSystem)->getWidth(text) > maxWidth) { - if (wrapMode == GuiText::WRAP) { // text wrapping - int lineheight = newSize + 6; - int strlen = wcslen(text); - int i = 0; - int ch = 0; - int linenum = 0; - int linemax = 200; - int lastSpace = -1; - int lastSpaceIndex = -1; - wchar_t * tmptext[linemax]; + if(maxWidth > 0 && (font ? font : fontSystem)->getWidth(text) > maxWidth) + { + if(wrapMode == GuiText::WRAP) // text wrapping + { + int lineheight = newSize + 6; + int strlen = wcslen(text); + int i = 0; + int ch = 0; + int linenum = 0; + int linemax = 200; + int lastSpace = -1; + int lastSpaceIndex = -1; + wchar_t * tmptext[linemax]; + + totalLines=0; + while(ch < strlen) + { + if(i == 0) + { + if (linenum <= linemax) + { + tmptext[linenum] = new wchar_t[strlen + 1]; + } + else + { + break; + } + } + + tmptext[linenum][i] = text[ch]; + tmptext[linenum][i+1] = 0; - totalLines=0; - while (ch < strlen) { - if (i == 0) { - if (linenum <= linemax) { - tmptext[linenum] = new wchar_t[strlen + 1]; - } else { - break; - } - } + //if(text[ch] == ' ' || ch == strlen-1) + //{ + if((font ? font : fontSystem)->getWidth(tmptext[linenum]) >= maxWidth) + //if(fontSystem->getWidth(tmptext[linenum]) >= maxWidth) + { + if(lastSpace >= 0) + { + tmptext[linenum][lastSpaceIndex] = 0; // discard space, and everything after + ch = lastSpace; // go backwards to the last space + lastSpace = -1; // we have used this space + lastSpaceIndex = -1; + } + linenum++; + i = -1; + } + else if(ch == strlen-1) + { + linenum++; + } + //} + if(text[ch] == ' ' && i >= 0) + { + lastSpace = ch; + lastSpaceIndex = i; + } + if(text[ch] == '\n' && ch != strlen-1 && i >= 0) + { + linenum++; + i = -1; + } + ch++; + i++; + } + totalLines = linenum; + + if(alignmentVert == ALIGN_MIDDLE) + voffset = voffset - (lineheight*linenum)/2 + lineheight/2; - tmptext[linenum][i] = text[ch]; - tmptext[linenum][i+1] = 0; + if (numLines <0){ + for(i=0; i < linenum; i++) + { + (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset+i*lineheight, tmptext[i], c, style); + delete tmptext[i]; + } + } + + //put in for txt vertical txt scrolling + else { + int j; + i=0; + for(j=firstLine-1; j < numLines+firstLine-1; j++) + { + //if (jdrawText(this->GetLeft(), this->GetTop()+voffset+i*lineheight, tmptext[j], c, style); + i++; + } + for(i=0; i < linenum; i++) + { + delete tmptext[i]; + } + } + + + } + else if(wrapMode == GuiText::DOTTED) // text dotted + { + wchar_t save[4]; + int strlen = wcslen(text); + int dotPos=strlen-3; + int i; + bool drawed = false; + while(dotPos > 0 && drawed == false) + { + for(i=0; i<4; i++) // save Text for "..." + { + save[i] = text[dotPos+i]; + text[dotPos+i] = (i != 3 ? _TEXT('.') : 0); + } + if(((font ? font : fontSystem)->getWidth(text)) <= maxWidth) + { + (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset, text, c, style); + drawed = true; + } - //if(text[ch] == ' ' || ch == strlen-1) - //{ - if ((font ? font : fontSystem)->getWidth(tmptext[linenum]) >= maxWidth) - //if(fontSystem->getWidth(tmptext[linenum]) >= maxWidth) - { - if (lastSpace >= 0) { - tmptext[linenum][lastSpaceIndex] = 0; // discard space, and everything after - ch = lastSpace; // go backwards to the last space - lastSpace = -1; // we have used this space - lastSpaceIndex = -1; - } - linenum++; - i = -1; - } else if (ch == strlen-1) { - linenum++; - } - //} - if (text[ch] == ' ' && i >= 0) { - lastSpace = ch; - lastSpaceIndex = i; - } - if (text[ch] == '\n' && ch != strlen-1 && i >= 0) { - linenum++; - i = -1; - } - ch++; - i++; - } - totalLines = linenum; + for(i=0; i<4; i++) // write saved Text back + text[dotPos+i] = save[i]; + dotPos--; + } + if(!drawed) + (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset, text, c, style); + } + else if(wrapMode == GuiText::SCROLL) // text scroller + { + wchar_t save; + + if(scrollPos2 == 0 || frameCount > scrollDelay+5) + { + scrollPos1 = 0; + scrollOffset = 0; + for(scrollPos2 = wcslen(text); scrollPos2 > 1; scrollPos2--) + { + save = text[scrollPos2]; // save Pos2 + text[scrollPos2] = 0; + int textWidth = (font ? font : fontSystem)->getWidth(text); + text[scrollPos2] = save; // restore Pos2 + if(textWidth <= maxWidth) + break; + } + scrollDelay = frameCount+50; // wait 50 Frames before beginning with scrolling + } + else if(scrollPos2 > 0 && frameCount >= scrollDelay) + { + + if(--scrollOffset < 0) + { + wchar_t tmp[] = { text[scrollPos1], text[scrollPos1+1], 0 }; + scrollOffset += (font ? font : fontSystem)->getWidth(tmp) - (font ? font : fontSystem)->getWidth(tmp+1); + scrollPos1++; + } + + int strlen = wcslen(text); + for(; scrollPos2 < strlen; scrollPos2++) + { + save = text[scrollPos2+1]; // save Pos2 + text[scrollPos2+1] = 0; + int textWidth = (font ? font : fontSystem)->getWidth(&text[scrollPos1]); + text[scrollPos2+1] = save; // restore Pos2 + if(textWidth+scrollOffset > maxWidth) + break; + } + if(scrollPos2 == strlen) + { + scrollPos2 = -scrollPos2; + scrollDelay = frameCount+25; // when dir-change wait 25 Frames + } + else + scrollDelay = frameCount+1; // wait 1 Frames + } + else if(frameCount >= scrollDelay) + { + scrollPos2 = -scrollPos2; + + scrollOffset++; + wchar_t tmp[] = { text[scrollPos1-1], text[scrollPos1], 0 }; + int tmpOffset = (font ? font : fontSystem)->getWidth(tmp) - (font ? font : fontSystem)->getWidth(tmp+1); + if(scrollOffset >= tmpOffset) + { + scrollOffset -= tmpOffset; + scrollPos1--; + } - if (alignmentVert == ALIGN_MIDDLE) - voffset = voffset - (lineheight*linenum)/2 + lineheight/2; + for(; scrollPos2 > scrollPos1; scrollPos2--) + { + save = text[scrollPos2]; // save Pos2 + text[scrollPos2] = 0; + int textWidth = (font ? font : fontSystem)->getWidth(&text[scrollPos1]); + text[scrollPos2] = save; // restore Pos2 + if(textWidth+scrollOffset <= maxWidth) + break; + } + if(scrollPos1 == 0) + { + scrollPos2 = -scrollPos2; + scrollDelay = frameCount+25; // when dir-change wait 25 Frames + } + else + scrollDelay = frameCount+1; // wait 10 Frames - if (numLines <0) { - for (i=0; i < linenum; i++) { - (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset+i*lineheight, tmptext[i], c, style); - delete tmptext[i]; - } - } - - //put in for txt vertical txt scrolling - else { - int j; - i=0; - for (j=firstLine-1; j < numLines+firstLine-1; j++) { - //if (jdrawText(this->GetLeft(), this->GetTop()+voffset+i*lineheight, tmptext[j], c, style); - i++; - } - for (i=0; i < linenum; i++) { - delete tmptext[i]; - } - } - - - } else if (wrapMode == GuiText::DOTTED) { // text dotted - wchar_t save[4]; - int strlen = wcslen(text); - int dotPos=strlen-3; - int i; - bool drawed = false; - while (dotPos > 0 && drawed == false) { - for (i=0; i<4; i++) { // save Text for "..." - save[i] = text[dotPos+i]; - text[dotPos+i] = (i != 3 ? _TEXT('.') : 0); - } - if (((font ? font : fontSystem)->getWidth(text)) <= maxWidth) { - (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset, text, c, style); - drawed = true; - } - - for (i=0; i<4; i++) // write saved Text back - text[dotPos+i] = save[i]; - dotPos--; - } - if (!drawed) - (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset, text, c, style); - } else if (wrapMode == GuiText::SCROLL) { // text scroller - wchar_t save; - - if (scrollPos2 == 0 || frameCount > scrollDelay+5) { - scrollPos1 = 0; - scrollOffset = 0; - for (scrollPos2 = wcslen(text); scrollPos2 > 1; scrollPos2--) { - save = text[scrollPos2]; // save Pos2 - text[scrollPos2] = 0; - int textWidth = (font ? font : fontSystem)->getWidth(text); - text[scrollPos2] = save; // restore Pos2 - if (textWidth <= maxWidth) - break; - } - scrollDelay = frameCount+50; // wait 50 Frames before beginning with scrolling - } else if (scrollPos2 > 0 && frameCount >= scrollDelay) { - - if (--scrollOffset < 0) { - wchar_t tmp[] = { text[scrollPos1], text[scrollPos1+1], 0 }; - scrollOffset += (font ? font : fontSystem)->getWidth(tmp) - (font ? font : fontSystem)->getWidth(tmp+1); - scrollPos1++; - } - - int strlen = wcslen(text); - for (; scrollPos2 < strlen; scrollPos2++) { - save = text[scrollPos2+1]; // save Pos2 - text[scrollPos2+1] = 0; - int textWidth = (font ? font : fontSystem)->getWidth(&text[scrollPos1]); - text[scrollPos2+1] = save; // restore Pos2 - if (textWidth+scrollOffset > maxWidth) - break; - } - if (scrollPos2 == strlen) { - scrollPos2 = -scrollPos2; - scrollDelay = frameCount+25; // when dir-change wait 25 Frames - } else - scrollDelay = frameCount+1; // wait 1 Frames - } else if (frameCount >= scrollDelay) { - scrollPos2 = -scrollPos2; - - scrollOffset++; - wchar_t tmp[] = { text[scrollPos1-1], text[scrollPos1], 0 }; - int tmpOffset = (font ? font : fontSystem)->getWidth(tmp) - (font ? font : fontSystem)->getWidth(tmp+1); - if (scrollOffset >= tmpOffset) { - scrollOffset -= tmpOffset; - scrollPos1--; - } - - for (; scrollPos2 > scrollPos1; scrollPos2--) { - save = text[scrollPos2]; // save Pos2 - text[scrollPos2] = 0; - int textWidth = (font ? font : fontSystem)->getWidth(&text[scrollPos1]); - text[scrollPos2] = save; // restore Pos2 - if (textWidth+scrollOffset <= maxWidth) - break; - } - if (scrollPos1 == 0) { - scrollPos2 = -scrollPos2; - scrollDelay = frameCount+25; // when dir-change wait 25 Frames - } else - scrollDelay = frameCount+1; // wait 10 Frames - - scrollPos2 = -scrollPos2; - } - - uint16_t drawStyle = style; - uint16_t drawX = this->GetLeft() + scrollOffset; - - if ((drawStyle & FTGX_JUSTIFY_MASK) == FTGX_JUSTIFY_CENTER) { - drawStyle = (drawStyle & ~FTGX_JUSTIFY_MASK) | FTGX_JUSTIFY_LEFT; - drawX -= maxWidth >> 1; - } else if ((drawStyle & FTGX_JUSTIFY_MASK) == FTGX_JUSTIFY_RIGHT) { - drawStyle = (drawStyle & ~FTGX_JUSTIFY_MASK) | FTGX_JUSTIFY_LEFT; - drawX -= maxWidth; - } - - save = text[abs(scrollPos2)]; // save Pos2 - text[abs(scrollPos2)] = 0; - (font ? font : fontSystem)->drawText(drawX, this->GetTop()+voffset, &text[scrollPos1], c, drawStyle); - text[abs(scrollPos2)] = save; // restore Pos2 - } - } else { - (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset, text, c, style); - } - this->UpdateEffects(); + scrollPos2 = -scrollPos2; + } + + uint16_t drawStyle = style; + uint16_t drawX = this->GetLeft() + scrollOffset; + + if((drawStyle & FTGX_JUSTIFY_MASK) == FTGX_JUSTIFY_CENTER) + { + drawStyle = (drawStyle & ~FTGX_JUSTIFY_MASK) | FTGX_JUSTIFY_LEFT; + drawX -= maxWidth >> 1; + } + else if((drawStyle & FTGX_JUSTIFY_MASK) == FTGX_JUSTIFY_RIGHT) + { + drawStyle = (drawStyle & ~FTGX_JUSTIFY_MASK) | FTGX_JUSTIFY_LEFT; + drawX -= maxWidth; + } + + save = text[abs(scrollPos2)]; // save Pos2 + text[abs(scrollPos2)] = 0; + (font ? font : fontSystem)->drawText(drawX, this->GetTop()+voffset, &text[scrollPos1], c, drawStyle); + text[abs(scrollPos2)] = save; // restore Pos2 + } + } + else + { + (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop()+voffset, text, c, style); + } + this->UpdateEffects(); } diff --git a/source/libwiigui/gui_tooltip.cpp b/source/libwiigui/gui_tooltip.cpp index 3167313d..58a17f5d 100644 --- a/source/libwiigui/gui_tooltip.cpp +++ b/source/libwiigui/gui_tooltip.cpp @@ -19,66 +19,73 @@ static GuiImageData tooltipRight(tooltip_right_png); * Constructor for the GuiTooltip class. */ GuiTooltip::GuiTooltip(const char *t, int Alpha/*=255*/) - : - leftImage(&tooltipLeft), tileImage(&tooltipTile), rightImage(&tooltipRight) { - text = NULL; - height = leftImage.GetHeight(); - leftImage.SetParent(this); - tileImage.SetParent(this); - rightImage.SetParent(this); - leftImage.SetParentAngle(false); - tileImage.SetParentAngle(false); - rightImage.SetParentAngle(false); - SetText(t); - SetAlpha(Alpha); +: +leftImage(&tooltipLeft), tileImage(&tooltipTile), rightImage(&tooltipRight) +{ + text = NULL; + height = leftImage.GetHeight(); + leftImage.SetParent(this); + tileImage.SetParent(this); + rightImage.SetParent(this); + leftImage.SetParentAngle(false); + tileImage.SetParentAngle(false); + rightImage.SetParentAngle(false); + SetText(t); + SetAlpha(Alpha); } /* * Destructor for the GuiTooltip class. */ -GuiTooltip::~GuiTooltip() { - if (text) delete text; +GuiTooltip::~GuiTooltip() +{ + if(text) delete text; } -float GuiTooltip::GetScale() { - float s = scale * scaleDyn; +float GuiTooltip::GetScale() +{ + float s = scale * scaleDyn; - return s; + return s; } /* !Sets the text of the GuiTooltip element * !\param t Text */ -void GuiTooltip::SetText(const char * t) { - LOCK(this); - if (text) { - delete text; - text = NULL; - } - int tile_cnt = 0; - if (t && (text = new GuiText(t, 22, (GXColor) {0, 0, 0, 255}))) { - text->SetParent(this); - tile_cnt = (text->GetTextWidth()-12) /tileImage.GetWidth(); - if (tile_cnt < 0) tile_cnt = 0; - } - tileImage.SetPosition(leftImage.GetWidth(), 0); - tileImage.SetTile(tile_cnt); - rightImage.SetPosition(leftImage.GetWidth() + tile_cnt * tileImage.GetWidth(), 0); - width = leftImage.GetWidth() + tile_cnt * tileImage.GetWidth() + rightImage.GetWidth(); +void GuiTooltip::SetText(const char * t) +{ + LOCK(this); + if(text) + { + delete text; + text = NULL; + } + int tile_cnt = 0; + if(t && (text = new GuiText(t, 22, (GXColor){0, 0, 0, 255}))) + { + text->SetParent(this); + tile_cnt = (text->GetTextWidth()-12) /tileImage.GetWidth(); + if(tile_cnt < 0) tile_cnt = 0; + } + tileImage.SetPosition(leftImage.GetWidth(), 0); + tileImage.SetTile(tile_cnt); + rightImage.SetPosition(leftImage.GetWidth() + tile_cnt * tileImage.GetWidth(), 0); + width = leftImage.GetWidth() + tile_cnt * tileImage.GetWidth() + rightImage.GetWidth(); } -void GuiTooltip::SetWidescreen(bool) {} +void GuiTooltip::SetWidescreen(bool){} /* * Draw the Tooltip on screen */ -void GuiTooltip::Draw() { - LOCK(this); - if (!this->IsVisible()) return; +void GuiTooltip::Draw() +{ + LOCK(this); + if(!this->IsVisible()) return; - leftImage.Draw(); - tileImage.Draw(); - rightImage.Draw(); - if (text) text->Draw(); + leftImage.Draw(); + tileImage.Draw(); + rightImage.Draw(); + if(text) text->Draw(); - this->UpdateEffects(); + this->UpdateEffects(); } diff --git a/source/libwiigui/gui_trigger.cpp b/source/libwiigui/gui_trigger.cpp index 9184acbf..1d9207ec 100644 --- a/source/libwiigui/gui_trigger.cpp +++ b/source/libwiigui/gui_trigger.cpp @@ -15,16 +15,18 @@ static int scrollDelay = 0; /** * Constructor for the GuiTrigger class. */ -GuiTrigger::GuiTrigger() { - chan = -1; - memset(&wpad, 0, sizeof(WPADData)); - memset(&pad, 0, sizeof(PADData)); +GuiTrigger::GuiTrigger() +{ + chan = -1; + memset(&wpad, 0, sizeof(WPADData)); + memset(&pad, 0, sizeof(PADData)); } /** * Destructor for the GuiTrigger class. */ -GuiTrigger::~GuiTrigger() { +GuiTrigger::~GuiTrigger() +{ } /** @@ -32,11 +34,12 @@ GuiTrigger::~GuiTrigger() { * - Element is selected * - Trigger button is pressed */ -void GuiTrigger::SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { - type = TRIGGER_SIMPLE; - chan = ch; - wpad.btns_d = wiibtns; - pad.btns_d = gcbtns; +void GuiTrigger::SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns) +{ + type = TRIGGER_SIMPLE; + chan = ch; + wpad.btns_d = wiibtns; + pad.btns_d = gcbtns; } /** @@ -44,22 +47,24 @@ void GuiTrigger::SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { * - Element is selected * - Trigger button is pressed and held */ -void GuiTrigger::SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { - type = TRIGGER_HELD; - chan = ch; - wpad.btns_h = wiibtns; - pad.btns_h = gcbtns; +void GuiTrigger::SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns) +{ + type = TRIGGER_HELD; + chan = ch; + wpad.btns_h = wiibtns; + pad.btns_h = gcbtns; } /** * Sets a button trigger. Requires: * - Trigger button is pressed */ -void GuiTrigger::SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { - type = TRIGGER_BUTTON_ONLY; - chan = ch; - wpad.btns_d = wiibtns; - pad.btns_d = gcbtns; +void GuiTrigger::SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns) +{ + type = TRIGGER_BUTTON_ONLY; + chan = ch; + wpad.btns_d = wiibtns; + pad.btns_d = gcbtns; } /** @@ -67,11 +72,12 @@ void GuiTrigger::SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { * - Trigger button is pressed * - Parent window is in focus */ -void GuiTrigger::SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { - type = TRIGGER_BUTTON_ONLY_IN_FOCUS; - chan = ch; - wpad.btns_d = wiibtns; - pad.btns_d = gcbtns; +void GuiTrigger::SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns) +{ + type = TRIGGER_BUTTON_ONLY_IN_FOCUS; + chan = ch; + wpad.btns_d = wiibtns; + pad.btns_d = gcbtns; } /**************************************************************************** @@ -80,136 +86,170 @@ void GuiTrigger::SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { * Get X/Y value from Wii Joystick (classic, nunchuk) input ***************************************************************************/ -s8 GuiTrigger::WPAD_Stick(u8 right, int axis) { -#ifdef HW_RVL +s8 GuiTrigger::WPAD_Stick(u8 right, int axis) +{ + #ifdef HW_RVL - float mag = 0.0; - float ang = 0.0; + float mag = 0.0; + float ang = 0.0; - switch (wpad.exp.type) { - case WPAD_EXP_NUNCHUK: - case WPAD_EXP_GUITARHERO3: - if (right == 0) { - mag = wpad.exp.nunchuk.js.mag; - ang = wpad.exp.nunchuk.js.ang; - } - break; + switch (wpad.exp.type) + { + case WPAD_EXP_NUNCHUK: + case WPAD_EXP_GUITARHERO3: + if (right == 0) + { + mag = wpad.exp.nunchuk.js.mag; + ang = wpad.exp.nunchuk.js.ang; + } + break; - case WPAD_EXP_CLASSIC: - if (right == 0) { - mag = wpad.exp.classic.ljs.mag; - ang = wpad.exp.classic.ljs.ang; - } else { - mag = wpad.exp.classic.rjs.mag; - ang = wpad.exp.classic.rjs.ang; - } - break; + case WPAD_EXP_CLASSIC: + if (right == 0) + { + mag = wpad.exp.classic.ljs.mag; + ang = wpad.exp.classic.ljs.ang; + } + else + { + mag = wpad.exp.classic.rjs.mag; + ang = wpad.exp.classic.rjs.ang; + } + break; - default: - break; - } + default: + break; + } - /* calculate x/y value (angle need to be converted into radian) */ - if (mag > 1.0) mag = 1.0; - else if (mag < -1.0) mag = -1.0; - double val; + /* calculate x/y value (angle need to be converted into radian) */ + if (mag > 1.0) mag = 1.0; + else if (mag < -1.0) mag = -1.0; + double val; - if (axis == 0) // x-axis - val = mag * sin((PI * ang)/180.0f); - else // y-axis - val = mag * cos((PI * ang)/180.0f); + if(axis == 0) // x-axis + val = mag * sin((PI * ang)/180.0f); + else // y-axis + val = mag * cos((PI * ang)/180.0f); - return (s8)(val * 128.0f); + return (s8)(val * 128.0f); -#else - return 0; -#endif + #else + return 0; + #endif } -bool GuiTrigger::Left() { - u32 wiibtn = WPAD_BUTTON_LEFT; +bool GuiTrigger::Left() +{ + u32 wiibtn = WPAD_BUTTON_LEFT; - if ((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_LEFT) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_LEFT - || pad.stickX < -PADCAL - || WPAD_Stick(0,0) < -PADCAL) { - if (wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_LEFT) - || pad.btns_d & PAD_BUTTON_LEFT) { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } else if (scrollDelay == 0) { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } else { - if (scrollDelay > 0) - scrollDelay--; - } - } - return false; + if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_LEFT) + || (pad.btns_d | pad.btns_h) & PAD_BUTTON_LEFT + || pad.stickX < -PADCAL + || WPAD_Stick(0,0) < -PADCAL) + { + if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_LEFT) + || pad.btns_d & PAD_BUTTON_LEFT) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if(scrollDelay == 0) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if(scrollDelay > 0) + scrollDelay--; + } + } + return false; } -bool GuiTrigger::Right() { - u32 wiibtn = WPAD_BUTTON_RIGHT; +bool GuiTrigger::Right() +{ + u32 wiibtn = WPAD_BUTTON_RIGHT; - if ((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_RIGHT) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_RIGHT - || pad.stickX > PADCAL - || WPAD_Stick(0,0) > PADCAL) { - if (wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_RIGHT) - || pad.btns_d & PAD_BUTTON_RIGHT) { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } else if (scrollDelay == 0) { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } else { - if (scrollDelay > 0) - scrollDelay--; - } - } - return false; + if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_RIGHT) + || (pad.btns_d | pad.btns_h) & PAD_BUTTON_RIGHT + || pad.stickX > PADCAL + || WPAD_Stick(0,0) > PADCAL) + { + if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_RIGHT) + || pad.btns_d & PAD_BUTTON_RIGHT) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if(scrollDelay == 0) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if(scrollDelay > 0) + scrollDelay--; + } + } + return false; } -bool GuiTrigger::Up() { - u32 wiibtn = WPAD_BUTTON_UP; +bool GuiTrigger::Up() +{ + u32 wiibtn = WPAD_BUTTON_UP; - if ((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_UP) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_UP - || pad.stickY > PADCAL - || WPAD_Stick(0,1) > PADCAL) { - if (wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_UP) - || pad.btns_d & PAD_BUTTON_UP) { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } else if (scrollDelay == 0) { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } else { - if (scrollDelay > 0) - scrollDelay--; - } - } - return false; + if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_UP) + || (pad.btns_d | pad.btns_h) & PAD_BUTTON_UP + || pad.stickY > PADCAL + || WPAD_Stick(0,1) > PADCAL) + { + if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_UP) + || pad.btns_d & PAD_BUTTON_UP) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if(scrollDelay == 0) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if(scrollDelay > 0) + scrollDelay--; + } + } + return false; } -bool GuiTrigger::Down() { - u32 wiibtn = WPAD_BUTTON_DOWN; +bool GuiTrigger::Down() +{ + u32 wiibtn = WPAD_BUTTON_DOWN; - if ((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_DOWN) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_DOWN - || pad.stickY < -PADCAL - || WPAD_Stick(0,1) < -PADCAL) { - if (wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_DOWN) - || pad.btns_d & PAD_BUTTON_DOWN) { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } else if (scrollDelay == 0) { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } else { - if (scrollDelay > 0) - scrollDelay--; - } - } - return false; + if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_DOWN) + || (pad.btns_d | pad.btns_h) & PAD_BUTTON_DOWN + || pad.stickY < -PADCAL + || WPAD_Stick(0,1) < -PADCAL) + { + if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_DOWN) + || pad.btns_d & PAD_BUTTON_DOWN) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if(scrollDelay == 0) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if(scrollDelay > 0) + scrollDelay--; + } + } + return false; } diff --git a/source/libwiigui/gui_window.cpp b/source/libwiigui/gui_window.cpp index 42e8cb6b..303b4b2d 100644 --- a/source/libwiigui/gui_window.cpp +++ b/source/libwiigui/gui_window.cpp @@ -10,354 +10,421 @@ #include "gui.h" -GuiWindow::GuiWindow() { - width = 0; - height = 0; - focus = 0; // allow focus +GuiWindow::GuiWindow() +{ + width = 0; + height = 0; + focus = 0; // allow focus } -GuiWindow::GuiWindow(int w, int h) { - width = w; - height = h; - focus = 0; // allow focus +GuiWindow::GuiWindow(int w, int h) +{ + width = w; + height = h; + focus = 0; // allow focus } -GuiWindow::~GuiWindow() { +GuiWindow::~GuiWindow() +{ } -void GuiWindow::Append(GuiElement* e) { - LOCK(this); - if (e == NULL) - return; +void GuiWindow::Append(GuiElement* e) +{ + LOCK(this); + if (e == NULL) + return; - Remove(e); - _elements.push_back(e); - e->SetParent(this); + Remove(e); + _elements.push_back(e); + e->SetParent(this); } -void GuiWindow::Insert(GuiElement* e, u32 index) { - LOCK(this); - if (e == NULL || index > (_elements.size() - 1)) - return; +void GuiWindow::Insert(GuiElement* e, u32 index) +{ + LOCK(this); + if (e == NULL || index > (_elements.size() - 1)) + return; - Remove(e); - _elements.insert(_elements.begin()+index, e); - e->SetParent(this); + Remove(e); + _elements.insert(_elements.begin()+index, e); + e->SetParent(this); } -void GuiWindow::Remove(GuiElement* e) { - LOCK(this); - if (e == NULL) - return; +void GuiWindow::Remove(GuiElement* e) +{ + LOCK(this); + if (e == NULL) + return; - for (u8 i = 0; i < _elements.size(); i++) { - if (e == _elements.at(i)) { - _elements.erase(_elements.begin()+i); - break; - } - } + for (u8 i = 0; i < _elements.size(); i++) + { + if(e == _elements.at(i)) + { + _elements.erase(_elements.begin()+i); + break; + } + } } -void GuiWindow::RemoveAll() { - LOCK(this); - _elements.clear(); +void GuiWindow::RemoveAll() +{ + LOCK(this); + _elements.clear(); } -GuiElement* GuiWindow::GetGuiElementAt(u32 index) const { - if (index >= _elements.size()) - return NULL; - return _elements.at(index); +GuiElement* GuiWindow::GetGuiElementAt(u32 index) const +{ + if (index >= _elements.size()) + return NULL; + return _elements.at(index); } -u32 GuiWindow::GetSize() { - return _elements.size(); +u32 GuiWindow::GetSize() +{ + return _elements.size(); } -void GuiWindow::Draw() { - LOCK(this); - if (_elements.size() == 0 || !this->IsVisible()) - return; +void GuiWindow::Draw() +{ + LOCK(this); + if(_elements.size() == 0 || !this->IsVisible()) + return; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->Draw(); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->Draw(); } + catch (const std::exception& e) { } + } - this->UpdateEffects(); + this->UpdateEffects(); - if (parentElement && state == STATE_DISABLED) - //Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor){0xbe, 0xca, 0xd5, 0x70},1); - Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor) {0, 0, 0, 0x70},1); + if(parentElement && state == STATE_DISABLED) + //Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor){0xbe, 0xca, 0xd5, 0x70},1); + Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor){0, 0, 0, 0x70},1); } -void GuiWindow::DrawTooltip() { - LOCK(this); - if (_elements.size() == 0 || !this->IsVisible()) - return; +void GuiWindow::DrawTooltip() +{ + LOCK(this); + if(_elements.size() == 0 || !this->IsVisible()) + return; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->DrawTooltip(); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->DrawTooltip(); } + catch (const std::exception& e) { } + } } -void GuiWindow::ResetState() { - LOCK(this); - if (state != STATE_DISABLED) - state = STATE_DEFAULT; +void GuiWindow::ResetState() +{ + LOCK(this); + if(state != STATE_DISABLED) + state = STATE_DEFAULT; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->ResetState(); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->ResetState(); } + catch (const std::exception& e) { } + } } -void GuiWindow::SetState(int s) { - LOCK(this); - state = s; +void GuiWindow::SetState(int s) +{ + LOCK(this); + state = s; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->SetState(s); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->SetState(s); } + catch (const std::exception& e) { } + } } -void GuiWindow::SetVisible(bool v) { - LOCK(this); - visible = v; +void GuiWindow::SetVisible(bool v) +{ + LOCK(this); + visible = v; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->SetVisible(v); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->SetVisible(v); } + catch (const std::exception& e) { } + } } -void GuiWindow::SetFocus(int f) { - LOCK(this); - focus = f; +void GuiWindow::SetFocus(int f) +{ + LOCK(this); + focus = f; - if (f == 1) - this->MoveSelectionVert(1); - else - this->ResetState(); + if(f == 1) + this->MoveSelectionVert(1); + else + this->ResetState(); } -void GuiWindow::ChangeFocus(GuiElement* e) { - LOCK(this); - if (parentElement) - return; // this is only intended for the main window +void GuiWindow::ChangeFocus(GuiElement* e) +{ + LOCK(this); + if(parentElement) + return; // this is only intended for the main window - for (u8 i = 0; i < _elements.size(); i++) { - if (e == _elements.at(i)) - _elements.at(i)->SetFocus(1); - else if (_elements.at(i)->IsFocused() == 1) - _elements.at(i)->SetFocus(0); - } + for (u8 i = 0; i < _elements.size(); i++) + { + if(e == _elements.at(i)) + _elements.at(i)->SetFocus(1); + else if(_elements.at(i)->IsFocused() == 1) + _elements.at(i)->SetFocus(0); + } } -void GuiWindow::ToggleFocus(GuiTrigger * t) { - LOCK(this); - if (parentElement) - return; // this is only intended for the main window +void GuiWindow::ToggleFocus(GuiTrigger * t) +{ + LOCK(this); + if(parentElement) + return; // this is only intended for the main window - int found = -1; - int newfocus = -1; - u8 i; + int found = -1; + int newfocus = -1; + u8 i; - // look for currently in focus element - for (i = 0; i < _elements.size(); i++) { - try { - if (_elements.at(i)->IsFocused() == 1) { - found = i; - break; - } - } catch (const std::exception& e) { } - } + // look for currently in focus element + for (i = 0; i < _elements.size(); i++) + { + try + { + if(_elements.at(i)->IsFocused() == 1) + { + found = i; + break; + } + } + catch (const std::exception& e) { } + } - // element with focus not found, try to give focus - if (found == -1) { - for (i = 0; i < _elements.size(); i++) { - try { - if (_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) { // focus is possible (but not set) - _elements.at(i)->SetFocus(1); // give this element focus - break; - } - } catch (const std::exception& e) { } - } - } - // change focus - else if (t->wpad.btns_d & (WPAD_BUTTON_1 | WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_PLUS) - || t->pad.btns_d & PAD_BUTTON_B) { - for (i = found; i < _elements.size(); i++) { - try { - if (_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) { // focus is possible (but not set) - newfocus = i; - _elements.at(i)->SetFocus(1); // give this element focus - _elements.at(found)->SetFocus(0); // disable focus on other element - break; - } - } catch (const std::exception& e) { } - } + // element with focus not found, try to give focus + if(found == -1) + { + for (i = 0; i < _elements.size(); i++) + { + try + { + if(_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) // focus is possible (but not set) + { + _elements.at(i)->SetFocus(1); // give this element focus + break; + } + } + catch (const std::exception& e) { } + } + } + // change focus + else if(t->wpad.btns_d & (WPAD_BUTTON_1 | WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_PLUS) + || t->pad.btns_d & PAD_BUTTON_B) + { + for (i = found; i < _elements.size(); i++) + { + try + { + if(_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) // focus is possible (but not set) + { + newfocus = i; + _elements.at(i)->SetFocus(1); // give this element focus + _elements.at(found)->SetFocus(0); // disable focus on other element + break; + } + } + catch (const std::exception& e) { } + } - if (newfocus == -1) { - for (i = 0; i < found; i++) { - try { - if (_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) { // focus is possible (but not set) - _elements.at(i)->SetFocus(1); // give this element focus - _elements.at(found)->SetFocus(0); // disable focus on other element - break; - } - } catch (const std::exception& e) { } - } - } - } + if(newfocus == -1) + { + for (i = 0; i < found; i++) + { + try + { + if(_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) // focus is possible (but not set) + { + _elements.at(i)->SetFocus(1); // give this element focus + _elements.at(found)->SetFocus(0); // disable focus on other element + break; + } + } + catch (const std::exception& e) { } + } + } + } } -int GuiWindow::GetSelected() { - // find selected element - int found = -1; - for (u8 i = 0; i < _elements.size(); i++) { - try { - if (_elements.at(i)->GetState() == STATE_SELECTED) { - found = i; - break; - } - } catch (const std::exception& e) { } - } - return found; +int GuiWindow::GetSelected() +{ + // find selected element + int found = -1; + for (u8 i = 0; i < _elements.size(); i++) + { + try + { + if(_elements.at(i)->GetState() == STATE_SELECTED) + { + found = i; + break; + } + } + catch (const std::exception& e) { } + } + return found; } // set element to left/right as selected // there's probably a more clever way to do this, but this way works -void GuiWindow::MoveSelectionHor(int dir) { - LOCK(this); - int found = -1; - u16 left = 0; - u16 top = 0; - u8 i = 0; +void GuiWindow::MoveSelectionHor(int dir) +{ + LOCK(this); + int found = -1; + u16 left = 0; + u16 top = 0; + u8 i = 0; - int selected = this->GetSelected(); + int selected = this->GetSelected(); - if (selected >= 0) { - left = _elements.at(selected)->GetLeft(); - top = _elements.at(selected)->GetTop(); - } + if(selected >= 0) + { + left = _elements.at(selected)->GetLeft(); + top = _elements.at(selected)->GetTop(); + } - // look for a button on the same row, to the left/right - for (i = 0; i < _elements.size(); i++) { - try { - if (_elements.at(i)->IsSelectable()) { - if (_elements.at(i)->GetLeft()*dir > left*dir && _elements.at(i)->GetTop() == top) { - if (found == -1) - found = i; - else if (_elements.at(i)->GetLeft()*dir < _elements.at(found)->GetLeft()*dir) - found = i; // this is a better match - } - } - } catch (const std::exception& e) { } - } - if (found >= 0) - goto matchfound; + // look for a button on the same row, to the left/right + for (i = 0; i < _elements.size(); i++) + { + try + { + if(_elements.at(i)->IsSelectable()) + { + if(_elements.at(i)->GetLeft()*dir > left*dir && _elements.at(i)->GetTop() == top) + { + if(found == -1) + found = i; + else if(_elements.at(i)->GetLeft()*dir < _elements.at(found)->GetLeft()*dir) + found = i; // this is a better match + } + } + } + catch (const std::exception& e) { } + } + if(found >= 0) + goto matchfound; - // match still not found, let's try the first button in the next row - for (i = 0; i < _elements.size(); i++) { - try { - if (_elements.at(i)->IsSelectable()) { - if (_elements.at(i)->GetTop()*dir > top*dir) { - if (found == -1) - found = i; - else if (_elements.at(i)->GetTop()*dir < _elements.at(found)->GetTop()*dir) - found = i; // this is a better match - else if (_elements.at(i)->GetTop()*dir == _elements.at(found)->GetTop()*dir - && - _elements.at(i)->GetLeft()*dir < _elements.at(found)->GetLeft()*dir) - found = i; // this is a better match - } - } - } catch (const std::exception& e) { } - } + // match still not found, let's try the first button in the next row + for (i = 0; i < _elements.size(); i++) + { + try + { + if(_elements.at(i)->IsSelectable()) + { + if(_elements.at(i)->GetTop()*dir > top*dir) + { + if(found == -1) + found = i; + else if(_elements.at(i)->GetTop()*dir < _elements.at(found)->GetTop()*dir) + found = i; // this is a better match + else if(_elements.at(i)->GetTop()*dir == _elements.at(found)->GetTop()*dir + && + _elements.at(i)->GetLeft()*dir < _elements.at(found)->GetLeft()*dir) + found = i; // this is a better match + } + } + } + catch (const std::exception& e) { } + } - // match found -matchfound: - if (found >= 0) { - _elements.at(found)->SetState(STATE_SELECTED); - if (selected >= 0) - _elements.at(selected)->ResetState(); - } + // match found + matchfound: + if(found >= 0) + { + _elements.at(found)->SetState(STATE_SELECTED); + if(selected >= 0) + _elements.at(selected)->ResetState(); + } } -void GuiWindow::MoveSelectionVert(int dir) { - LOCK(this); - int found = -1; - u16 left = 0; - u16 top = 0; - u8 i = 0; +void GuiWindow::MoveSelectionVert(int dir) +{ + LOCK(this); + int found = -1; + u16 left = 0; + u16 top = 0; + u8 i = 0; - int selected = this->GetSelected(); + int selected = this->GetSelected(); - if (selected >= 0) { - left = _elements.at(selected)->GetLeft(); - top = _elements.at(selected)->GetTop(); - } + if(selected >= 0) + { + left = _elements.at(selected)->GetLeft(); + top = _elements.at(selected)->GetTop(); + } - // look for a button above/below, with the least horizontal difference - for (i = 0; i < _elements.size(); i++) { - try { - if (_elements.at(i)->IsSelectable()) { - if (_elements.at(i)->GetTop()*dir > top*dir) { - if (found == -1) - found = i; - else if (_elements.at(i)->GetTop()*dir < _elements.at(found)->GetTop()*dir) - found = i; // this is a better match - else if (_elements.at(i)->GetTop()*dir == _elements.at(found)->GetTop()*dir - && - abs(_elements.at(i)->GetLeft() - left) < - abs(_elements.at(found)->GetLeft() - left)) - found = i; - } - } - } catch (const std::exception& e) { } - } - if (found >= 0) - goto matchfound; + // look for a button above/below, with the least horizontal difference + for (i = 0; i < _elements.size(); i++) + { + try + { + if(_elements.at(i)->IsSelectable()) + { + if(_elements.at(i)->GetTop()*dir > top*dir) + { + if(found == -1) + found = i; + else if(_elements.at(i)->GetTop()*dir < _elements.at(found)->GetTop()*dir) + found = i; // this is a better match + else if(_elements.at(i)->GetTop()*dir == _elements.at(found)->GetTop()*dir + && + abs(_elements.at(i)->GetLeft() - left) < + abs(_elements.at(found)->GetLeft() - left)) + found = i; + } + } + } + catch (const std::exception& e) { } + } + if(found >= 0) + goto matchfound; - // match found -matchfound: - if (found >= 0) { - _elements.at(found)->SetState(STATE_SELECTED); - if (selected >= 0) - _elements.at(selected)->ResetState(); - } + // match found + matchfound: + if(found >= 0) + { + _elements.at(found)->SetState(STATE_SELECTED); + if(selected >= 0) + _elements.at(selected)->ResetState(); + } } -void GuiWindow::Update(GuiTrigger * t) { - LOCK(this); - if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) - return; +void GuiWindow::Update(GuiTrigger * t) +{ + LOCK(this); + if(_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) + return; - for (u8 i = 0; i < _elements.size(); i++) { - try { - _elements.at(i)->Update(t); - } catch (const std::exception& e) { } - } + for (u8 i = 0; i < _elements.size(); i++) + { + try { _elements.at(i)->Update(t); } + catch (const std::exception& e) { } + } - this->ToggleFocus(t); + this->ToggleFocus(t); - if (focus) { // only send actions to this window if it's in focus - // pad/joystick navigation - if (t->Right()) - this->MoveSelectionHor(1); - else if (t->Left()) - this->MoveSelectionHor(-1); - else if (t->Down()) - this->MoveSelectionVert(1); - else if (t->Up()) - this->MoveSelectionVert(-1); - } + if(focus) // only send actions to this window if it's in focus + { + // pad/joystick navigation + if(t->Right()) + this->MoveSelectionHor(1); + else if(t->Left()) + this->MoveSelectionHor(-1); + else if(t->Down()) + this->MoveSelectionVert(1); + else if(t->Up()) + this->MoveSelectionVert(-1); + } - if (updateCB) - updateCB(this); + if(updateCB) + updateCB(this); } diff --git a/source/listfiles.c b/source/listfiles.c index 2609012f..d016b581 100644 --- a/source/listfiles.c +++ b/source/listfiles.c @@ -32,63 +32,72 @@ bool findfile(const char * filename, const char * path) { } bool subfoldercreate(const char * fullpath) { - //check forsubfolders - char dir[300]; - char * pch = NULL; - u32 len; - struct stat st; + //check forsubfolders + char dir[300]; + char * pch = NULL; + u32 len; + struct stat st; - strlcpy(dir, fullpath, sizeof(dir)); - len = strlen(dir); - if (len && len< sizeof(dir)-2 && dir[len-1] != '/') { - dir[len++] = '/'; - dir[len] = '\0'; - } - if (stat(dir, &st) != 0) { // fullpath not exist? - while (len && dir[len-1] == '/') - dir[--len] = '\0'; // remove all trailing / - pch = strrchr(dir, '/'); - if (pch == NULL) return false; - *pch = '\0'; - if (subfoldercreate(dir)) { - *pch = '/'; - if (mkdir(dir, 0777) == -1) - return false; - } else - return false; - } - return true; + strlcpy(dir, fullpath, sizeof(dir)); + len = strlen(dir); + if(len && len< sizeof(dir)-2 && dir[len-1] != '/') + { + dir[len++] = '/'; + dir[len] = '\0'; + } + if (stat(dir, &st) != 0) // fullpath not exist? + { + while(len && dir[len-1] == '/') + dir[--len] = '\0'; // remove all trailing / + pch = strrchr(dir, '/'); + if(pch == NULL) return false; + *pch = '\0'; + if(subfoldercreate(dir)) + { + *pch = '/'; + if (mkdir(dir, 0777) == -1) + return false; + } + else + return false; + } + return true; } bool subfolderremove(const char * fullpath, const char*fp) { - struct stat st; - if (stat(fullpath, &st) != 0) // fullpath not exist? - return false; - if (S_ISDIR(st.st_mode)) { - DIR_ITER *dir = NULL; - char filename[256]; - bool cont = true; - while (cont) { - cont = false; - dir = diropen(fullpath); - if (dir) { - char* bind = fullpath[strlen(fullpath)-1] == '/' ? "":"/"; - while (dirnext(dir,filename,&st) == 0) { - if (strcmp(filename,".") != 0 && strcmp(filename,"..") != 0) { - char currentname[256]; - if (S_ISDIR(st.st_mode)) - snprintf(currentname, sizeof(currentname), "%s%s%s/", fullpath, bind, filename); - else - snprintf(currentname, sizeof(currentname), "%s%s%s", fullpath, bind, filename); - subfolderremove(currentname, fp); - cont = true; - break; - } - } - dirclose(dir); - } - } - } - return unlink(fullpath) == 0; + struct stat st; + if (stat(fullpath, &st) != 0) // fullpath not exist? + return false; + if(S_ISDIR(st.st_mode)) + { + DIR_ITER *dir = NULL; + char filename[256]; + bool cont = true; + while(cont) + { + cont = false; + dir = diropen(fullpath); + if(dir) + { + char* bind = fullpath[strlen(fullpath)-1] == '/' ? "":"/"; + while (dirnext(dir,filename,&st) == 0) + { + if (strcmp(filename,".") != 0 && strcmp(filename,"..") != 0) + { + char currentname[256]; + if(S_ISDIR(st.st_mode)) + snprintf(currentname, sizeof(currentname), "%s%s%s/", fullpath, bind, filename); + else + snprintf(currentname, sizeof(currentname), "%s%s%s", fullpath, bind, filename); + subfolderremove(currentname, fp); + cont = true; + break; + } + } + dirclose(dir); + } + } + } + return unlink(fullpath) == 0; } char * GetFileName(int i) { return alldirfiles[i]; @@ -130,7 +139,8 @@ bool checkfile(char * path) { return false; } -bool SearchFile(const char * searchpath, const char * searched_filename, char * outfilepath) { +bool SearchFile(const char * searchpath, const char * searched_filename, char * outfilepath) +{ struct stat st; DIR_ITER *dir = NULL; bool result = false; @@ -139,28 +149,35 @@ bool SearchFile(const char * searchpath, const char * searched_filename, char * char pathptr[strlen(searchpath)+1]; snprintf(pathptr, sizeof(pathptr), "%s", searchpath); - if (pathptr[strlen(pathptr)-1] == '/') { + if(pathptr[strlen(pathptr)-1] == '/') + { pathptr[strlen(pathptr)-1] = '\0'; } dir = diropen(pathptr); - if (!dir) + if(!dir) return false; - while (dirnext(dir,filename,&st) == 0 && result == false) { - if (strcasecmp(filename, searched_filename) == 0) { - if (outfilepath) { - sprintf(outfilepath, "%s/%s", pathptr, filename); - } - result = true; - } else if ((st.st_mode & S_IFDIR) != 0) { - if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) { + while (dirnext(dir,filename,&st) == 0 && result == false) + { + if(strcasecmp(filename, searched_filename) == 0) + { + if(outfilepath) + { + sprintf(outfilepath, "%s/%s", pathptr, filename); + } + result = true; + } + else if((st.st_mode & S_IFDIR) != 0) + { + if(strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) + { char newpath[1024]; snprintf(newpath, sizeof(newpath), "%s/%s", pathptr, filename); result = SearchFile(newpath, searched_filename, outfilepath); } } - } + } dirclose(dir); return result; diff --git a/source/lstub.c b/source/lstub.c index 20d6ef80..b00d1f8f 100644 --- a/source/lstub.c +++ b/source/lstub.c @@ -18,103 +18,109 @@ #define TITLE_7(x) ((u8)((x) >> 56)) #define TITLE_ID(x,y) (((u64)(x) << 32) | (y)) -s32 Set_Stub(u64 reqID) { - u32 tmdsize; - u64 tid = 0; - u64 *list; - u32 titlecount; - s32 ret; - u32 i; +s32 Set_Stub(u64 reqID) +{ + u32 tmdsize; + u64 tid = 0; + u64 *list; + u32 titlecount; + s32 ret; + u32 i; - ret = ES_GetNumTitles(&titlecount); - if (ret < 0) - return WII_EINTERNAL; + ret = ES_GetNumTitles(&titlecount); + if(ret < 0) + return WII_EINTERNAL; - list = memalign(32, titlecount * sizeof(u64) + 32); + list = memalign(32, titlecount * sizeof(u64) + 32); - ret = ES_GetTitles(list, titlecount); - if (ret < 0) { - free(list); - return WII_EINTERNAL; - } + ret = ES_GetTitles(list, titlecount); + if(ret < 0) { + free(list); + return WII_EINTERNAL; + } + + for(i=0; i #include //#include -extern "C" { +extern "C" +{ extern void __exception_setreload(int t); } @@ -66,7 +67,8 @@ PartList partitions; u8 dbvideo =0; -static void BootUpProblems() { +static void BootUpProblems() +{ s32 ret2; // load main font from file, or default to built-in font @@ -76,7 +78,8 @@ static void BootUpProblems() { GuiImageData bootimageData(gxlogo_png); GuiImage bootimage(&bootimageData); - GuiText boottext(NULL, 20, (GXColor) {255, 255, 255, 255}); + GuiText boottext(NULL, 20, (GXColor) {255, 255, 255, 255} + ); boottext.SetPosition(200, 240-1.2*bootimage.GetHeight()/2+250); bootimage.SetPosition(320-1.2*bootimage.GetWidth()/2, 240-1.2*bootimage.GetHeight()/2); bootimage.SetScale(1.2); @@ -89,7 +92,8 @@ static void BootUpProblems() { time_t curtime; time_t endtime = time(0) + 30; - do { + do + { /*ret2 = IOS_ReloadIOSsafe(249); if (ret2 < 0) { ret2 = IOS_ReloadIOSsafe(222); @@ -108,7 +112,8 @@ static void BootUpProblems() { USBDevice_deInit(); USBDevice_Init(); ret2 = WBFS_Init(WBFS_DEVICE_USB); - if (ret2 >= 0) { + if (ret2 >= 0) + { boottext.SetText("Loading..."); bootimage.Draw(); boottext.Draw(); @@ -117,13 +122,14 @@ static void BootUpProblems() { } curtime = time(0); boottext.SetTextf("Waiting for your slow USB Device: %i secs...", int(endtime-curtime)); - while (curtime == time(0)) { + while(curtime == time(0)) + { boottext.Draw(); bootimage.Draw(); if (endtime-curtime<15)usbimage.Draw(); Menu_Render(); } - } while ((endtime-time(0)) > 0); + } while((endtime-time(0)) > 0); /*if(ret2 < 0) { boottext.SetText("ERROR: USB device could not be loaded!"); @@ -135,7 +141,8 @@ static void BootUpProblems() { }*/ ///delete font to load up custom if set - if (fontSystem) { + if(fontSystem) + { delete fontSystem; fontSystem = NULL; } @@ -144,15 +151,17 @@ static void BootUpProblems() { unsigned int *xfb = NULL; -void InitTextVideo () { +void InitTextVideo () +{ gprintf("\nInitTextVideo ()"); - if (textVideoInit) { + if (textVideoInit) + { gprintf("...0"); return; } dbvideo=1; VIDEO_Init(); - // get default video mode + // get default video mode GXRModeObj *vmode = VIDEO_GetPreferredMode(NULL); // widescreen fix @@ -183,11 +192,13 @@ void InitTextVideo () { int -main(int argc, char *argv[]) { +main(int argc, char *argv[]) +{ setlocale(LC_ALL, "en.UTF-8"); geckoinit = InitGecko(); - if (hbcStubAvailable() || geckoinit) { + if (hbcStubAvailable() || geckoinit) + { InitTextVideo(); } @@ -205,7 +216,8 @@ main(int argc, char *argv[]) { // This part is added, because we need a identify patched ios // printf("\n\tReloading into ios 236"); - if (IOS_ReloadIOSsafe(236) < 0) { + if (IOS_ReloadIOSsafe(236) < 0) + { // printf("\n\tIOS 236 not found, reloading into 36"); IOS_ReloadIOSsafe(36); } @@ -219,12 +231,14 @@ main(int argc, char *argv[]) { bool startupproblem = false; bool bootDevice_found=false; - if (argc >= 1) { - if (!strncasecmp(argv[0], "usb:/", 5)) { + if (argc >= 1) + { + if (!strncasecmp(argv[0], "usb:/", 5)) + { strcpy(bootDevice, "USB:"); bootDevice_found = true; } else if (!strncasecmp(argv[0], "sd:/", 4)) - bootDevice_found = true; + bootDevice_found = true; } printf("\n\tInitializing controllers"); @@ -241,10 +255,12 @@ main(int argc, char *argv[]) { ios249rev = getIOSrev(0x00000001000000f9ll); //if we don't like either of the cIOS then scram - if (!(ios222rev==4 || (ios249rev>=9 && ios249rev<65280))) { + if (!(ios222rev==4 || (ios249rev>=9 && ios249rev<65280))) + { InitTextVideo(); printf("\x1b[2J"); - if ((ios222rev < 0 && ios222rev != WII_EINSTALL) && (ios249rev < 0 && ios249rev != WII_EINSTALL)) { + if ((ios222rev < 0 && ios222rev != WII_EINSTALL) && (ios249rev < 0 && ios249rev != WII_EINSTALL)) + { printf("\n\n\n\tWARNING!"); printf("\n\tUSB Loader GX needs unstubbed cIOS 222 v4 or 249 v9+"); printf("\n\n\tWe cannot determine the versions on your system,\n\tsince you have no patched ios 36 or 236 installed."); @@ -252,7 +268,9 @@ main(int argc, char *argv[]) { printf("\n\tand you should go figure out how to get some cios action going on\n\tin your Wii."); printf("\n\n\tThis message will show every time."); sleep(5); - } else { + } + else + { printf("\n\n\n\tERROR!"); printf("\n\tUSB Loader GX needs unstubbed cIOS 222 v4 or 249 v9+"); printf("\n\n\tI found \n\t\t222 = %d%s",ios222rev,ios222rev==65280?" (Stubbed by 4.2 update)":""); @@ -272,22 +290,26 @@ main(int argc, char *argv[]) { printf("%d", ret); - if (ret < 0) { + if (ret < 0) + { printf("\n\tIOS 249 failed, reloading ios 222..."); ret = IOS_ReloadIOSsafe(222); printf("%d", ret); - if (ret < 0) { + if (ret < 0) + { printf("\n\tIOS 222 failed, reloading ios 250..."); ret = IOS_ReloadIOSsafe(250); printf("%d", ret); - if (ret < 0) { + if(ret < 0) + { printf("\n\tIOS 250 failed, reloading ios 223..."); ret = IOS_ReloadIOSsafe(223); printf("%d", ret); - if (ret < 0) { + if (ret < 0) + { printf("\n\tERROR: cIOS could not be loaded!\n"); sleep(5); SYS_ResetSystem(SYS_RETURNTOMENU, 0, 0); @@ -306,7 +328,8 @@ main(int argc, char *argv[]) { ret = WBFS_Init(WBFS_DEVICE_USB); printf("%d", ret); - if (ret < 0) { + if (ret < 0) + { printf("\n\tYou have issues with a slow disc, or a difficult disc\n\tReloading 222..."); ret = IOS_ReloadIOSsafe(222); printf("%d", ret); @@ -333,7 +356,8 @@ main(int argc, char *argv[]) { ret = WBFS_Init(WBFS_DEVICE_USB); printf("%d", ret); - if (ret < 0) { + if(ret < 0) + { // printf("\n\tSleeping for 4 seconds"); // sleep(4); InitVideo(); // Initialise video @@ -351,14 +375,15 @@ main(int argc, char *argv[]) { printf("\n\tInitialize usb device"); USBDevice_Init(); // and mount USB:/ - if (!bootDevice_found) { + if (!bootDevice_found) + { printf("\n\tSearch for configuration file"); //try USB //left in all the dol and elf files in this check in case this is the first time running the app and they dont have the config if (checkfile((char*) "USB:/config/GXglobal.cfg") || (checkfile((char*) "USB:/apps/usbloader_gx/boot.elf")) - || checkfile((char*) "USB:/apps/usbloadergx/boot.dol") || (checkfile((char*) "USB:/apps/usbloadergx/boot.elf")) - || checkfile((char*) "USB:/apps/usbloader_gx/boot.dol")) + || checkfile((char*) "USB:/apps/usbloadergx/boot.dol") || (checkfile((char*) "USB:/apps/usbloadergx/boot.elf")) + || checkfile((char*) "USB:/apps/usbloader_gx/boot.dol")) strcpy(bootDevice, "USB:"); printf("\n\tConfiguration file is on %s", bootDevice); @@ -369,7 +394,8 @@ main(int argc, char *argv[]) { char GXGlobal_cfg[26]; sprintf(GXGlobal_cfg, "%s/config/GXGlobal.cfg", bootDevice); FILE *fp = fopen(GXGlobal_cfg, "r"); - if (fp) { + if (fp) + { fclose(fp); } @@ -381,7 +407,8 @@ main(int argc, char *argv[]) { /* Load Custom IOS */ if ((Settings.cios == ios222 && IOS_GetVersion() != 222) || - (Settings.cios == ios223 && IOS_GetVersion() != 223)) { + (Settings.cios == ios223 && IOS_GetVersion() != 223)) + { printf("\n\tReloading IOS to config setting (%d)...", ios222 ? 222 : 223); SDCard_deInit(); // unmount SD for reloading IOS USBDevice_deInit(); // unmount USB for reloading IOS @@ -390,7 +417,8 @@ main(int argc, char *argv[]) { printf("%d", ret); SDCard_Init(); load_ehc_module(); - if (ret < 0) { + if (ret < 0) + { SDCard_deInit(); Settings.cios = ios249; ret = IOS_ReloadIOSsafe(249); @@ -401,7 +429,8 @@ main(int argc, char *argv[]) { USBDevice_Init(); // and mount USB:/ WBFS_Init(WBFS_DEVICE_USB); } else if ((Settings.cios == ios249 && IOS_GetVersion() != 249) || - (Settings.cios == ios250 && IOS_GetVersion() != 250)) { + (Settings.cios == ios250 && IOS_GetVersion() != 250)) + { printf("\n\tReloading IOS to config setting (%d)...", ios249 ? 249 : 250); SDCard_deInit(); // unmount SD for reloading IOS @@ -409,7 +438,8 @@ main(int argc, char *argv[]) { USBStorage_Deinit(); ret = IOS_ReloadIOSsafe(ios249 ? 249 : 250); printf("%d", ret); - if (ret < 0) { + if (ret < 0) + { Settings.cios = ios222; ret = IOS_ReloadIOSsafe(222); SDCard_Init(); @@ -423,7 +453,8 @@ main(int argc, char *argv[]) { // Partition_GetList(&partitions); - if (ret < 0) { + if (ret < 0) + { printf("\nERROR: cIOS could not be loaded!"); sleep(5); exit(0); @@ -437,7 +468,8 @@ main(int argc, char *argv[]) { //if a ID was passed via args copy it and try to boot it after the partition is mounted //its not really a headless mode. more like hairless. - if (argc > 1 && argv[1]) { + if (argc > 1 && argv[1]) + { if (strlen(argv[1])==6) strncpy(headlessID, argv[1], sizeof(headlessID)); } @@ -445,7 +477,7 @@ main(int argc, char *argv[]) { //! Init the rest of the System Sys_Init(); Wpad_Init(); - if (!startupproblem) + if(!startupproblem) InitVideo(); InitAudio(); // Initialize audio diff --git a/source/memory/mem2.cpp b/source/memory/mem2.cpp index 4b2cb811..a8b942ae 100644 --- a/source/memory/mem2.cpp +++ b/source/memory/mem2.cpp @@ -12,28 +12,34 @@ u32 MALLOC_MEM2 = 0; static CMEM2Alloc g_mem2gp; -void MEM2_init(unsigned int mem2Size) { - g_mem2gp.init(mem2Size); +void MEM2_init(unsigned int mem2Size) +{ + g_mem2gp.init(mem2Size); } -void MEM2_cleanup(void) { - g_mem2gp.cleanup(); +void MEM2_cleanup(void) +{ + g_mem2gp.cleanup(); } -extern "C" void *MEM2_alloc(unsigned int s) { - return g_mem2gp.allocate(s); +extern "C" void *MEM2_alloc(unsigned int s) +{ + return g_mem2gp.allocate(s); } -extern "C" void MEM2_free(void *p) { - g_mem2gp.release(p); +extern "C" void MEM2_free(void *p) +{ + g_mem2gp.release(p); } -extern "C" void *MEM2_realloc(void *p, unsigned int s) { - return g_mem2gp.reallocate(p, s); +extern "C" void *MEM2_realloc(void *p, unsigned int s) +{ + return g_mem2gp.reallocate(p, s); } -extern "C" unsigned int MEM2_usableSize(void *p) { - return CMEM2Alloc::usableSize(p); +extern "C" unsigned int MEM2_usableSize(void *p) +{ + return CMEM2Alloc::usableSize(p); } // Give priority to MEM2 for big allocations @@ -42,122 +48,138 @@ extern "C" unsigned int MEM2_usableSize(void *p) { // - newlib uses its malloc internally (for *printf for example) so it should always have some memory left bool g_bigGoesToMem2 = false; -void MEM2_takeBigOnes(bool b) { - g_bigGoesToMem2 = b; +void MEM2_takeBigOnes(bool b) +{ + g_bigGoesToMem2 = b; } -extern "C" { +extern "C" +{ - extern __typeof(malloc) __real_malloc; - extern __typeof(calloc) __real_calloc; - extern __typeof(realloc) __real_realloc; - extern __typeof(memalign) __real_memalign; - extern __typeof(free) __real_free; - extern __typeof(malloc_usable_size) __real_malloc_usable_size; +extern __typeof(malloc) __real_malloc; +extern __typeof(calloc) __real_calloc; +extern __typeof(realloc) __real_realloc; +extern __typeof(memalign) __real_memalign; +extern __typeof(free) __real_free; +extern __typeof(malloc_usable_size) __real_malloc_usable_size; - void *__wrap_malloc(size_t size) { - void *p; - if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) { - p = MEM2_alloc(size); - if (p != 0) { - return p; - } - return __real_malloc(size); - } - p = __real_malloc(size); - if (p != 0) { - return p; - } - return MEM2_alloc(size); - } +void *__wrap_malloc(size_t size) +{ + void *p; + if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) + { + p = MEM2_alloc(size); + if (p != 0) { + return p; + } + return __real_malloc(size); + } + p = __real_malloc(size); + if (p != 0) { + return p; + } + return MEM2_alloc(size); +} - void *__wrap_calloc(size_t n, size_t size) { - void *p; - if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) { - p = MEM2_alloc(n * size); - if (p != 0) { - memset(p, 0, n * size); - return p; - } - return __real_calloc(n, size); - } - p = __real_calloc(n, size); - if (p != 0) { - return p; - } - p = MEM2_alloc(n * size); - if (p != 0) { - memset(p, 0, n * size); - } - return p; - } +void *__wrap_calloc(size_t n, size_t size) +{ + void *p; + if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) + { + p = MEM2_alloc(n * size); + if (p != 0) + { + memset(p, 0, n * size); + return p; + } + return __real_calloc(n, size); + } + p = __real_calloc(n, size); + if (p != 0) { + return p; + } + p = MEM2_alloc(n * size); + if (p != 0) { + memset(p, 0, n * size); + } + return p; +} - void *__wrap_memalign(size_t a, size_t size) { - void *p; - if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) { - if (a <= 32 && 32 % a == 0) { - p = MEM2_alloc(size); - if (p != 0) { - return p; - } - } - return __real_memalign(a, size); - } - p = __real_memalign(a, size); - if (p != 0 || a > 32 || 32 % a != 0) { - return p; - } +void *__wrap_memalign(size_t a, size_t size) +{ + void *p; + if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) + { + if (a <= 32 && 32 % a == 0) + { + p = MEM2_alloc(size); + if (p != 0) { + return p; + } + } + return __real_memalign(a, size); + } + p = __real_memalign(a, size); + if (p != 0 || a > 32 || 32 % a != 0) { + return p; + } - return MEM2_alloc(size); - } + return MEM2_alloc(size); +} - void __wrap_free(void *p) { - if (((u32)p & 0x10000000) != 0) { - MEM2_free(p); - } else { - __real_free(p); - } - } +void __wrap_free(void *p) +{ + if (((u32)p & 0x10000000) != 0) { + MEM2_free(p); + } else { + __real_free(p); + } +} - void *__wrap_realloc(void *p, size_t size) { - void *n; - // ptr from mem2 - if (((u32)p & 0x10000000) != 0 || (p == 0 && g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE)) { - n = MEM2_realloc(p, size); - if (n != 0) { - return n; - } - n = __real_malloc(size); - if (n == 0) { - return 0; - } - if (p != 0) { - memcpy(n, p, MEM2_usableSize(p) < size ? MEM2_usableSize(p) : size); - MEM2_free(p); - } - return n; - } - // ptr from malloc - n = __real_realloc(p, size); - if (n != 0) { - return n; - } - n = MEM2_alloc(size); - if (n == 0) { - return 0; - } - if (p != 0) { - memcpy(n, p, __real_malloc_usable_size(p) < size ? __real_malloc_usable_size(p) : size); - __real_free(p); - } - return n; - } +void *__wrap_realloc(void *p, size_t size) +{ + void *n; + // ptr from mem2 + if (((u32)p & 0x10000000) != 0 || (p == 0 && g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE)) + { + n = MEM2_realloc(p, size); + if (n != 0) { + return n; + } + n = __real_malloc(size); + if (n == 0) { + return 0; + } + if (p != 0) + { + memcpy(n, p, MEM2_usableSize(p) < size ? MEM2_usableSize(p) : size); + MEM2_free(p); + } + return n; + } + // ptr from malloc + n = __real_realloc(p, size); + if (n != 0) { + return n; + } + n = MEM2_alloc(size); + if (n == 0) { + return 0; + } + if (p != 0) + { + memcpy(n, p, __real_malloc_usable_size(p) < size ? __real_malloc_usable_size(p) : size); + __real_free(p); + } + return n; +} - size_t __wrap_malloc_usable_size(void *p) { - if (((u32)p & 0x10000000) != 0) - return MEM2_usableSize(p); - return __real_malloc_usable_size(p); - } +size_t __wrap_malloc_usable_size(void *p) +{ + if (((u32)p & 0x10000000) != 0) + return MEM2_usableSize(p); + return __real_malloc_usable_size(p); +} } diff --git a/source/memory/mem2.h b/source/memory/mem2.h index df9815b6..410705f6 100644 --- a/source/memory/mem2.h +++ b/source/memory/mem2.h @@ -5,13 +5,14 @@ #define __MEM2_HPP #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - void *MEM2_alloc(unsigned int s); - void *MEM2_realloc(void *p, unsigned int s); - void MEM2_free(void *p); - unsigned int MEM2_usableSize(void *p); +void *MEM2_alloc(unsigned int s); +void *MEM2_realloc(void *p, unsigned int s); +void MEM2_free(void *p); +unsigned int MEM2_usableSize(void *p); #ifdef __cplusplus } diff --git a/source/memory/mem2alloc.cpp b/source/memory/mem2alloc.cpp index 4bdfa71a..83d2cb7a 100644 --- a/source/memory/mem2alloc.cpp +++ b/source/memory/mem2alloc.cpp @@ -6,178 +6,193 @@ #include -class LockMutex { - mutex_t &m_mutex; +class LockMutex +{ + mutex_t &m_mutex; public: - LockMutex(mutex_t &m) : m_mutex(m) { - LWP_MutexLock(m_mutex); - } - ~LockMutex(void) { - LWP_MutexUnlock(m_mutex); - } + LockMutex(mutex_t &m) : m_mutex(m) { LWP_MutexLock(m_mutex); } + ~LockMutex(void) { LWP_MutexUnlock(m_mutex); } }; -void CMEM2Alloc::init(unsigned int size) { - m_baseAddress = (SBlock *)(((u32)SYS_GetArena2Lo() + 31) & ~31); - m_endAddress = (SBlock *)((char *)m_baseAddress + std::min(size * 0x100000, SYS_GetArena2Size() & ~31)); - if (m_endAddress > (SBlock *)0x93000000) // See loader/disc.c - m_endAddress = (SBlock *)0x93000000; - SYS_SetArena2Lo(m_endAddress); - LWP_MutexInit(&m_mutex, 0); +void CMEM2Alloc::init(unsigned int size) +{ + m_baseAddress = (SBlock *)(((u32)SYS_GetArena2Lo() + 31) & ~31); + m_endAddress = (SBlock *)((char *)m_baseAddress + std::min(size * 0x100000, SYS_GetArena2Size() & ~31)); + if (m_endAddress > (SBlock *)0x93000000) // See loader/disc.c + m_endAddress = (SBlock *)0x93000000; + SYS_SetArena2Lo(m_endAddress); + LWP_MutexInit(&m_mutex, 0); } -void CMEM2Alloc::init(void *addr, void *end) { - m_baseAddress = (SBlock *)(((u32)addr + 31) & ~31); - m_endAddress = (SBlock *)((u32)end & ~31); - LWP_MutexInit(&m_mutex, 0); +void CMEM2Alloc::init(void *addr, void *end) +{ + m_baseAddress = (SBlock *)(((u32)addr + 31) & ~31); + m_endAddress = (SBlock *)((u32)end & ~31); + LWP_MutexInit(&m_mutex, 0); } -void CMEM2Alloc::cleanup(void) { - LWP_MutexDestroy(m_mutex); - m_mutex = 0; - m_first = 0; +void CMEM2Alloc::cleanup(void) +{ + LWP_MutexDestroy(m_mutex); + m_mutex = 0; + m_first = 0; // // Try to release the range we took through SYS functions // if (SYS_GetArena2Lo() == m_endAdress) // SYS_SetArena2Lo(m_baseAddress); - m_baseAddress = 0; - m_endAddress = 0; + m_baseAddress = 0; + m_endAddress = 0; } -void CMEM2Alloc::clear(void) { - m_first = 0; - memset(m_baseAddress, 0, (u8 *)m_endAddress - (u8 *)m_endAddress); +void CMEM2Alloc::clear(void) +{ + m_first = 0; + memset(m_baseAddress, 0, (u8 *)m_endAddress - (u8 *)m_endAddress); } -unsigned int CMEM2Alloc::usableSize(void *p) { - return p == 0 ? 0 : ((SBlock *)p - 1)->s * sizeof (SBlock); +unsigned int CMEM2Alloc::usableSize(void *p) +{ + return p == 0 ? 0 : ((SBlock *)p - 1)->s * sizeof (SBlock); } -void *CMEM2Alloc::allocate(unsigned int s) { - if (s == 0) - s = 1; - // - LockMutex lock(m_mutex); - // - s = (s - 1) / sizeof (SBlock) + 1; - // First block - if (m_first == 0) { - if (m_baseAddress + s + 1 >= m_endAddress) - return 0; - m_first = m_baseAddress; - m_first->next = 0; - m_first->prev = 0; - m_first->s = s; - m_first->f = false; - return (void *)(m_first + 1); - } - // Search for a free block - SBlock *i; - SBlock *j; - for (i = m_first; i != 0; i = i->next) { - if (i->f && i->s >= s) - break; - j = i; - } - // Create a new block - if (i == 0) { - i = j + j->s + 1; - if (i + s + 1 >= m_endAddress) - return 0; - j->next = i; - i->prev = j; - i->next = 0; - i->s = s; - i->f = false; - return (void *)(i + 1); - } - // Reuse a free block - i->f = false; - // Split it - if (i->s > s + 1) { - j = i + s + 1; - j->f = true; - j->s = i->s - s - 1; - i->s = s; - j->next = i->next; - j->prev = i; - i->next = j; - if (j->next != 0) - j->next->prev = j; - } - return (void *)(i + 1); +void *CMEM2Alloc::allocate(unsigned int s) +{ + if (s == 0) + s = 1; + // + LockMutex lock(m_mutex); + // + s = (s - 1) / sizeof (SBlock) + 1; + // First block + if (m_first == 0) + { + if (m_baseAddress + s + 1 >= m_endAddress) + return 0; + m_first = m_baseAddress; + m_first->next = 0; + m_first->prev = 0; + m_first->s = s; + m_first->f = false; + return (void *)(m_first + 1); + } + // Search for a free block + SBlock *i; + SBlock *j; + for (i = m_first; i != 0; i = i->next) + { + if (i->f && i->s >= s) + break; + j = i; + } + // Create a new block + if (i == 0) + { + i = j + j->s + 1; + if (i + s + 1 >= m_endAddress) + return 0; + j->next = i; + i->prev = j; + i->next = 0; + i->s = s; + i->f = false; + return (void *)(i + 1); + } + // Reuse a free block + i->f = false; + // Split it + if (i->s > s + 1) + { + j = i + s + 1; + j->f = true; + j->s = i->s - s - 1; + i->s = s; + j->next = i->next; + j->prev = i; + i->next = j; + if (j->next != 0) + j->next->prev = j; + } + return (void *)(i + 1); } -void CMEM2Alloc::release(void *p) { - if (p == 0) - return; - LockMutex lock(m_mutex); - SBlock *i = (SBlock *)p - 1; - i->f = true; - // Merge with previous block - if (i->prev != 0 && i->prev->f) { - i = i->prev; - i->s += i->next->s + 1; - i->next = i->next->next; - if (i->next != 0) - i->next->prev = i; - } - // Merge with next block - if (i->next != 0 && i->next->f) { - i->s += i->next->s + 1; - i->next = i->next->next; - if (i->next != 0) - i->next->prev = i; - } +void CMEM2Alloc::release(void *p) +{ + if (p == 0) + return; + LockMutex lock(m_mutex); + SBlock *i = (SBlock *)p - 1; + i->f = true; + // Merge with previous block + if (i->prev != 0 && i->prev->f) + { + i = i->prev; + i->s += i->next->s + 1; + i->next = i->next->next; + if (i->next != 0) + i->next->prev = i; + } + // Merge with next block + if (i->next != 0 && i->next->f) + { + i->s += i->next->s + 1; + i->next = i->next->next; + if (i->next != 0) + i->next->prev = i; + } } -void *CMEM2Alloc::reallocate(void *p, unsigned int s) { - SBlock *i; - SBlock *j; - void *n; +void *CMEM2Alloc::reallocate(void *p, unsigned int s) +{ + SBlock *i; + SBlock *j; + void *n; - if (s == 0) - s = 1; - if (p == 0) - return allocate(s); - i = (SBlock *)p - 1; - s = (s - 1) / sizeof (SBlock) + 1; - { - LockMutex lock(m_mutex); - // Last block - if (i->next == 0 && i + s + 1 < m_endAddress) { - i->s = s; - return p; - } - // Size <= current size + next block - if (i->s < s && i->next->f && i->s + i->next->s + 1 >= s) { - // Merge - i->s += i->next->s + 1; - i->next = i->next->next; - if (i->next != 0) - i->next->prev = i; - } - // Size <= current size - if (i->s >= s) { - // Split - if (i->s > s + 1) { - j = i + s + 1; - j->f = true; - j->s = i->s - s - 1; - i->s = s; - j->next = i->next; - j->prev = i; - i->next = j; - if (j->next != 0) - j->next->prev = j; - } - return p; - } - } - // Size > current size - n = allocate(s * sizeof (SBlock)); - if (n == 0) - return 0; - memcpy(n, p, i->s * sizeof (SBlock)); - release(p); - return n; + if (s == 0) + s = 1; + if (p == 0) + return allocate(s); + i = (SBlock *)p - 1; + s = (s - 1) / sizeof (SBlock) + 1; + { + LockMutex lock(m_mutex); + // Last block + if (i->next == 0 && i + s + 1 < m_endAddress) + { + i->s = s; + return p; + } + // Size <= current size + next block + if (i->s < s && i->next->f && i->s + i->next->s + 1 >= s) + { + // Merge + i->s += i->next->s + 1; + i->next = i->next->next; + if (i->next != 0) + i->next->prev = i; + } + // Size <= current size + if (i->s >= s) + { + // Split + if (i->s > s + 1) + { + j = i + s + 1; + j->f = true; + j->s = i->s - s - 1; + i->s = s; + j->next = i->next; + j->prev = i; + i->next = j; + if (j->next != 0) + j->next->prev = j; + } + return p; + } + } + // Size > current size + n = allocate(s * sizeof (SBlock)); + if (n == 0) + return 0; + memcpy(n, p, i->s * sizeof (SBlock)); + release(p); + return n; } diff --git a/source/memory/mem2alloc.h b/source/memory/mem2alloc.h index e01a5ce5..6d681b09 100644 --- a/source/memory/mem2alloc.h +++ b/source/memory/mem2alloc.h @@ -6,41 +6,36 @@ #include -class CMEM2Alloc { +class CMEM2Alloc +{ public: - void *allocate(unsigned int s); - void release(void *p); - void *reallocate(void *p, unsigned int s); - void init(unsigned int size); - void init(void *addr, void *end); - void cleanup(void); - void clear(void); - static unsigned int usableSize(void *p); - void forceEndAddress(void *newAddr) { - m_endAddress = (SBlock *)newAddr; - } - void *getEndAddress(void) const { - return m_endAddress; - } - void info(void *&address, unsigned int &size) const { - address = m_baseAddress; - size = (const char *)m_endAddress - (const char *)m_baseAddress; - } - // - CMEM2Alloc(void) : m_baseAddress(0), m_endAddress(0), m_first(0), m_mutex(0) { } + void *allocate(unsigned int s); + void release(void *p); + void *reallocate(void *p, unsigned int s); + void init(unsigned int size); + void init(void *addr, void *end); + void cleanup(void); + void clear(void); + static unsigned int usableSize(void *p); + void forceEndAddress(void *newAddr) { m_endAddress = (SBlock *)newAddr; } + void *getEndAddress(void) const { return m_endAddress; } + void info(void *&address, unsigned int &size) const { address = m_baseAddress; size = (const char *)m_endAddress - (const char *)m_baseAddress; } + // + CMEM2Alloc(void) : m_baseAddress(0), m_endAddress(0), m_first(0), m_mutex(0) { } private: - struct SBlock { - unsigned int s; - SBlock *next; - SBlock *prev; - bool f; - } __attribute__((aligned(32))); - SBlock *m_baseAddress; - SBlock *m_endAddress; - SBlock *m_first; - mutex_t m_mutex; + struct SBlock + { + unsigned int s; + SBlock *next; + SBlock *prev; + bool f; + } __attribute__((aligned(32))); + SBlock *m_baseAddress; + SBlock *m_endAddress; + SBlock *m_first; + mutex_t m_mutex; private: - CMEM2Alloc(const CMEM2Alloc &); + CMEM2Alloc(const CMEM2Alloc &); }; #endif // !defined(__MEM2ALLOC_HPP) diff --git a/source/menu.cpp b/source/menu.cpp index 5fcf2e12..74025b74 100644 --- a/source/menu.cpp +++ b/source/menu.cpp @@ -93,7 +93,7 @@ void ResumeGui() { * an element that is being changed. ***************************************************************************/ void HaltGui() { - if (guiHalt)return; + if (guiHalt)return; guiHalt = true; // wait for thread to finish @@ -110,7 +110,8 @@ static void * UpdateGUI (void *arg) { while (1) { if (guiHalt) { LWP_SuspendThread(guithread); - } else { + } + else { if (!ExitRequested) { mainWindow->Draw(); if (Settings.tooltips == TooltipsOn && THEME.show_tooltip != 0 && mainWindow->GetState() != STATE_DISABLED) @@ -134,8 +135,8 @@ static void * UpdateGUI (void *arg) { } else { for (int a = 5; a < 255; a += 10) { if (strcmp(headlessID,"")==0) - mainWindow->Draw(); - Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor) { 0, 0, 0, a},1); + mainWindow->Draw(); + Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor) {0, 0, 0, a},1); Menu_Render(); } mainWindow->RemoveAll(); @@ -195,52 +196,53 @@ void ExitGUIThreads() { /**************************************************************************** * LoadCoverImage ***************************************************************************/ -GuiImageData *LoadCoverImage(struct discHdr *header, bool Prefere3D, bool noCover) { - if (!header) return NULL; - GuiImageData *Cover = NULL; - char ID[4]; - char IDfull[7]; - char Path[100]; - bool flag = Prefere3D; +GuiImageData *LoadCoverImage(struct discHdr *header, bool Prefere3D, bool noCover) +{ + if(!header) return NULL; + GuiImageData *Cover = NULL; + char ID[4]; + char IDfull[7]; + char Path[100]; + bool flag = Prefere3D; - snprintf(ID, sizeof(ID), "%c%c%c", header->id[0], header->id[1], header->id[2]); - snprintf(IDfull, sizeof(IDfull), "%s%c%c%c", ID, header->id[3], header->id[4], header->id[5]); + snprintf(ID, sizeof(ID), "%c%c%c", header->id[0], header->id[1], header->id[2]); + snprintf(IDfull, sizeof(IDfull), "%s%c%c%c", ID, header->id[3], header->id[4], header->id[5]); - for (int i=0; i<2; ++i) { - char *coverPath = flag ? Settings.covers_path : Settings.covers2d_path; - flag = !flag; - //Load full id image - snprintf(Path, sizeof(Path), "%s%s.png", coverPath, IDfull); - delete Cover; - Cover = new(std::nothrow) GuiImageData(Path, NULL); - //Load short id image - if (!Cover || !Cover->GetImage()) { - snprintf(Path, sizeof(Path), "%s%s.png", coverPath, ID); - delete Cover; - Cover = new(std::nothrow) GuiImageData(Path, NULL); - } - if (Cover && Cover->GetImage()) - break; - } - //Load no image - if (noCover && (!Cover || !Cover->GetImage())) { - flag = Prefere3D; - for (int i=0; i<2; ++i) { - const char *nocoverPath = (flag ? "%snoimage.png" : "%snoimage2d.png"); - flag = !flag; - snprintf(Path, sizeof(Path), nocoverPath, CFG.theme_path); - delete Cover; - Cover = new(std::nothrow) GuiImageData(Path, (Prefere3D ? nocover_png : nocoverFlat_png)); - if (Cover && Cover->GetImage()) - break; - } - } - if (Cover && !Cover->GetImage()) { - delete Cover; - Cover = NULL; - } - return Cover; + for(int i=0; i<2; ++i) + { + char *coverPath = flag ? Settings.covers_path : Settings.covers2d_path; flag = !flag; + //Load full id image + snprintf(Path, sizeof(Path), "%s%s.png", coverPath, IDfull); + delete Cover; Cover = new(std::nothrow) GuiImageData(Path, NULL); + //Load short id image + if (!Cover || !Cover->GetImage()) + { + snprintf(Path, sizeof(Path), "%s%s.png", coverPath, ID); + delete Cover; Cover = new(std::nothrow) GuiImageData(Path, NULL); + } + if(Cover && Cover->GetImage()) + break; + } + //Load no image + if (noCover && (!Cover || !Cover->GetImage())) + { + flag = Prefere3D; + for(int i=0; i<2; ++i) + { + const char *nocoverPath = (flag ? "%snoimage.png" : "%snoimage2d.png"); flag = !flag; + snprintf(Path, sizeof(Path), nocoverPath, CFG.theme_path); + delete Cover; Cover = new(std::nothrow) GuiImageData(Path, (Prefere3D ? nocover_png : nocoverFlat_png)); + if (Cover && Cover->GetImage()) + break; + } + } + if(Cover && !Cover->GetImage()) + { + delete Cover; + Cover = NULL; + } + return Cover; } /**************************************************************************** @@ -251,8 +253,8 @@ int MainMenu(int menu) { currentMenu = menu; char imgPath[100]; - //if (strcmp(headlessID,"")!=0)HaltGui(); - //WindowPrompt("Can you see me now",0,"ok"); + //if (strcmp(headlessID,"")!=0)HaltGui(); + //WindowPrompt("Can you see me now",0,"ok"); snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", CFG.theme_path); pointer[0] = new GuiImageData(imgPath, player1_point_png); @@ -276,15 +278,15 @@ int MainMenu(int menu) { mainWindow->Append(bgImg); if (strcmp(headlessID,"")==0) - ResumeGui(); + ResumeGui(); - bgMusic = new GuiSound(bg_music_ogg, bg_music_ogg_size, Settings.volume); + bgMusic = new GuiSound(bg_music_ogg, bg_music_ogg_size, Settings.volume); bgMusic->SetLoop(1); //loop music // startup music if (strcmp("", Settings.oggload_path) && strcmp("notset", Settings.ogg_path)) { bgMusic->Load(Settings.ogg_path); } - bgMusic->Play(); + bgMusic->Play(); while (currentMenu != MENU_EXIT) { bgMusic->SetVolume(Settings.volume); @@ -319,16 +321,16 @@ int MainMenu(int menu) { } - // MemInfoPrompt(); - gprintf("\nExiting main GUI. mountMethod = %d",mountMethod); + // MemInfoPrompt(); + gprintf("\nExiting main GUI. mountMethod = %d",mountMethod); - CloseXMLDatabase(); + CloseXMLDatabase(); NewTitles::DestroyInstance(); - CFG_Cleanup(); + CFG_Cleanup(); if (strcmp(headlessID,"")!=0)//the GUIthread was never started, so it cant be ended and joined properly if headless mode was used. so we resume it and close it. - ResumeGui(); - ExitGUIThreads(); + ResumeGui(); + ExitGUIThreads(); bgMusic->Stop(); delete bgMusic; @@ -341,66 +343,76 @@ int MainMenu(int menu) { delete GameIDTxt; delete cover; delete coverImg; - delete fontClock; - delete fontSystem; - ShutdownAudio(); + delete fontClock; + delete fontSystem; + ShutdownAudio(); StopGX(); - gettextCleanUp(); + gettextCleanUp(); - if (dbvideo) { - InitVideodebug (); - printf("\n\n\n\n\n"); - } - if (mountMethod==3) { - struct discHdr *header = &gameList[gameSelected]; - char tmp[20]; - u32 tid; - sprintf(tmp,"%c%c%c%c",header->id[0],header->id[1],header->id[2],header->id[3]); - memcpy(&tid, tmp, 4); - gprintf("\nBooting title %016llx",TITLE_ID((header->id[5]=='1'?0x00010001:0x00010002),tid)); - WII_Initialize(); - WII_LaunchTitle(TITLE_ID((header->id[5]=='1'?0x00010001:0x00010002),tid)); - } - if (mountMethod==2) { - gprintf("\nLoading BC for GameCube"); - WII_Initialize(); - WII_LaunchTitle(0x0000000100000100ULL); + if(dbvideo) + { + InitVideodebug (); + printf("\n\n\n\n\n"); } + if (mountMethod==3) + { + struct discHdr *header = &gameList[gameSelected]; + char tmp[20]; + u32 tid; + sprintf(tmp,"%c%c%c%c",header->id[0],header->id[1],header->id[2],header->id[3]); + memcpy(&tid, tmp, 4); + gprintf("\nBooting title %016llx",TITLE_ID((header->id[5]=='1'?0x00010001:0x00010002),tid)); + WII_Initialize(); + WII_LaunchTitle(TITLE_ID((header->id[5]=='1'?0x00010001:0x00010002),tid)); + } + if (mountMethod==2) + { + gprintf("\nLoading BC for GameCube"); + WII_Initialize(); + WII_LaunchTitle(0x0000000100000100ULL); + } else if (boothomebrew == 1) { - gprintf("\nBootHomebrew"); + gprintf("\nBootHomebrew"); BootHomebrew(Settings.selected_homebrew); - } else if (boothomebrew == 2) { - gprintf("\nBootHomebrewFromMenu"); + } + else if (boothomebrew == 2) { + gprintf("\nBootHomebrewFromMenu"); BootHomebrewFromMem(); - } else { - gprintf("\n\tSettings.partition:%d",Settings.partition); - struct discHdr *header = NULL; - //if the GUI was "skipped" to boot a game from main(argv[1]) - if (strcmp(headlessID,"")!=0) { - gprintf("\n\tHeadless mode (%s)",headlessID); - __Menu_GetEntries(1); - if (!gameCnt) { - gprintf(" ERROR : !gameCnt"); - exit(0); - } - //gprintf("\n\tgameCnt:%d",gameCnt); - for (u32 i=0;iid[0],header->id[1],header->id[2],header->id[3],header->id[4],header->id[5]); - if (strcmp(tmp,headlessID)==0) { - gameSelected = i; - gprintf(" found (%d)",i); - break; - } - //if the game was not found - if (i==gameCnt-1) { - gprintf(" not found (%d IDs checked)",i); - exit(0); - } - } - } + } + else { + gprintf("\n\tSettings.partition:%d",Settings.partition); + struct discHdr *header = NULL; + //if the GUI was "skipped" to boot a game from main(argv[1]) + if (strcmp(headlessID,"")!=0) + { + gprintf("\n\tHeadless mode (%s)",headlessID); + __Menu_GetEntries(1); + if (!gameCnt) + { + gprintf(" ERROR : !gameCnt"); + exit(0); + } + //gprintf("\n\tgameCnt:%d",gameCnt); + for(u32 i=0;iid[0],header->id[1],header->id[2],header->id[3],header->id[4],header->id[5]); + if (strcmp(tmp,headlessID)==0) + { + gameSelected = i; + gprintf(" found (%d)",i); + break; + } + //if the game was not found + if (i==gameCnt-1) + { + gprintf(" not found (%d IDs checked)",i); + exit(0); + } + } + } int ret = 0; @@ -416,10 +428,10 @@ int MainMenu(int menu) { fix002 = game_cfg->errorfix002; iosChoice = game_cfg->ios; countrystrings = game_cfg->patchcountrystrings; - if (!altdoldefault) { - alternatedol = game_cfg->loadalternatedol; - alternatedoloffset = game_cfg->alternatedolstart; - } + if (!altdoldefault) { + alternatedol = game_cfg->loadalternatedol; + alternatedoloffset = game_cfg->alternatedolstart; + } reloadblock = game_cfg->iosreloadblock; } else { videoChoice = Settings.video; @@ -433,79 +445,81 @@ int MainMenu(int menu) { } fix002 = Settings.error002; countrystrings = Settings.patchcountrystrings; - if (!altdoldefault) { - alternatedol = off; - alternatedoloffset = 0; - } + if (!altdoldefault) { + alternatedol = off; + alternatedoloffset = 0; + } reloadblock = off; } - int ios2; + int ios2; - switch (iosChoice) { - case i249: - ios2 = 249; - break; + switch (iosChoice) { + case i249: + ios2 = 249; + break; - case i222: - ios2 = 222; - break; + case i222: + ios2 = 222; + break; - case i223: - ios2 = 223; - break; + case i223: + ios2 = 223; + break; - default: - ios2 = 249; - break; - } + default: + ios2 = 249; + break; + } - // When the selected ios is 249, and you're loading from FAT, reset ios to 222 - if (load_from_fs != PART_FS_WBFS && ios2 == 249) { - ios2 = 222; - } + // When the selected ios is 249, and you're loading from FAT, reset ios to 222 + if (load_from_fs != PART_FS_WBFS && ios2 == 249) { + ios2 = 222; + } bool onlinefix = ShutdownWC24(); - // You cannot reload ios when loading from fat + // You cannot reload ios when loading from fat if (IOS_GetVersion() != ios2 || onlinefix) { ret = Sys_ChangeIos(ios2); if (ret < 0) { Sys_ChangeIos(249); } } - if (!mountMethod) { - gprintf("\nLoading fragment list..."); - ret = get_frag_list(header->id); - gprintf("%d\n", ret); + if (!mountMethod) + { + gprintf("\nLoading fragment list..."); + ret = get_frag_list(header->id); + gprintf("%d\n", ret); - gprintf("\nSetting fragment list..."); - ret = set_frag_list(header->id); - gprintf("%d\n", ret); + gprintf("\nSetting fragment list..."); + ret = set_frag_list(header->id); + gprintf("%d\n", ret); - ret = Disc_SetUSB(header->id); - if (ret < 0) Sys_BackToLoader(); - gprintf("\n\tUSB set to game"); - } else { - gprintf("\n\tUSB not set, loading DVD"); - } + ret = Disc_SetUSB(header->id); + if (ret < 0) Sys_BackToLoader(); + gprintf("\n\tUSB set to game"); + } + else { + gprintf("\n\tUSB not set, loading DVD"); + } ret = Disc_Open(); if (ret < 0) Sys_BackToLoader(); - if (gameList) { - free(gameList); - } - if (dvdheader) - delete dvdheader; + if (gameList){ + free(gameList); + } + if(dvdheader) + delete dvdheader; - gprintf("\nLoading BCA data..."); - ret = do_bca_code(header->id); - gprintf("%d\n", ret); + gprintf("\nLoading BCA data..."); + ret = do_bca_code(header->id); + gprintf("%d\n", ret); - if (reloadblock == on && Sys_IsHermes()) { + if (reloadblock == on && Sys_IsHermes()) { patch_cios_data(); - if (load_from_fs == PART_FS_WBFS) { - mload_close(); - } + if (load_from_fs == PART_FS_WBFS) { + mload_close(); + } } u8 errorfixer002 = 0; @@ -632,14 +646,14 @@ int MainMenu(int menu) { vipatch = 0; break; } - gprintf("\n\tDisc_wiiBoot"); + gprintf("\n\tDisc_wiiBoot"); ret = Disc_WiiBoot(videoselected, cheat, vipatch, countrystrings, errorfixer002, alternatedol, alternatedoloffset); if (ret < 0) { Sys_LoadMenu(); } - printf("Returning entry point: 0x%0x\n", ret); + printf("Returning entry point: 0x%0x\n", ret); } - return 0; + return 0; } diff --git a/source/menu/menu_check.cpp b/source/menu/menu_check.cpp index 2d58c008..add798b7 100644 --- a/source/menu/menu_check.cpp +++ b/source/menu/menu_check.cpp @@ -15,7 +15,7 @@ extern char headlessID[8]; * MenuCheck ***************************************************************************/ int MenuCheck() { - gprintf("\nMenuCheck()"); + gprintf("\nMenuCheck()"); int menu = MENU_NONE; int i = 0; int choice; @@ -51,72 +51,73 @@ int MenuCheck() { } } - ret2 = -1; - memset(game_partition, 0, 6); - load_from_fs = -1; + ret2 = -1; + memset(game_partition, 0, 6); + load_from_fs = -1; - extern PartList partitions; - // Added for slow HDD - for (int runs = 0; runs < 10; runs++) { - if (Partition_GetList(WBFS_DEVICE_USB, &partitions) != 0) { - sleep(1); - continue; - } + extern PartList partitions; + // Added for slow HDD + for (int runs = 0; runs < 10; runs++) { + if (Partition_GetList(WBFS_DEVICE_USB, &partitions) != 0) { + sleep(1); + continue; + } + + if (Settings.partition != -1 && partitions.num > Settings.partition) { + PartInfo pinfo = partitions.pinfo[Settings.partition]; + if (WBFS_OpenPart(pinfo.part_fs, pinfo.index, partitions.pentry[Settings.partition].sector, partitions.pentry[Settings.partition].size, (char *) &game_partition) == 0) + { + ret2 = 0; + load_from_fs = pinfo.part_fs; + break; + } + } - if (Settings.partition != -1 && partitions.num > Settings.partition) { - PartInfo pinfo = partitions.pinfo[Settings.partition]; - if (WBFS_OpenPart(pinfo.part_fs, pinfo.index, partitions.pentry[Settings.partition].sector, partitions.pentry[Settings.partition].size, (char *) &game_partition) == 0) { - ret2 = 0; - load_from_fs = pinfo.part_fs; - break; - } - } + if (partitions.wbfs_n != 0) { + ret2 = WBFS_Open(); + for (int p = 0; p < partitions.num; p++) { + if (partitions.pinfo[p].fs_type == FS_TYPE_WBFS) { + Settings.partition = p; + load_from_fs = PART_FS_WBFS; + break; + } + } + } else if (Sys_IsHermes() && (partitions.fat_n != 0 || partitions.ntfs_n != 0)) { + // Loop through FAT/NTFS partitions, and find the first partition with games on it (if there is one) + u32 count; + + for (int i = 0; i < partitions.num; i++) { + if (partitions.pinfo[i].fs_type == FS_TYPE_FAT32 || partitions.pinfo[i].fs_type == FS_TYPE_NTFS) { - if (partitions.wbfs_n != 0) { - ret2 = WBFS_Open(); - for (int p = 0; p < partitions.num; p++) { - if (partitions.pinfo[p].fs_type == FS_TYPE_WBFS) { - Settings.partition = p; - load_from_fs = PART_FS_WBFS; - break; - } - } - } else if (Sys_IsHermes() && (partitions.fat_n != 0 || partitions.ntfs_n != 0)) { - // Loop through FAT/NTFS partitions, and find the first partition with games on it (if there is one) - u32 count; + if (!WBFS_OpenPart(partitions.pinfo[i].part_fs, partitions.pinfo[i].index, partitions.pentry[i].sector, partitions.pentry[i].size, (char *) &game_partition)) { + // Get the game count... + WBFS_GetCount(&count); - for (int i = 0; i < partitions.num; i++) { - if (partitions.pinfo[i].fs_type == FS_TYPE_FAT32 || partitions.pinfo[i].fs_type == FS_TYPE_NTFS) { - - if (!WBFS_OpenPart(partitions.pinfo[i].part_fs, partitions.pinfo[i].index, partitions.pentry[i].sector, partitions.pentry[i].size, (char *) &game_partition)) { - // Get the game count... - WBFS_GetCount(&count); - - if (count > 0) { - load_from_fs = partitions.pinfo[i].part_fs; - Settings.partition = i; - break; - } else { - WBFS_Close(); - } - } - } - } - } - - if ((ret2 >= 0 || load_from_fs != PART_FS_WBFS) && isInserted(bootDevice)) { - cfg_save_global(); - break; - } - sleep(1); - } + if (count > 0) { + load_from_fs = partitions.pinfo[i].part_fs; + Settings.partition = i; + break; + } else { + WBFS_Close(); + } + } + } + } + } + if ((ret2 >= 0 || load_from_fs != PART_FS_WBFS) && isInserted(bootDevice)) { + cfg_save_global(); + break; + } + sleep(1); + } + if (ret2 < 0 && load_from_fs != PART_FS_WBFS) { choice = WindowPrompt(tr("No WBFS or FAT/NTFS partition found"),tr("You need to select or format a partition"), tr("Select"), tr("Format"), tr("Return")); if (choice == 0) { Sys_LoadMenu(); } else { - load_from_fs = choice == 1 ? PART_FS_FAT : PART_FS_WBFS; + load_from_fs = choice == 1 ? PART_FS_FAT : PART_FS_WBFS; menu = MENU_FORMAT; } } @@ -135,9 +136,9 @@ int MenuCheck() { if (wbfsinit < 0) { sleep(1); } - - // open database if needed, load titles if needed - if (isInserted(bootDevice))OpenXMLDatabase(Settings.titlestxt_path,Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); + + // open database if needed, load titles if needed + if(isInserted(bootDevice))OpenXMLDatabase(Settings.titlestxt_path,Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // titles.txt loaded after database to override database titles with custom titles //snprintf(pathname, sizeof(pathname), "%stitles.txt", Settings.titlestxt_path); @@ -147,7 +148,7 @@ int MenuCheck() { //__Menu_GetEntries(0);//no point getting the gamelist here if (strcmp(headlessID,"")!=0) - menu = MENU_EXIT; + menu = MENU_EXIT; if (menu == MENU_NONE) menu = MENU_DISCLIST; diff --git a/source/menu/menu_disclist.cpp b/source/menu/menu_disclist.cpp index afa45517..b0e5d965 100644 --- a/source/menu/menu_disclist.cpp +++ b/source/menu/menu_disclist.cpp @@ -63,22 +63,22 @@ int MenuDiscList() { char IDfull[7]; u32 covert = 0; char imgPath[100]; - if (!dvdheader) - dvdheader = new struct discHdr; - u8 mountMethodOLD =0; + if (!dvdheader) + dvdheader = new struct discHdr; + u8 mountMethodOLD =0; - WDVD_GetCoverStatus(&covert); + WDVD_GetCoverStatus(&covert); u32 covertOld=covert; - f32 freespace, used, size = 0.0; - wchar_t searchChar; + f32 freespace, used, size = 0.0; + wchar_t searchChar; //SCREENSAVER int check = 0; //to skip the first cycle when wiimote isn't completely connected datagB=0; int menu = MENU_NONE, dataef=0; - + u32 nolist; char text[MAX_CHARACTERS + 4]; int choice = 0, selectedold = 100; @@ -89,18 +89,18 @@ int MenuDiscList() { char theTime[80]=""; time_t lastrawtime=0; - if (mountMethod != 3 && load_from_fs != PART_FS_FAT) { - WBFS_DiskSpace(&used, &freespace); - } + if (mountMethod != 3 && load_from_fs != PART_FS_FAT) { + WBFS_DiskSpace(&used, &freespace); + } if (!gameCnt) { //if there is no list of games to display nolist = 1; } - + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); snprintf(imgPath, sizeof(imgPath), "%sbutton_install.png", CFG.theme_path); GuiImageData btnInstall(imgPath, button_install_png); @@ -159,16 +159,16 @@ int MenuDiscList() { GuiImageData imgarrangeCarousel(imgPath, arrangeCarousel_png); snprintf(imgPath, sizeof(imgPath), "%sarrangeCarousel_gray.png", CFG.theme_path); GuiImageData imgarrangeCarousel_gray(imgPath, NULL); - - snprintf(imgPath, sizeof(imgPath), "%slock.png", CFG.theme_path); - GuiImageData imgLock(imgPath, lock_png); - snprintf(imgPath, sizeof(imgPath), "%slock_gray.png", CFG.theme_path); - GuiImageData imgLock_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%sunlock.png", CFG.theme_path); - GuiImageData imgUnlock(imgPath, unlock_png); - snprintf(imgPath, sizeof(imgPath), "%sunlock_gray.png", CFG.theme_path); - GuiImageData imgUnlock_gray(imgPath, NULL); - + + snprintf(imgPath, sizeof(imgPath), "%slock.png", CFG.theme_path); + GuiImageData imgLock(imgPath, lock_png); + snprintf(imgPath, sizeof(imgPath), "%slock_gray.png", CFG.theme_path); + GuiImageData imgLock_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sunlock.png", CFG.theme_path); + GuiImageData imgUnlock(imgPath, unlock_png); + snprintf(imgPath, sizeof(imgPath), "%sunlock_gray.png", CFG.theme_path); + GuiImageData imgUnlock_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sdvd.png", CFG.theme_path); GuiImageData imgdvd(imgPath, dvd_png); snprintf(imgPath, sizeof(imgPath), "%sdvd_gray.png", CFG.theme_path); @@ -196,30 +196,30 @@ int MenuDiscList() { screenShotBtn.SetTrigger(&trigZ); char spaceinfo[30]; - if (load_from_fs == PART_FS_FAT) { - memset(spaceinfo, 0, 30); - } else { - if (!strcmp(Settings.db_language,"JA")) { - // needs to be "total...used" for Japanese - sprintf(spaceinfo,(mountMethod!=3?"%.2fGB %s %.2fGB %s":" "),(freespace+used),tr("of"),freespace,tr("free")); - } else { - sprintf(spaceinfo,(mountMethod!=3?"%.2fGB %s %.2fGB %s":" "),freespace,tr("of"),(freespace+used),tr("free")); - } - } + if (load_from_fs == PART_FS_FAT) { + memset(spaceinfo, 0, 30); + } else { + if (!strcmp(Settings.db_language,"JA")) { + // needs to be "total...used" for Japanese + sprintf(spaceinfo,(mountMethod!=3?"%.2fGB %s %.2fGB %s":" "),(freespace+used),tr("of"),freespace,tr("free")); + } else { + sprintf(spaceinfo,(mountMethod!=3?"%.2fGB %s %.2fGB %s":" "),freespace,tr("of"),(freespace+used),tr("free")); + } + } GuiText usedSpaceTxt(spaceinfo, 18, THEME.info); usedSpaceTxt.SetAlignment(THEME.hddinfo_align, ALIGN_TOP); usedSpaceTxt.SetPosition(THEME.hddinfo_x, THEME.hddinfo_y); - char GamesCnt[15]; + char GamesCnt[15]; sprintf(GamesCnt,"%s: %i",(mountMethod!=3?tr("Games"):tr("Channels")), gameCnt); GuiText gamecntTxt(GamesCnt, 18, THEME.info); - GuiButton gamecntBtn(100,18); - gamecntBtn.SetAlignment(THEME.gamecount_align, ALIGN_TOP); + GuiButton gamecntBtn(100,18); + gamecntBtn.SetAlignment(THEME.gamecount_align, ALIGN_TOP); gamecntBtn.SetPosition(THEME.gamecount_x,THEME.gamecount_y); - gamecntBtn.SetLabel(&gamecntTxt); - gamecntBtn.SetEffectGrow(); - gamecntBtn.SetTrigger(&trigA); + gamecntBtn.SetLabel(&gamecntTxt); + gamecntBtn.SetEffectGrow(); + gamecntBtn.SetTrigger(&trigA); GuiTooltip installBtnTT(tr("Install a game")); if (Settings.wsprompt == yes) @@ -231,7 +231,7 @@ int MenuDiscList() { installBtnImgOver.SetWidescreen(CFG.widescreen); GuiButton installBtn(&installBtnImg, &installBtnImgOver, ALIGN_LEFT, ALIGN_TOP, THEME.install_x, THEME.install_y, &trigA, &btnSoundOver, btnClick2, 1, &installBtnTT,24,-30, 0,5); - + GuiTooltip settingsBtnTT(tr("Settings")); if (Settings.wsprompt == yes) @@ -292,10 +292,7 @@ int MenuDiscList() { favoriteBtnImg.SetWidescreen(CFG.widescreen); // GuiImage favoriteBtnImg_g(favoriteBtnImg);favoriteBtnImg_g.SetGrayscale(); GuiImage favoriteBtnImg_g(&imgfavIcon_gray); - if (favoriteBtnImg_g.GetImage() == NULL) { - favoriteBtnImg_g = favoriteBtnImg; - favoriteBtnImg_g.SetGrayscale(); - } + if(favoriteBtnImg_g.GetImage() == NULL) { favoriteBtnImg_g = favoriteBtnImg; favoriteBtnImg_g.SetGrayscale();} favoriteBtnImg_g.SetWidescreen(CFG.widescreen); GuiButton favoriteBtn(&favoriteBtnImg_g,&favoriteBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_favorite_x, THEME.gamelist_favorite_y, &trigA, &btnSoundOver, btnClick2,1, &favoriteBtnTT, -15, 52, 0, 3); favoriteBtn.SetAlpha(180); @@ -308,10 +305,7 @@ int MenuDiscList() { searchBtnImg.SetWidescreen(CFG.widescreen); // GuiImage searchBtnImg_g(searchBtnImg); searchBtnImg_g.SetGrayscale(); GuiImage searchBtnImg_g(&imgsearchIcon_gray); - if (searchBtnImg_g.GetImage() == NULL) { - searchBtnImg_g = searchBtnImg; - searchBtnImg_g.SetGrayscale(); - } + if(searchBtnImg_g.GetImage() == NULL) { searchBtnImg_g = searchBtnImg; searchBtnImg_g.SetGrayscale();} searchBtnImg_g.SetWidescreen(CFG.widescreen); GuiButton searchBtn(&searchBtnImg_g,&searchBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_search_x, THEME.gamelist_search_y, &trigA, &btnSoundOver, btnClick2,1, &searchBtnTT, -15, 52, 0, 3); searchBtn.SetAlpha(180); @@ -324,10 +318,7 @@ int MenuDiscList() { abcBtnImg.SetWidescreen(CFG.widescreen); // GuiImage abcBtnImg_g(abcBtnImg); abcBtnImg_g.SetGrayscale(); GuiImage abcBtnImg_g(Settings.fave ? &imgrankIcon_gray : &imgabcIcon_gray); - if (abcBtnImg_g.GetImage() == NULL) { - abcBtnImg_g = abcBtnImg; - abcBtnImg_g.SetGrayscale(); - } + if(abcBtnImg_g.GetImage() == NULL) { abcBtnImg_g = abcBtnImg; abcBtnImg_g.SetGrayscale();} abcBtnImg_g.SetWidescreen(CFG.widescreen); GuiButton abcBtn(&abcBtnImg_g,&abcBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_abc_x, THEME.gamelist_abc_y, &trigA, &btnSoundOver, btnClick2,1,&abcBtnTT, -15, 52, 0, 3); abcBtn.SetAlpha(180); @@ -340,10 +331,7 @@ int MenuDiscList() { countBtnImg.SetWidescreen(CFG.widescreen); // GuiImage countBtnImg_g(countBtnImg); countBtnImg_g.SetGrayscale(); GuiImage countBtnImg_g(&imgplayCountIcon_gray); - if (countBtnImg_g.GetImage() == NULL) { - countBtnImg_g = countBtnImg; - countBtnImg_g.SetGrayscale(); - } + if(countBtnImg_g.GetImage() == NULL) { countBtnImg_g = countBtnImg; countBtnImg_g.SetGrayscale();} countBtnImg_g.SetWidescreen(CFG.widescreen); GuiButton countBtn(&countBtnImg_g,&countBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_count_x, THEME.gamelist_count_y, &trigA, &btnSoundOver, btnClick2,1, &countBtnTT, -15, 52, 0, 3); countBtn.SetAlpha(180); @@ -356,10 +344,7 @@ int MenuDiscList() { listBtnImg.SetWidescreen(CFG.widescreen); // GuiImage listBtnImg_g(listBtnImg); listBtnImg_g.SetGrayscale(); GuiImage listBtnImg_g(&imgarrangeList_gray); - if (listBtnImg_g.GetImage() == NULL) { - listBtnImg_g = listBtnImg; - listBtnImg_g.SetGrayscale(); - } + if(listBtnImg_g.GetImage() == NULL) { listBtnImg_g = listBtnImg; listBtnImg_g.SetGrayscale();} listBtnImg_g.SetWidescreen(CFG.widescreen); GuiButton listBtn(&listBtnImg_g,&listBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_list_x, THEME.gamelist_list_y, &trigA, &btnSoundOver, btnClick2,1, &listBtnTT, 15, 52, 1, 3); listBtn.SetAlpha(180); @@ -372,82 +357,71 @@ int MenuDiscList() { gridBtnImg.SetWidescreen(CFG.widescreen); // GuiImage gridBtnImg_g(gridBtnImg); gridBtnImg_g.SetGrayscale(); GuiImage gridBtnImg_g(&imgarrangeGrid_gray); - if (gridBtnImg_g.GetImage() == NULL) { - gridBtnImg_g = gridBtnImg; - gridBtnImg_g.SetGrayscale(); - } + if(gridBtnImg_g.GetImage() == NULL) { gridBtnImg_g = gridBtnImg; gridBtnImg_g.SetGrayscale();} gridBtnImg_g.SetWidescreen(CFG.widescreen); GuiButton gridBtn(&gridBtnImg_g,&gridBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_grid_x, THEME.gamelist_grid_y, &trigA, &btnSoundOver, btnClick2,1, &gridBtnTT, 15, 52, 1, 3); gridBtn.SetAlpha(180); - GuiTooltip carouselBtnTT(tr("Display as a carousel")); - if (Settings.wsprompt == yes) - carouselBtnTT.SetWidescreen(CFG.widescreen); - carouselBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage carouselBtnImg(&imgarrangeCarousel); - carouselBtnImg.SetWidescreen(CFG.widescreen); + GuiTooltip carouselBtnTT(tr("Display as a carousel")); + if (Settings.wsprompt == yes) + carouselBtnTT.SetWidescreen(CFG.widescreen); + carouselBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage carouselBtnImg(&imgarrangeCarousel); + carouselBtnImg.SetWidescreen(CFG.widescreen); // GuiImage carouselBtnImg_g(carouselBtnImg); carouselBtnImg_g.SetGrayscale(); - GuiImage carouselBtnImg_g(&imgarrangeCarousel_gray); - if (carouselBtnImg_g.GetImage() == NULL) { - carouselBtnImg_g = carouselBtnImg; - carouselBtnImg_g.SetGrayscale(); - } - carouselBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton carouselBtn(&carouselBtnImg_g,&carouselBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_carousel_x, THEME.gamelist_carousel_y, &trigA, &btnSoundOver, btnClick2,1, &carouselBtnTT, 15, 52, 1, 3); - carouselBtn.SetAlpha(180); + GuiImage carouselBtnImg_g(&imgarrangeCarousel_gray); + if(carouselBtnImg_g.GetImage() == NULL) { carouselBtnImg_g = carouselBtnImg; carouselBtnImg_g.SetGrayscale();} + carouselBtnImg_g.SetWidescreen(CFG.widescreen); + GuiButton carouselBtn(&carouselBtnImg_g,&carouselBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_carousel_x, THEME.gamelist_carousel_y, &trigA, &btnSoundOver, btnClick2,1, &carouselBtnTT, 15, 52, 1, 3); + carouselBtn.SetAlpha(180); - bool canUnlock = (Settings.parentalcontrol == 0 && Settings.parental.enabled == 1); + bool canUnlock = (Settings.parentalcontrol == 0 && Settings.parental.enabled == 1); + + GuiTooltip lockBtnTT(canUnlock ? tr("Unlock Parental Control") : tr("Parental Control disabled")); + if (Settings.wsprompt == yes) + lockBtnTT.SetWidescreen(CFG.widescreen); + lockBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage lockBtnImg(&imgLock); + lockBtnImg.SetWidescreen(CFG.widescreen); + GuiImage lockBtnImg_g(&imgLock_gray); + if(lockBtnImg_g.GetImage() == NULL) { lockBtnImg_g = lockBtnImg; lockBtnImg_g.SetGrayscale(); } + lockBtnImg_g.SetWidescreen(CFG.widescreen); + GuiButton lockBtn(&lockBtnImg_g, &lockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2,1, &lockBtnTT, 15, 52, 1, 3); + lockBtn.SetAlpha(180); - GuiTooltip lockBtnTT(canUnlock ? tr("Unlock Parental Control") : tr("Parental Control disabled")); - if (Settings.wsprompt == yes) - lockBtnTT.SetWidescreen(CFG.widescreen); - lockBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage lockBtnImg(&imgLock); - lockBtnImg.SetWidescreen(CFG.widescreen); - GuiImage lockBtnImg_g(&imgLock_gray); - if (lockBtnImg_g.GetImage() == NULL) { - lockBtnImg_g = lockBtnImg; - lockBtnImg_g.SetGrayscale(); - } - lockBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton lockBtn(&lockBtnImg_g, &lockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2,1, &lockBtnTT, 15, 52, 1, 3); - lockBtn.SetAlpha(180); + GuiTooltip unlockBtnTT(tr("Enable Parental Control")); + if (Settings.wsprompt == yes) + unlockBtnTT.SetWidescreen(CFG.widescreen); + unlockBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage unlockBtnImg(&imgUnlock); + unlockBtnImg.SetWidescreen(CFG.widescreen); + GuiImage unlockBtnImg_g(&imgUnlock_gray); + if(unlockBtnImg_g.GetImage() == NULL) { unlockBtnImg_g = unlockBtnImg; unlockBtnImg_g.SetGrayscale(); } + unlockBtnImg_g.SetWidescreen(CFG.widescreen); - GuiTooltip unlockBtnTT(tr("Enable Parental Control")); - if (Settings.wsprompt == yes) - unlockBtnTT.SetWidescreen(CFG.widescreen); - unlockBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage unlockBtnImg(&imgUnlock); - unlockBtnImg.SetWidescreen(CFG.widescreen); - GuiImage unlockBtnImg_g(&imgUnlock_gray); - if (unlockBtnImg_g.GetImage() == NULL) { - unlockBtnImg_g = unlockBtnImg; - unlockBtnImg_g.SetGrayscale(); - } - unlockBtnImg_g.SetWidescreen(CFG.widescreen); - - if (canUnlock && Settings.godmode) { - lockBtn.SetImage(&unlockBtnImg_g); - lockBtn.SetImageOver(&unlockBtnImg_g); - lockBtn.SetToolTip(&unlockBtnTT, 15, 52, 1, 3); - } - - /* - GuiButton unlockBtn(&unlockBtnImg_g, &unlockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2,1, &lockBtnTT, 15, 52, 1, 3); - unlockBtn.SetAlpha(180); - */ + if (canUnlock && Settings.godmode) + { + lockBtn.SetImage(&unlockBtnImg_g); + lockBtn.SetImageOver(&unlockBtnImg_g); + lockBtn.SetToolTip(&unlockBtnTT, 15, 52, 1, 3); + } + +/* + GuiButton unlockBtn(&unlockBtnImg_g, &unlockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2,1, &lockBtnTT, 15, 52, 1, 3); + unlockBtn.SetAlpha(180); +*/ GuiTooltip dvdBtnTT(tr("Mount DVD drive")); - if (Settings.wsprompt == yes) - dvdBtnTT.SetWidescreen(CFG.widescreen); - dvdBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage dvdBtnImg(&imgdvd); - dvdBtnImg.SetWidescreen(CFG.widescreen); - GuiImage dvdBtnImg_g(dvdBtnImg); //dvdBtnImg_g.SetGrayscale(); + if (Settings.wsprompt == yes) + dvdBtnTT.SetWidescreen(CFG.widescreen); + dvdBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage dvdBtnImg(&imgdvd); + dvdBtnImg.SetWidescreen(CFG.widescreen); + GuiImage dvdBtnImg_g(dvdBtnImg); //dvdBtnImg_g.SetGrayscale(); // GuiImage carouselBtnImg_g(&imgarrangeCarousel_gray); - dvdBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton dvdBtn(&dvdBtnImg_g,&dvdBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_dvd_x, THEME.gamelist_dvd_y, &trigA, &btnSoundOver, btnClick2,1, &dvdBtnTT, 15, 52, 1, 3); - dvdBtn.SetAlpha(180); + dvdBtnImg_g.SetWidescreen(CFG.widescreen); + GuiButton dvdBtn(&dvdBtnImg_g,&dvdBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_dvd_x, THEME.gamelist_dvd_y, &trigA, &btnSoundOver, btnClick2,1, &dvdBtnTT, 15, 52, 1, 3); + dvdBtn.SetAlpha(180); GuiTooltip homebrewBtnTT(tr("Homebrew Launcher")); if (Settings.wsprompt == yes) @@ -464,16 +438,17 @@ int MenuDiscList() { favoriteBtn.SetImageOver(&favoriteBtnImg); favoriteBtn.SetAlpha(255); } - static bool show_searchwindow = false; - if (gameFilter && *gameFilter) { - if (show_searchwindow && gameCnt==1) - show_searchwindow = false; - if (!show_searchwindow) - searchBtn.SetEffect(EFFECT_PULSE, 10, 105); - searchBtn.SetImage(&searchBtnImg); + static bool show_searchwindow = false; + if(gameFilter && *gameFilter) + { + if(show_searchwindow && gameCnt==1) + show_searchwindow = false; + if(!show_searchwindow) + searchBtn.SetEffect(EFFECT_PULSE, 10, 105); + searchBtn.SetImage(&searchBtnImg); searchBtn.SetImageOver(&searchBtnImg); searchBtn.SetAlpha(255); - } + } if (Settings.sort==all) { abcBtn.SetImage(&abcBtnImg); abcBtn.SetImageOver(&abcBtnImg); @@ -496,38 +471,38 @@ int MenuDiscList() { carouselBtn.SetImageOver(&carouselBtnImg); carouselBtn.SetAlpha(255); } - + if (Settings.gameDisplay==list) { - favoriteBtn.SetPosition(THEME.gamelist_favorite_x, THEME.gamelist_favorite_y); - searchBtn.SetPosition(THEME.gamelist_search_x, THEME.gamelist_search_y); - abcBtn.SetPosition(THEME.gamelist_abc_x, THEME.gamelist_abc_y); - countBtn.SetPosition(THEME.gamelist_count_x, THEME.gamelist_count_y); - listBtn.SetPosition(THEME.gamelist_list_x, THEME.gamelist_list_y); - gridBtn.SetPosition(THEME.gamelist_grid_x, THEME.gamelist_grid_y); - carouselBtn.SetPosition(THEME.gamelist_carousel_x, THEME.gamelist_carousel_y); - lockBtn.SetPosition(THEME.gamelist_lock_x, THEME.gamelist_lock_y); - dvdBtn.SetPosition(THEME.gamelist_dvd_x, THEME.gamelist_dvd_y); - } else if (Settings.gameDisplay==grid) { - favoriteBtn.SetPosition(THEME.gamegrid_favorite_x, THEME.gamegrid_favorite_y); - searchBtn.SetPosition(THEME.gamegrid_search_x, THEME.gamegrid_search_y); - abcBtn.SetPosition(THEME.gamegrid_abc_x, THEME.gamegrid_abc_y); - countBtn.SetPosition(THEME.gamegrid_count_x, THEME.gamegrid_count_y); - listBtn.SetPosition(THEME.gamegrid_list_x, THEME.gamegrid_list_y); - gridBtn.SetPosition(THEME.gamegrid_grid_x, THEME.gamegrid_grid_y); - carouselBtn.SetPosition(THEME.gamegrid_carousel_x, THEME.gamegrid_carousel_y); - lockBtn.SetPosition(THEME.gamegrid_lock_x, THEME.gamegrid_lock_y); - dvdBtn.SetPosition(THEME.gamegrid_dvd_x, THEME.gamegrid_dvd_y); - } else if (Settings.gameDisplay==carousel) { - favoriteBtn.SetPosition(THEME.gamecarousel_favorite_x, THEME.gamecarousel_favorite_y); - searchBtn.SetPosition(THEME.gamecarousel_search_x, THEME.gamecarousel_favorite_y); - abcBtn.SetPosition(THEME.gamecarousel_abc_x, THEME.gamecarousel_abc_y); - countBtn.SetPosition(THEME.gamecarousel_count_x, THEME.gamecarousel_count_y); - listBtn.SetPosition(THEME.gamecarousel_list_x, THEME.gamecarousel_list_y); - gridBtn.SetPosition(THEME.gamecarousel_grid_x, THEME.gamecarousel_grid_y); - carouselBtn.SetPosition(THEME.gamecarousel_carousel_x, THEME.gamecarousel_carousel_y); - lockBtn.SetPosition(THEME.gamecarousel_lock_x, THEME.gamecarousel_lock_y); - dvdBtn.SetPosition(THEME.gamecarousel_dvd_x, THEME.gamecarousel_dvd_y); - } + favoriteBtn.SetPosition(THEME.gamelist_favorite_x, THEME.gamelist_favorite_y); + searchBtn.SetPosition(THEME.gamelist_search_x, THEME.gamelist_search_y); + abcBtn.SetPosition(THEME.gamelist_abc_x, THEME.gamelist_abc_y); + countBtn.SetPosition(THEME.gamelist_count_x, THEME.gamelist_count_y); + listBtn.SetPosition(THEME.gamelist_list_x, THEME.gamelist_list_y); + gridBtn.SetPosition(THEME.gamelist_grid_x, THEME.gamelist_grid_y); + carouselBtn.SetPosition(THEME.gamelist_carousel_x, THEME.gamelist_carousel_y); + lockBtn.SetPosition(THEME.gamelist_lock_x, THEME.gamelist_lock_y); + dvdBtn.SetPosition(THEME.gamelist_dvd_x, THEME.gamelist_dvd_y); + } else if(Settings.gameDisplay==grid) { + favoriteBtn.SetPosition(THEME.gamegrid_favorite_x, THEME.gamegrid_favorite_y); + searchBtn.SetPosition(THEME.gamegrid_search_x, THEME.gamegrid_search_y); + abcBtn.SetPosition(THEME.gamegrid_abc_x, THEME.gamegrid_abc_y); + countBtn.SetPosition(THEME.gamegrid_count_x, THEME.gamegrid_count_y); + listBtn.SetPosition(THEME.gamegrid_list_x, THEME.gamegrid_list_y); + gridBtn.SetPosition(THEME.gamegrid_grid_x, THEME.gamegrid_grid_y); + carouselBtn.SetPosition(THEME.gamegrid_carousel_x, THEME.gamegrid_carousel_y); + lockBtn.SetPosition(THEME.gamegrid_lock_x, THEME.gamegrid_lock_y); + dvdBtn.SetPosition(THEME.gamegrid_dvd_x, THEME.gamegrid_dvd_y); + } else if(Settings.gameDisplay==carousel) { + favoriteBtn.SetPosition(THEME.gamecarousel_favorite_x, THEME.gamecarousel_favorite_y); + searchBtn.SetPosition(THEME.gamecarousel_search_x, THEME.gamecarousel_favorite_y); + abcBtn.SetPosition(THEME.gamecarousel_abc_x, THEME.gamecarousel_abc_y); + countBtn.SetPosition(THEME.gamecarousel_count_x, THEME.gamecarousel_count_y); + listBtn.SetPosition(THEME.gamecarousel_list_x, THEME.gamecarousel_list_y); + gridBtn.SetPosition(THEME.gamecarousel_grid_x, THEME.gamecarousel_grid_y); + carouselBtn.SetPosition(THEME.gamecarousel_carousel_x, THEME.gamecarousel_carousel_y); + lockBtn.SetPosition(THEME.gamecarousel_lock_x, THEME.gamecarousel_lock_y); + dvdBtn.SetPosition(THEME.gamecarousel_dvd_x, THEME.gamecarousel_dvd_y); + } //Downloading Covers @@ -539,7 +514,7 @@ int MenuDiscList() { DownloadBtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP); DownloadBtn.SetPosition(THEME.covers_x,THEME.covers_y); - GuiTooltip IDBtnTT(tr("Click to change game ID")); + GuiTooltip IDBtnTT(tr("Click to change game ID")); if (Settings.wsprompt == yes) IDBtnTT.SetWidescreen(CFG.widescreen); IDBtnTT.SetAlpha(THEME.tooltipAlpha); @@ -553,14 +528,15 @@ int MenuDiscList() { DownloadBtn.SetTrigger(&trig1); DownloadBtn.SetToolTip(&DownloadBtnTT,205,-30); - idBtn.SetSoundOver(&btnSoundOver); - idBtn.SetTrigger(&trigA); - idBtn.SetToolTip(&IDBtnTT,205,-30); + idBtn.SetSoundOver(&btnSoundOver); + idBtn.SetTrigger(&trigA); + idBtn.SetToolTip(&IDBtnTT,205,-30); - } else { + } else + { DownloadBtn.SetRumble(false); - idBtn.SetRumble(false); - } + idBtn.SetRumble(false); + } GuiGameBrowser * gameBrowser = NULL; GuiGameGrid * gameGrid = NULL; @@ -601,9 +577,9 @@ int MenuDiscList() { w.Append(&sdcardBtn); w.Append(&poweroffBtn); w.Append(&gameInfo); - if (Settings.godmode) { - w.Append(&installBtn); - } + if (Settings.godmode) { + w.Append(&installBtn); + } w.Append(&homeBtn); w.Append(&settingsBtn); w.Append(&DownloadBtn); @@ -611,31 +587,31 @@ int MenuDiscList() { w.Append(&screenShotBtn); - // Begin Toolbar + // Begin Toolbar w.Append(&favoriteBtn); - Toolbar[0] = &favoriteBtn; + Toolbar[0] = &favoriteBtn; w.Append(&searchBtn); - Toolbar[1] = &searchBtn; + Toolbar[1] = &searchBtn; w.Append(&abcBtn); - Toolbar[2] = &abcBtn; + Toolbar[2] = &abcBtn; w.Append(&countBtn); - Toolbar[3] = &countBtn; + Toolbar[3] = &countBtn; w.Append(&listBtn); - Toolbar[4] = &listBtn; + Toolbar[4] = &listBtn; w.Append(&gridBtn); - Toolbar[5] = &gridBtn; + Toolbar[5] = &gridBtn; w.Append(&carouselBtn); - Toolbar[6] = &carouselBtn; - w.Append(&lockBtn); - Toolbar[7] = &lockBtn; - w.Append(&dvdBtn); - Toolbar[8] = &dvdBtn; - w.SetUpdateCallback(DiscListWinUpdateCallback); - // End Toolbar + Toolbar[6] = &carouselBtn; + w.Append(&lockBtn); + Toolbar[7] = &lockBtn; + w.Append(&dvdBtn); + Toolbar[8] = &dvdBtn; + w.SetUpdateCallback(DiscListWinUpdateCallback); + // End Toolbar - if (Settings.godmode == 1) + if (Settings.godmode == 1) w.Append(&homebrewBtn); if ((Settings.hddinfo == hr12)||(Settings.hddinfo == hr24)) { @@ -654,21 +630,21 @@ int MenuDiscList() { } mainWindow->Append(&w); - GuiSearchBar *searchBar=NULL; - if (show_searchwindow) { - searchBar = new GuiSearchBar(gameFilterNextList); - if (searchBar) - mainWindow->Append(searchBar); - } - - ResumeGui(); + GuiSearchBar *searchBar=NULL; + if(show_searchwindow) { + searchBar = new GuiSearchBar(gameFilterNextList); + if(searchBar) + mainWindow->Append(searchBar); + } + ResumeGui(); + // ShowMemInfo(); - while (menu == MENU_NONE) { + while (menu == MENU_NONE) { if (idiotFlag==1) { - gprintf("\n\tIdiot flag"); + gprintf("\n\tIdiot flag"); char idiotBuffer[200]; snprintf(idiotBuffer, sizeof(idiotBuffer), "%s (%s). %s",tr("You have attempted to load a bad image"), idiotChar,tr("Most likely it has dimensions that are not evenly divisible by 4.")); @@ -725,92 +701,7 @@ int MenuDiscList() { } - if ((datagB<1)&&(Settings.cios==1)&&(Settings.video == ntsc)&&(Settings.hddinfo == hr12)&&(Settings.qboot==1)&&(Settings.wsprompt==0)&&(Settings.language==ger)&&(Settings.tooltips==0)) { - dataed=1; - dataef=1; - } - if (dataef==1) { - if (cosa>7) { - cosa=1; - } - datag++; - if (sina==3) { - wiiBtn.SetAlignment(ALIGN_LEFT,ALIGN_BOTTOM); - wiiBtnImg.SetAngle(0); - if (datag>163) { - datag=1; - } else if (datag<62) { - wiiBtn.SetPosition(((cosa)*70),(-2*(datag)+120)); - } else if (62<=datag) { - wiiBtn.SetPosition(((cosa)*70),((datag*2)-130)); - } - if (datag>162) { - wiiBtn.SetPosition(700,700); - w.Remove(&wiiBtn); - datagB=2; - cosa++; - sina=lastrawtime%4; - } - w.Append(&wiiBtn); - } - if (sina==2) { - wiiBtn.SetAlignment(ALIGN_RIGHT,ALIGN_TOP); - wiiBtnImg.SetAngle(270); - if (datag>163) { - datag=1; - } else if (datag<62) { - wiiBtn.SetPosition(((-2*(datag)+130)),((cosa)*50)); - } else if (62<=datag) { - wiiBtn.SetPosition((2*(datag)-120),((cosa)*50)); - } - if (datag>162) { - wiiBtn.SetPosition(700,700); - w.Remove(&wiiBtn); - datagB=2; - cosa++; - sina=lastrawtime%4; - } - w.Append(&wiiBtn); - } - if (sina==1) { - wiiBtn.SetAlignment(ALIGN_TOP,ALIGN_LEFT); - wiiBtnImg.SetAngle(180); - if (datag>163) { - datag=1; - } else if (datag<62) { - wiiBtn.SetPosition(((cosa)*70),(2*(datag)-120)); - } else if (62<=datag) { - wiiBtn.SetPosition(((cosa)*70),(-2*(datag)+130)); - } - if (datag>162) { - wiiBtn.SetPosition(700,700); - w.Remove(&wiiBtn); - datagB=2; - cosa++; - sina=lastrawtime%4; - } - w.Append(&wiiBtn); - } - if (sina==0) { - wiiBtn.SetAlignment(ALIGN_TOP,ALIGN_LEFT); - wiiBtnImg.SetAngle(90); - if (datag>163) { - datag=1; - } else if (datag<62) { - wiiBtn.SetPosition(((2*(datag)-130)),((cosa)*50)); - } else if (62<=datag) { - wiiBtn.SetPosition((-2*(datag)+120),((cosa)*50)); - } - if (datag>162) { - wiiBtn.SetPosition(700,700); - w.Remove(&wiiBtn); - datagB=2; - cosa++; - sina=lastrawtime%4; - } - w.Append(&wiiBtn); - } - } + if ((datagB<1)&&(Settings.cios==1)&&(Settings.video == ntsc)&&(Settings.hddinfo == hr12)&&(Settings.qboot==1)&&(Settings.wsprompt==0)&&(Settings.language==ger)&&(Settings.tooltips==0)){dataed=1;dataef=1;}if (dataef==1){if (cosa>7){cosa=1;}datag++;if (sina==3){wiiBtn.SetAlignment(ALIGN_LEFT,ALIGN_BOTTOM);wiiBtnImg.SetAngle(0);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((cosa)*70),(-2*(datag)+120));}else if(62<=datag){wiiBtn.SetPosition(((cosa)*70),((datag*2)-130));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}if (sina==2){wiiBtn.SetAlignment(ALIGN_RIGHT,ALIGN_TOP);wiiBtnImg.SetAngle(270);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((-2*(datag)+130)),((cosa)*50));}else if(62<=datag){wiiBtn.SetPosition((2*(datag)-120),((cosa)*50));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}if (sina==1){wiiBtn.SetAlignment(ALIGN_TOP,ALIGN_LEFT);wiiBtnImg.SetAngle(180);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((cosa)*70),(2*(datag)-120));}else if(62<=datag){wiiBtn.SetPosition(((cosa)*70),(-2*(datag)+130));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}if (sina==0){wiiBtn.SetAlignment(ALIGN_TOP,ALIGN_LEFT);wiiBtnImg.SetAngle(90);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((2*(datag)-130)),((cosa)*50));}else if(62<=datag){wiiBtn.SetPosition((-2*(datag)+120),((cosa)*50));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}} // respond to button presses if (shutdown == 1) { gprintf("\n\tshutdown"); @@ -853,29 +744,30 @@ int MenuDiscList() { } } - } else if (gamecntBtn.GetState() == STATE_CLICKED && mountMethod!=3) { - gprintf("\n\tgameCntBtn clicked"); - gamecntBtn.ResetState(); - char linebuf[150]; - snprintf(linebuf, sizeof(linebuf), "%s %sGameList ?",tr("Save Game List to"), Settings.update_path); - choice = WindowPrompt(0,linebuf,"TXT","CSV",tr("Back")); - if (choice) { - if (save_gamelist(choice-1)) - WindowPrompt(0,tr("Saved"),tr("OK")); - else - WindowPrompt(tr("Error"),tr("Could not save."),tr("OK")); - } - menu = MENU_DISCLIST; - break; + } else if (gamecntBtn.GetState() == STATE_CLICKED && mountMethod!=3) { + gprintf("\n\tgameCntBtn clicked"); + gamecntBtn.ResetState(); + char linebuf[150]; + snprintf(linebuf, sizeof(linebuf), "%s %sGameList ?",tr("Save Game List to"), Settings.update_path); + choice = WindowPrompt(0,linebuf,"TXT","CSV",tr("Back")); + if (choice) { + if (save_gamelist(choice-1)) + WindowPrompt(0,tr("Saved"),tr("OK")); + else + WindowPrompt(tr("Error"),tr("Could not save."),tr("OK")); + } + menu = MENU_DISCLIST; + break; - } else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); + } + else if (screenShotBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tscreenShotBtn clicked"); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf("...It's easy, mmmmmmKay"); - } else if (homeBtn.GetState() == STATE_CLICKED) { + }else if (homeBtn.GetState() == STATE_CLICKED) { gprintf("\n\thomeBtn clicked"); bgMusic->Pause(); choice = WindowExitPrompt(); @@ -897,8 +789,8 @@ int MenuDiscList() { } } else if (wiiBtn.GetState() == STATE_CLICKED) { - gprintf("\n\twiiBtn clicked"); - + gprintf("\n\twiiBtn clicked"); + dataed++; wiiBtn.ResetState(); if (Settings.gameDisplay==list) { @@ -924,15 +816,17 @@ int MenuDiscList() { gameCarousel->SetFocus(1); } } - } else if ((covert & 0x2)&&(covert!=covertOld)) { + }else if ((covert & 0x2)&&(covert!=covertOld)) { gprintf("\n\tNew Disc Detected"); choice = WindowPrompt(tr("New Disc Detected"),0,tr("Install"),tr("Mount DVD drive"),tr("Cancel")); if (choice == 1) { - menu = MENU_INSTALL; - break; - } else if (choice ==2) { - dvdBtn.SetState(STATE_CLICKED); - } else { + menu = MENU_INSTALL; + break; + } + else if (choice ==2) + { + dvdBtn.SetState(STATE_CLICKED); + }else { if (Settings.gameDisplay==list) { gameBrowser->SetFocus(1); } else if (Settings.gameDisplay==grid) { @@ -958,9 +852,9 @@ int MenuDiscList() { offset = gameCarousel->GetOffset(); } if (isInserted(bootDevice)) { - HaltGui(); // to fix endless rumble when clicking on the SD icon when rumble is disabled because rumble is set to on in Global_Default() - CFG_Load(); - ResumeGui(); + HaltGui(); // to fix endless rumble when clicking on the SD icon when rumble is disabled because rumble is set to on in Global_Default() + CFG_Load(); + ResumeGui(); } sdcardBtn.ResetState(); menu = MENU_DISCLIST; @@ -973,7 +867,7 @@ int MenuDiscList() { choice = WindowPrompt(tr("Cover Download"), 0, tr("Normal Covers"), tr("3D Covers"), tr("Disc Images"), tr("Back")); // ask for download choice if (choice != 0) { int choice2 = choice; - bool missing; + bool missing; missing = SearchMissingImages(choice2); if (IsNetworkInit() == false && missing == true) { WindowPrompt(tr("Network init error"), 0, tr("OK")); @@ -1042,70 +936,84 @@ int MenuDiscList() { gprintf("\n\tsearchBtn Clicked"); show_searchwindow=!show_searchwindow; - HaltGui(); - if (searchBar) { - mainWindow->Remove(searchBar); - delete searchBar; - searchBar = NULL; - } - if (show_searchwindow) { - if (gameFilter && *gameFilter) { - searchBtn.StopEffect(); - searchBtn.SetEffectGrow(); - } - searchBar = new GuiSearchBar(gameFilterNextList); - if (searchBar) - mainWindow->Append(searchBar); - } else { - if (gameFilter && *gameFilter) - searchBtn.SetEffect(EFFECT_PULSE, 10, 105); - } - searchBtn.ResetState(); - ResumeGui(); + HaltGui(); + if(searchBar) + { + mainWindow->Remove(searchBar); + delete searchBar; + searchBar = NULL; + } + if(show_searchwindow) + { + if(gameFilter && *gameFilter) + { + searchBtn.StopEffect(); + searchBtn.SetEffectGrow(); + } + searchBar = new GuiSearchBar(gameFilterNextList); + if(searchBar) + mainWindow->Append(searchBar); + } + else + { + if(gameFilter && *gameFilter) + searchBtn.SetEffect(EFFECT_PULSE, 10, 105); + } + searchBtn.ResetState(); + ResumeGui(); } else if (searchBar && (searchChar=searchBar->GetClicked())) { - if (searchChar > 27) { - int len = gameFilter ? wcslen(gameFilter) : 0; - wchar_t newFilter[len+2]; - if (gameFilter) - wcscpy(newFilter, gameFilter); - newFilter[len] = searchChar; - newFilter[len+1] = 0; + if(searchChar > 27) + { + int len = gameFilter ? wcslen(gameFilter) : 0; + wchar_t newFilter[len+2]; + if(gameFilter) + wcscpy(newFilter, gameFilter); + newFilter[len] = searchChar; + newFilter[len+1] = 0; - __Menu_GetEntries(0, newFilter); - menu = MENU_DISCLIST; - break; - } else if (searchChar == 7) { // Close - show_searchwindow=false; - HaltGui(); - if (searchBar) { - mainWindow->Remove(searchBar); - delete searchBar; - searchBar = NULL; - } - if (gameFilter && *gameFilter) { - searchBtn.SetEffect(EFFECT_PULSE, 10, 105); - searchBtn.SetImage(&searchBtnImg); - searchBtn.SetImageOver(&searchBtnImg); - searchBtn.SetAlpha(255); - } else { - searchBtn.StopEffect(); - searchBtn.SetEffectGrow(); - searchBtn.SetImage(&searchBtnImg_g); - searchBtn.SetImageOver(&searchBtnImg_g); - searchBtn.SetAlpha(180); - } + __Menu_GetEntries(0, newFilter); + menu = MENU_DISCLIST; + break; + } + else if(searchChar == 7) // Close + { + show_searchwindow=false; + HaltGui(); + if(searchBar) + { + mainWindow->Remove(searchBar); + delete searchBar; + searchBar = NULL; + } + if(gameFilter && *gameFilter) + { + searchBtn.SetEffect(EFFECT_PULSE, 10, 105); + searchBtn.SetImage(&searchBtnImg); + searchBtn.SetImageOver(&searchBtnImg); + searchBtn.SetAlpha(255); + } + else + { + searchBtn.StopEffect(); + searchBtn.SetEffectGrow(); + searchBtn.SetImage(&searchBtnImg_g); + searchBtn.SetImageOver(&searchBtnImg_g); + searchBtn.SetAlpha(180); + } - ResumeGui(); - } else if (searchChar == 8) { // Backspace - __Menu_GetEntries(0, gameFilterPrev); - menu = MENU_DISCLIST; - break; - } + ResumeGui(); + } + else if(searchChar == 8) // Backspace + { + __Menu_GetEntries(0, gameFilterPrev); + menu = MENU_DISCLIST; + break; + } - } + } else if (abcBtn.GetState() == STATE_CLICKED) { gprintf("\n\tabcBtn clicked"); @@ -1184,14 +1092,16 @@ int MenuDiscList() { } else { carouselBtn.ResetState(); } - } else if (homebrewBtn.GetState() == STATE_CLICKED) { + } + else if (homebrewBtn.GetState() == STATE_CLICKED) { gprintf("\n\thomebrewBtn Clicked"); menu = MENU_HOMEBREWBROWSE; break; - } else if (gameInfo.GetState() == STATE_CLICKED && mountMethod!=3) { - gprintf("\n\tgameinfo Clicked"); + } + else if (gameInfo.GetState() == STATE_CLICKED && mountMethod!=3) { + gprintf("\n\tgameinfo Clicked"); gameInfo.ResetState(); - if (selectImg1>=0 && selectImg1<(s32)gameCnt) { + if(selectImg1>=0 && selectImg1<(s32)gameCnt) { gameSelected = selectImg1; rockout(); struct discHdr *header = &gameList[selectImg1]; @@ -1200,59 +1110,61 @@ int MenuDiscList() { rockout(2); if (choice==2) homeBtn.SetState(STATE_CLICKED); - if (choice==3) { - menu = MENU_DISCLIST; - break; - } - } - } else if (lockBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tlockBtn clicked"); - lockBtn.ResetState(); - if (!canUnlock) { - WindowPrompt(tr("Parental Control"), tr("You don't have Parental Control enabled. If you wish to use Parental Control, enable it in the Wii Settings."), tr("OK")); - } else { - if (Settings.godmode) { - if (WindowPrompt(tr("Parental Control"), tr("Are you sure you want to enable Parent Control?"), tr("Yes"), tr("No")) == 1) { - Settings.godmode = 0; - lockBtn.SetImage(&lockBtnImg_g); - lockBtn.SetImageOver(&lockBtnImg_g); - lockBtn.SetToolTip(&lockBtnTT, 15, 52, 1, 3); - - // Retrieve the gamelist again - menu = MENU_DISCLIST; - break; - } - } else { - // Require the user to enter the PIN code - char pin[5]; - memset(&pin, 0, 5); - int ret = OnScreenNumpad((char *) &pin, 5); - - if (ret == 1) { - if (memcmp(pin, Settings.parental.pin, 4) == 0) { - Settings.godmode = 1; - lockBtn.SetImage(&unlockBtnImg_g); - lockBtn.SetImageOver(&unlockBtnImg_g); - lockBtn.SetToolTip(&unlockBtnTT, 15, 52, 1, 3); - - // Retrieve the gamelist again - menu = MENU_DISCLIST; - break; - } else { - WindowPrompt(tr("Parental Control"), tr("Invalid PIN code"), tr("OK")); - } - } - } - } - } else if (dvdBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tdvdBtn Clicked"); + if (choice==3) { + menu = MENU_DISCLIST; + break; + } + } + } + else if (lockBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tlockBtn clicked"); + lockBtn.ResetState(); + if (!canUnlock) { + WindowPrompt(tr("Parental Control"), tr("You don't have Parental Control enabled. If you wish to use Parental Control, enable it in the Wii Settings."), tr("OK")); + } else { + if (Settings.godmode) { + if (WindowPrompt(tr("Parental Control"), tr("Are you sure you want to enable Parent Control?"), tr("Yes"), tr("No")) == 1) { + Settings.godmode = 0; + lockBtn.SetImage(&lockBtnImg_g); + lockBtn.SetImageOver(&lockBtnImg_g); + lockBtn.SetToolTip(&lockBtnTT, 15, 52, 1, 3); + + // Retrieve the gamelist again + menu = MENU_DISCLIST; + break; + } + } else { + // Require the user to enter the PIN code + char pin[5]; + memset(&pin, 0, 5); + int ret = OnScreenNumpad((char *) &pin, 5); + + if (ret == 1) { + if (memcmp(pin, Settings.parental.pin, 4) == 0) { + Settings.godmode = 1; + lockBtn.SetImage(&unlockBtnImg_g); + lockBtn.SetImageOver(&unlockBtnImg_g); + lockBtn.SetToolTip(&unlockBtnTT, 15, 52, 1, 3); + + // Retrieve the gamelist again + menu = MENU_DISCLIST; + break; + } else { + WindowPrompt(tr("Parental Control"), tr("Invalid PIN code"), tr("OK")); + } + } + } + } + } + else if (dvdBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tdvdBtn Clicked"); mountMethodOLD = (mountMethod==3?mountMethod:0); - mountMethod=DiscMount(dvdheader); - dvdBtn.ResetState(); + mountMethod=DiscMount(dvdheader); + dvdBtn.ResetState(); - rockout(); - //break; + rockout(); + //break; } if (Settings.gameDisplay==grid) { int selectimg; @@ -1273,7 +1185,7 @@ int MenuDiscList() { //Get selected game under cursor int selectimg; DownloadBtn.SetSize(160,224); - idBtn.SetSize(100,40); + idBtn.SetSize(100,40); selectimg = gameBrowser->GetSelectedOption(); gameSelected = gameBrowser->GetClickedOption(); @@ -1282,7 +1194,7 @@ int MenuDiscList() { if (gameSelected > 0) //if click occured selectimg = gameSelected; - char gameregion[7]; + char gameregion[7]; if ((selectimg >= 0) && (selectimg < (s32) gameCnt)) { if (selectimg != selectedold) { selectedold = selectimg;//update displayed cover, game ID, and region if the selected game changes @@ -1307,12 +1219,12 @@ int MenuDiscList() { sprintf(gameregion,"NTSC U"); break; case 'J': - sprintf(gameregion,"NTSC J"); + sprintf(gameregion,"NTSC J"); break; case 'W': sprintf(gameregion,"NTSC T"); break; - default: + default: case 'K': sprintf(gameregion,"NTSC K"); break; @@ -1353,10 +1265,10 @@ int MenuDiscList() { GameIDTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); //GameIDTxt->SetPosition(THEME.id_x,THEME.id_y); idBtn.SetEffect(EFFECT_FADE, 20); - idBtn.SetLabel(GameIDTxt); + idBtn.SetLabel(GameIDTxt); w.Append(&idBtn); } - //don't try to show region for channels because all the custom channels wont follow the rules + //don't try to show region for channels because all the custom channels wont follow the rules if (((Settings.sinfo == GameRegion) || (Settings.sinfo == Both))&&mountMethod!=3) { GameRegionTxt = new GuiText(gameregion, 22, THEME.info); GameRegionTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); @@ -1367,55 +1279,57 @@ int MenuDiscList() { } } - if (idBtn.GetState() == STATE_CLICKED && mountMethod!=3) { - gprintf("\n\tidBtn Clicked"); - struct discHdr * header = &gameList[gameBrowser->GetSelectedOption()]; - //enter new game ID - char entered[10]; - snprintf(entered, sizeof(entered), "%s", IDfull); - //entered[9] = '\0'; - int result = OnScreenKeyboard(entered, 7,0); - if (result == 1) { - WBFS_ReIDGame(header->id, entered); - //__Menu_GetEntries(); - menu = MENU_DISCLIST; - } + if (idBtn.GetState() == STATE_CLICKED && mountMethod!=3) { + gprintf("\n\tidBtn Clicked"); + struct discHdr * header = &gameList[gameBrowser->GetSelectedOption()]; + //enter new game ID + char entered[10]; + snprintf(entered, sizeof(entered), "%s", IDfull); + //entered[9] = '\0'; + int result = OnScreenKeyboard(entered, 7,0); + if (result == 1) { + WBFS_ReIDGame(header->id, entered); + //__Menu_GetEntries(); + menu = MENU_DISCLIST; + } - idBtn.ResetState(); - } - startat=gameBrowser->GetOffset(), offset=startat; + idBtn.ResetState(); + } + startat=gameBrowser->GetOffset(), offset=startat; } if (((gameSelected >= 0) && (gameSelected < (s32)gameCnt)) - || mountMethod==1 - || mountMethod==2) { - if (searchBar) { - HaltGui(); - mainWindow->Remove(searchBar); - ResumeGui(); - } - rockout(); - struct discHdr *header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); - // struct discHdr *header = dvdheader:&gameList[gameSelected]); - if (!mountMethod) { //only get this stuff it we are booting a game from USB - WBFS_GameSize(header->id, &size); - if (strlen(get_title(header)) < (MAX_CHARACTERS + 3)) { - sprintf(text, "%s", get_title(header)); - } else { - strncpy(text, get_title(header), MAX_CHARACTERS); - text[MAX_CHARACTERS] = '\0'; - strncat(text, "...", 3); - } - } + || mountMethod==1 + || mountMethod==2) { + if(searchBar) + { + HaltGui(); + mainWindow->Remove(searchBar); + ResumeGui(); + } + rockout(); + struct discHdr *header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); + // struct discHdr *header = dvdheader:&gameList[gameSelected]); + if (!mountMethod)//only get this stuff it we are booting a game from USB + { + WBFS_GameSize(header->id, &size); + if (strlen(get_title(header)) < (MAX_CHARACTERS + 3)) { + sprintf(text, "%s", get_title(header)); + } else { + strncpy(text, get_title(header), MAX_CHARACTERS); + text[MAX_CHARACTERS] = '\0'; + strncat(text, "...", 3); + } + } //check if alt Dol and gct file is present FILE *exeFile = NULL; char nipple[100]; - header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); //reset header + header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); //reset header snprintf (IDfull,sizeof(IDfull),"%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); - if (game_cfg) { + if (game_cfg) { alternatedol = game_cfg->loadalternatedol; ocarinaChoice = game_cfg->ocarina; } else { @@ -1437,7 +1351,7 @@ int MenuDiscList() { break; } else { fclose(exeFile); - } + } } if (ocarinaChoice != off) { /* Open gct File and check exist */ @@ -1445,7 +1359,7 @@ int MenuDiscList() { exeFile = fopen (nipple ,"rb"); if (exeFile==NULL) { gprintf("\n\ttried to load missing gct."); - sprintf(nipple, "%s %s",nipple,tr("does not exist! Loading game without cheats.")); + sprintf(nipple, "%s %s",nipple,tr("does not exist! Loading game without cheats.")); WindowPrompt(tr("Error"),nipple,NULL,NULL,NULL,NULL,170); } else { fseek (exeFile, 0, SEEK_END); @@ -1454,7 +1368,7 @@ int MenuDiscList() { fclose(exeFile); if (size>MAX_GCT_SIZE) { gprintf("\n\tgct is too big"); - sprintf(nipple, "%s %s",nipple,tr("contains over 255 lines of code. It will produce unexpected results.")); + sprintf(nipple, "%s %s",nipple,tr("contains over 255 lines of code. It will produce unexpected results.")); WindowPrompt(tr("Error"),nipple,NULL,NULL,NULL,NULL,170); } } @@ -1476,8 +1390,8 @@ int MenuDiscList() { playcount += 1; CFG_save_game_num(header->id); - gprintf("\n\tplaycount for %c%c%c%c%c%c raised to %i",header->id[0],header->id[1],header->id[2],header->id[3],header->id[4],header->id[5],playcount); - + gprintf("\n\tplaycount for %c%c%c%c%c%c raised to %i",header->id[0],header->id[1],header->id[2],header->id[3],header->id[4],header->id[5],playcount); + } menu = MENU_EXIT; break; @@ -1487,7 +1401,7 @@ int MenuDiscList() { while (returnHere) { returnHere = false; if (Settings.wiilight != wiilight_forInstall) wiilight(1); - choice = GameWindowPrompt(); + choice = GameWindowPrompt(); // header = &gameList[gameSelected]; //reset header if (choice == 1) { @@ -1497,14 +1411,14 @@ int MenuDiscList() { exeFile = fopen (nipple ,"rb"); if (exeFile==NULL) { gprintf("\n\tTried to load alt dol that isn't there"); - sprintf(nipple, "%s %s",nipple,tr("does not exist! You Messed something up, Idiot.")); + sprintf(nipple, "%s %s",nipple,tr("does not exist! You Messed something up, Idiot.")); WindowPrompt(tr("Error"),nipple,tr("OK")); menu = MENU_CHECK; wiilight(0); break; } else { - fclose(exeFile); - } + fclose(exeFile); + } } if (ocarinaChoice != off) { /* Open gct File and check exist */ @@ -1512,7 +1426,7 @@ int MenuDiscList() { exeFile = fopen (nipple ,"rb"); if (exeFile==NULL) { gprintf("\n\ttried to load gct file that isn't there"); - sprintf(nipple, "%s %s",nipple,tr("does not exist! Loading game without cheats.")); + sprintf(nipple, "%s %s",nipple,tr("does not exist! Loading game without cheats.")); WindowPrompt(tr("Error"),nipple,NULL,NULL,NULL,NULL,170); } else { fseek (exeFile, 0, SEEK_END); @@ -1521,7 +1435,7 @@ int MenuDiscList() { fclose(exeFile); if (size>MAX_GCT_SIZE) { gprintf("\n\tgct file is too big"); - sprintf(nipple, "%s %s",nipple,tr("contains over 255 lines of code. It will produce unexpected results.")); + sprintf(nipple, "%s %s",nipple,tr("contains over 255 lines of code. It will produce unexpected results.")); WindowPrompt(tr("Error"),nipple,NULL,NULL,NULL,NULL,170); } } @@ -1532,7 +1446,7 @@ int MenuDiscList() { menu = MENU_EXIT; } else if (choice == 2) { - wiilight(0); + wiilight(0); HaltGui(); if (Settings.gameDisplay==list) mainWindow->Remove(gameBrowser); else if (Settings.gameDisplay==grid) mainWindow->Remove(gameGrid); @@ -1543,9 +1457,9 @@ int MenuDiscList() { //re-evaluate header now in case they changed games while on the game prompt header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); int settret = GameSettings(header); - /* unneeded for now, kept in case database gets a separate language setting + /* unneeded for now, kept in case database gets a separate language setting //menu = MENU_DISCLIST; // refresh titles (needed if the language setting has changed) - */ + */ HaltGui(); if (Settings.gameDisplay==list) mainWindow->Append(gameBrowser); else if (Settings.gameDisplay==grid) mainWindow->Append(gameGrid); @@ -1562,7 +1476,7 @@ int MenuDiscList() { else if (choice == 3 && !mountMethod) { //WBFS renaming wiilight(0); - //re-evaluate header now in case they changed games while on the game prompt + //re-evaluate header now in case they changed games while on the game prompt header = &gameList[gameSelected]; //enter new game title @@ -1577,7 +1491,7 @@ int MenuDiscList() { } } else if (choice == 0) { rockout(2); - if (mountMethod==1||mountMethod==2)mountMethod = mountMethodOLD; + if (mountMethod==1||mountMethod==2)mountMethod = mountMethodOLD; if (Settings.gameDisplay==list) { gameBrowser->SetFocus(1); } else if (Settings.gameDisplay==grid) { @@ -1589,11 +1503,12 @@ int MenuDiscList() { } - if (searchBar) { - HaltGui(); - mainWindow->Append(searchBar); - ResumeGui(); - } + if(searchBar) + { + HaltGui(); + mainWindow->Append(searchBar); + ResumeGui(); + } } // to skip the first call of windowScreensaver at startup when wiimote is not connected if (IsWpadConnected()) { @@ -1612,62 +1527,65 @@ int MenuDiscList() { covertOld=covert; } - // set alt dol default - if (menu == MENU_EXIT && altdoldefault) { - struct discHdr *header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); - struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); - // use default only if no alt dol was selected manually - if (game_cfg) { - if (game_cfg->alternatedolstart != 0) - altdoldefault = false; - } - if (altdoldefault) { - int autodol = autoSelectDol((char*)header->id, true); - if (autodol>0) { - alternatedol = 2; - alternatedoloffset = autodol; - char temp[20]; - sprintf(temp,"%d",autodol); - } else { - // alt dol menu for games that require more than a single alt dol - int autodol = autoSelectDolMenu((char*)header->id, true); - if (autodol>0) { - alternatedol = 2; - alternatedoloffset = autodol; - } - } - } - } + // set alt dol default + if (menu == MENU_EXIT && altdoldefault) { + struct discHdr *header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); + struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); + // use default only if no alt dol was selected manually + if (game_cfg) { + if (game_cfg->alternatedolstart != 0) + altdoldefault = false; + } + if (altdoldefault) { + int autodol = autoSelectDol((char*)header->id, true); + if (autodol>0) { + alternatedol = 2; + alternatedoloffset = autodol; + char temp[20]; + sprintf(temp,"%d",autodol); + } else { + // alt dol menu for games that require more than a single alt dol + int autodol = autoSelectDolMenu((char*)header->id, true); + if (autodol>0) { + alternatedol = 2; + alternatedoloffset = autodol; + } + } + } + } //no need to close sd here. we still need to get settings and codes and shit - /*if (menu == MENU_EXIT) { - SDCard_deInit(); - }*/ - //if (Settings.gameDisplay==list) {startat=gameBrowser->GetOffset(), offset=startat;}//save the variables in case we are refreshing the list - //gprintf("\n\tstartat:%d offset:%d",startat,offset); - HaltGui(); - mainWindow->RemoveAll(); - mainWindow->Append(bgImg); - delete searchBar; - searchBar = NULL; - delete gameBrowser; - gameBrowser = NULL; - delete gameGrid; - gameGrid = NULL; - delete gameCarousel; - gameCarousel = NULL; - ResumeGui(); + /*if (menu == MENU_EXIT) { + SDCard_deInit(); + }*/ + //if (Settings.gameDisplay==list) {startat=gameBrowser->GetOffset(), offset=startat;}//save the variables in case we are refreshing the list + //gprintf("\n\tstartat:%d offset:%d",startat,offset); + HaltGui(); + mainWindow->RemoveAll(); + mainWindow->Append(bgImg); + delete searchBar; + searchBar = NULL; + delete gameBrowser; + gameBrowser = NULL; + delete gameGrid; + gameGrid = NULL; + delete gameCarousel; + gameCarousel = NULL; + ResumeGui(); return menu; } -void DiscListWinUpdateCallback(void * e) { - GuiWindow *w = (GuiWindow *)e; - for (int i=0; i<8; ++i) { - if (Toolbar[i]->GetState() == STATE_SELECTED) { - w->Remove(Toolbar[i]); - w->Append(Toolbar[i]); // draw the selected Icon allways on top - break; - } - } +void DiscListWinUpdateCallback(void * e) +{ + GuiWindow *w = (GuiWindow *)e; + for(int i=0; i<8; ++i) + { + if(Toolbar[i]->GetState() == STATE_SELECTED) + { + w->Remove(Toolbar[i]); + w->Append(Toolbar[i]); // draw the selected Icon allways on top + break; + } + } } void rockout(int f) { diff --git a/source/menu/menu_format.cpp b/source/menu/menu_format.cpp index 0f19a36a..ff97fd76 100644 --- a/source/menu/menu_format.cpp +++ b/source/menu/menu_format.cpp @@ -24,7 +24,7 @@ int MenuFormat() { char imgPath[100]; customOptionList options(MAX_PARTITIONS_EX); - extern PartList partitions; + extern PartList partitions; u32 cnt, counter = 0; int choice, ret; @@ -44,13 +44,13 @@ int MenuFormat() { options.SetName(counter, "%s %d:",tr("Partition"), cnt+1); options.SetValue(counter,tr("Can't be formatted")); } - counter++; + counter++; } GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff.png", CFG.theme_path); GuiImageData btnpwroff(imgPath, wiimote_poweroff_png); snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff_over.png", CFG.theme_path); @@ -61,8 +61,8 @@ int MenuFormat() { GuiImageData btnhomeOver(imgPath, menu_button_over_png); GuiImageData battery(battery_png); GuiImageData batteryBar(battery_bar_png); - GuiImageData batteryRed(battery_red_png); - GuiImageData batteryBarRed(battery_bar_red_png); + GuiImageData batteryRed(battery_red_png); + GuiImageData batteryBarRed(battery_bar_red_png); GuiTrigger trigA; @@ -102,40 +102,40 @@ int MenuFormat() { ret = optionBrowser.GetClickedOption(); - if (ret >= 0) { - if (Settings.godmode == 1) { + if(ret >= 0) { + if(Settings.godmode == 1) { partitionEntry *entry = &partitions.pentry[ret]; if (entry->size) { - if (load_from_fs == PART_FS_FAT) { - WBFS_OpenPart(partitions.pinfo[ret].part_fs, partitions.pinfo[ret].index, entry->sector, - entry->size, (char *) &game_partition); - load_from_fs = partitions.pinfo[ret].part_fs; - menu = MENU_DISCLIST; - - Settings.partition = ret; - if (isInserted(bootDevice))cfg_save_global(); - } else { - sprintf(text, "%s %d : %.2fGB",tr("Partition"), ret+1, entry->size * (partitions.sector_size / GB_SIZE)); - choice = WindowPrompt( tr("Do you want to format:"), text,tr("Yes"),tr("No")); - if (choice == 1) { - ret = FormatingPartition(tr("Formatting, please wait..."), entry); - if (ret < 0) { - WindowPrompt(tr("Error !"),tr("Failed formating"),tr("Return")); - menu = MENU_SETTINGS; - } else { - sleep(1); - ret = WBFS_Open(); - sprintf(text, "%s %s", text,tr("formatted!")); - WindowPrompt(tr("Success:"),text,tr("OK")); - if (ret < 0) { - WindowPrompt(tr("ERROR"), tr("Failed to open partition"), tr("OK")); - Sys_LoadMenu(); - } - menu = MENU_DISCLIST; - } - } - } - } else if (Settings.godmode == 0) { + if (load_from_fs == PART_FS_FAT) { + WBFS_OpenPart(partitions.pinfo[ret].part_fs, partitions.pinfo[ret].index, entry->sector, + entry->size, (char *) &game_partition); + load_from_fs = partitions.pinfo[ret].part_fs; + menu = MENU_DISCLIST; + + Settings.partition = ret; + if(isInserted(bootDevice))cfg_save_global(); + } else { + sprintf(text, "%s %d : %.2fGB",tr("Partition"), ret+1, entry->size * (partitions.sector_size / GB_SIZE)); + choice = WindowPrompt( tr("Do you want to format:"), text,tr("Yes"),tr("No")); + if (choice == 1) { + ret = FormatingPartition(tr("Formatting, please wait..."), entry); + if (ret < 0) { + WindowPrompt(tr("Error !"),tr("Failed formating"),tr("Return")); + menu = MENU_SETTINGS; + } else { + sleep(1); + ret = WBFS_Open(); + sprintf(text, "%s %s", text,tr("formatted!")); + WindowPrompt(tr("Success:"),text,tr("OK")); + if(ret < 0) { + WindowPrompt(tr("ERROR"), tr("Failed to open partition"), tr("OK")); + Sys_LoadMenu(); + } + menu = MENU_DISCLIST; + } + } + } + } else if(Settings.godmode == 0) { mainWindow->Remove(&optionBrowser); char entered[20] = ""; int result = OnScreenKeyboard(entered, 20,0); diff --git a/source/menu/menu_install.cpp b/source/menu/menu_install.cpp index aac53e79..a9b8fe21 100644 --- a/source/menu/menu_install.cpp +++ b/source/menu/menu_install.cpp @@ -13,7 +13,7 @@ float gamesize; ***************************************************************************/ int MenuInstall() { - gprintf("\nMenuInstall()"); + gprintf("\nMenuInstall()"); int menu = MENU_NONE; static struct discHdr headerdisc ATTRIBUTE_ALIGN(32); @@ -29,9 +29,9 @@ int MenuInstall() { snprintf(imgPath, sizeof(imgPath), "%sbattery.png", CFG.theme_path); GuiImageData battery(imgPath, battery_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_bar.png", CFG.theme_path); + snprintf(imgPath, sizeof(imgPath), "%sbattery_bar.png", CFG.theme_path); GuiImageData batteryBar(imgPath, battery_bar_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", CFG.theme_path); + snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", CFG.theme_path); GuiImageData batteryRed(imgPath, battery_red_png); snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_red.png", CFG.theme_path); GuiImageData batteryBarRed(imgPath, battery_bar_red_png); @@ -116,16 +116,16 @@ int MenuInstall() { break; } else { __Menu_GetEntries(); //get the entries again - GuiSound * instsuccess = NULL; - bgMusic->Pause(); - instsuccess = new GuiSound(success_ogg, success_ogg_size, Settings.sfxvolume); - instsuccess->SetVolume(Settings.sfxvolume); - instsuccess->SetLoop(0); - instsuccess->Play(); + GuiSound * instsuccess = NULL; + bgMusic->Pause(); + instsuccess = new GuiSound(success_ogg, success_ogg_size, Settings.sfxvolume); + instsuccess->SetVolume(Settings.sfxvolume); + instsuccess->SetLoop(0); + instsuccess->Play(); WindowPrompt (tr("Successfully installed:"),name,tr("OK")); - instsuccess->Stop(); - delete instsuccess; - bgMusic->Resume(); + instsuccess->Stop(); + delete instsuccess; + bgMusic->Resume(); menu = MENU_DISCLIST; break; } diff --git a/source/mload/dip_plugin.c b/source/mload/dip_plugin.c index 06e41915..b154cf50 100644 --- a/source/mload/dip_plugin.c +++ b/source/mload/dip_plugin.c @@ -1,122 +1,122 @@ #define size_dip_plugin 3224 unsigned char dip_plugin[3224] __attribute__((aligned (32)))={ - 19, 119, 228, 85, 18, 52, 0, 1, 32, 34, 205, 172, 32, 32, 13, 57, 32, 32, 8, 197, 32, 32, 8, 153, 32, 32, 91, 129, 32, - 32, 0, 73, 32, 32, 40, 117, 32, 32, 54, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 119, 233, - 160, 19, 119, 233, 117, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 71, 120, 234, 0, 2, 23, 70, 192, - 71, 120, 234, 0, 2, 39, 70, 192, 71, 120, 234, 0, 2, 55, 70, 192, 71, 120, 234, 0, 2, 47, 70, 192, 71, 120, 234, 0, - 2, 21, 70, 192, 71, 120, 234, 0, 2, 7, 70, 192, 71, 120, 234, 0, 2, 45, 70, 192, 71, 120, 234, 0, 2, 41, 70, 192, 71, - 120, 234, 0, 2, 49, 181, 0, 75, 7, 176, 137, 147, 0, 70, 104, 35, 0, 33, 0, 34, 0, 147, 1, 147, 2, 240, 0, 252, 157, - 176, 9, 188, 2, 71, 8, 70, 192, 227, 0, 0, 0, 181, 16, 28, 3, 34, 32, 28, 12, 72, 13, 28, 25, 247, 255, 255, 210, 33, - 32, 72, 11, 247, 255, 255, 202, 73, 10, 34, 1, 104, 11, 66, 19, 209, 253, 34, 32, 28, 32, 73, 6, 247, 255, 255, 196, - 28, 32, 33, 32, 247, 255, 255, 188, 75, 4, 104, 24, 188, 16, 188, 2, 71, 8, 70, 192, 13, 0, 96, 0, 13, 0, 96, 28, 13, - 0, 96, 32, 181, 240, 70, 95, 70, 86, 70, 77, 70, 68, 180, 240, 10, 203, 70, 154, 75, 20, 176, 137, 37, 0, 28, 7, 28, - 14, 70, 145, 70, 108, 70, 155, 70, 168, 70, 91, 96, 35, 70, 67, 96, 99, 96, 163, 70, 83, 96, 227, 28, 56, 70, 75, 28, - 49, 97, 35, 247, 255, 255, 162, 70, 104, 28, 57, 28, 50, 240, 0, 252, 78, 53, 1, 40, 0, 209, 8, 176, 9, 188, 60, 70, - 144, 70, 153, 70, 162, 70, 171, 188, 240, 188, 2, 71, 8, 45, 15, 217, 223, 231, 243, 208, 0, 0, 0, 181, 112, 176, 136, - 75, 8, 28, 6, 28, 13, 70, 108, 147, 0, 96, 97, 146, 2, 247, 255, 255, 129, 28, 49, 28, 42, 70, 104, 240, 0, 252, 45, - 176, 8, 188, 112, 188, 2, 71, 8, 168, 0, 0, 0, 181, 240, 70, 95, 70, 86, 70, 77, 70, 68, 180, 240, 176, 143, 144, 4, - 145, 3, 146, 2, 41, 0, 209, 0, 224, 126, 10, 82, 70, 145, 35, 128, 34, 0, 1, 27, 70, 147, 34, 255, 147, 1, 3, 210, 171, - 6, 146, 0, 70, 152, 224, 7, 154, 3, 68, 179, 69, 90, 217, 62, 154, 5, 24, 179, 10, 219, 68, 153, 154, 3, 70, 91, 26, - 214, 70, 74, 2, 83, 154, 2, 66, 154, 216, 87, 35, 0, 147, 5, 36, 0, 159, 4, 34, 128, 68, 95, 28, 56, 28, 49, 1, 18, - 240, 0, 248, 103, 44, 0, 209, 47, 40, 0, 208, 45, 155, 0, 28, 6, 66, 152, 217, 1, 38, 255, 3, 246, 10, 242, 70, 146, - 36, 0, 75, 43, 70, 66, 96, 19, 35, 0, 96, 83, 96, 147, 70, 83, 96, 211, 70, 75, 97, 19, 28, 56, 28, 49, 247, 255, 255, - 38, 70, 64, 28, 57, 28, 50, 240, 0, 251, 210, 52, 1, 28, 5, 40, 0, 208, 192, 44, 15, 217, 230, 45, 0, 208, 188, 176, - 15, 28, 40, 188, 60, 70, 144, 70, 153, 70, 162, 70, 171, 188, 240, 188, 2, 71, 8, 154, 5, 25, 147, 154, 1, 66, 147, - 217, 1, 155, 5, 26, 214, 32, 128, 1, 0, 33, 32, 247, 255, 254, 251, 28, 4, 40, 0, 208, 18, 33, 128, 1, 9, 70, 74, 247, - 255, 255, 59, 28, 5, 40, 0, 208, 15, 28, 32, 247, 255, 254, 217, 231, 216, 26, 211, 0, 155, 28, 28, 147, 5, 30, 99, - 65, 156, 231, 163, 37, 1, 66, 109, 231, 208, 37, 0, 231, 206, 154, 5, 28, 56, 24, 161, 28, 50, 247, 255, 254, 214, 28, - 56, 28, 49, 247, 255, 254, 206, 231, 228, 70, 192, 208, 0, 0, 0, 181, 48, 28, 13, 28, 20, 6, 195, 209, 18, 75, 15, 66, - 152, 217, 19, 33, 0, 75, 14, 24, 194, 75, 14, 66, 154, 216, 1, 75, 13, 26, 25, 66, 161, 211, 5, 28, 8, 66, 169, 216, - 10, 30, 99, 67, 152, 224, 0, 32, 0, 188, 48, 188, 2, 71, 8, 35, 192, 4, 91, 26, 25, 231, 232, 28, 40, 30, 99, 67, 152, - 231, 244, 1, 127, 255, 255, 240, 0, 0, 0, 3, 97, 127, 255, 19, 97, 128, 0, 71, 112, 70, 192, 181, 48, 28, 4, 72, 15, - 28, 13, 104, 131, 104, 193, 176, 129, 24, 91, 24, 154, 105, 3, 43, 0, 209, 15, 104, 67, 43, 0, 209, 7, 28, 32, 28, 41, - 247, 255, 255, 13, 176, 1, 188, 48, 188, 2, 71, 8, 28, 32, 28, 41, 247, 255, 255, 27, 231, 246, 28, 32, 28, 41, 240, - 0, 249, 246, 231, 241, 70, 192, 19, 119, 240, 0, 181, 240, 79, 27, 35, 1, 28, 4, 96, 59, 176, 129, 33, 32, 247, 255, - 254, 127, 104, 227, 43, 8, 208, 8, 28, 32, 240, 0, 250, 246, 35, 0, 96, 59, 176, 1, 188, 240, 188, 2, 71, 8, 105, 163, - 37, 197, 104, 24, 104, 89, 247, 255, 254, 109, 105, 163, 1, 173, 104, 27, 28, 40, 33, 8, 104, 92, 104, 30, 247, 255, - 254, 100, 75, 10, 4, 36, 64, 30, 67, 52, 78, 9, 96, 44, 28, 40, 33, 4, 96, 52, 247, 255, 254, 73, 28, 48, 33, 4, 247, - 255, 254, 69, 35, 0, 96, 59, 32, 0, 231, 217, 70, 192, 19, 119, 240, 40, 0, 0, 255, 255, 0, 0, 49, 136, 181, 16, 73, - 20, 28, 4, 104, 139, 104, 202, 24, 154, 105, 11, 43, 0, 209, 18, 104, 75, 43, 0, 209, 11, 33, 32, 247, 255, 254, 175, - 40, 0, 219, 3, 105, 162, 75, 12, 66, 154, 208, 10, 188, 16, 188, 2, 71, 8, 33, 32, 247, 255, 254, 185, 231, 242, 33, - 32, 240, 0, 249, 149, 231, 238, 75, 6, 34, 1, 112, 26, 120, 91, 43, 0, 209, 238, 247, 255, 254, 10, 231, 235, 70, 192, - 19, 119, 240, 0, 93, 28, 158, 163, 32, 34, 205, 172, 181, 240, 70, 87, 70, 70, 180, 192, 28, 6, 120, 0, 176, 129, 28, - 15, 70, 144, 40, 224, 208, 24, 77, 145, 35, 0, 98, 43, 28, 3, 59, 112, 43, 143, 217, 13, 28, 48, 28, 57, 70, 66, 240, - 0, 250, 180, 28, 4, 176, 1, 28, 32, 188, 12, 70, 144, 70, 154, 188, 240, 188, 2, 71, 8, 74, 135, 0, 155, 88, 211, 70, - 159, 77, 132, 106, 43, 43, 0, 209, 2, 105, 43, 43, 0, 208, 230, 28, 56, 33, 0, 70, 66, 240, 0, 249, 10, 106, 43, 96, - 59, 28, 56, 70, 65, 247, 255, 253, 212, 36, 0, 231, 223, 104, 107, 43, 0, 209, 2, 105, 43, 43, 0, 208, 211, 36, 0, 231, - 215, 104, 107, 43, 0, 209, 2, 105, 43, 43, 0, 208, 203, 28, 56, 33, 0, 70, 66, 240, 0, 248, 239, 28, 56, 70, 65, 247, - 255, 253, 187, 36, 0, 231, 198, 104, 115, 36, 0, 96, 171, 231, 194, 104, 171, 231, 217, 104, 115, 36, 0, 96, 43, 231, - 188, 104, 43, 231, 211, 104, 115, 97, 43, 43, 0, 208, 6, 28, 40, 28, 49, 48, 24, 49, 8, 34, 6, 247, 255, 253, 166, 105, - 115, 36, 0, 97, 107, 231, 171, 105, 43, 231, 194, 104, 114, 35, 36, 84, 234, 36, 0, 231, 164, 104, 235, 104, 172, 70, - 154, 105, 43, 43, 0, 209, 0, 224, 170, 32, 0, 34, 0, 70, 83, 67, 35, 209, 2, 42, 0, 209, 0, 224, 142, 28, 3, 30, 90, - 65, 147, 96, 107, 28, 56, 70, 65, 247, 255, 255, 70, 28, 4, 231, 139, 35, 1, 34, 37, 84, 171, 104, 43, 43, 0, 209, 0, - 224, 132, 104, 113, 104, 178, 28, 56, 247, 255, 254, 214, 28, 4, 34, 0, 35, 37, 84, 234, 44, 0, 208, 0, 231, 120, 28, - 56, 70, 65, 247, 255, 254, 201, 231, 115, 104, 115, 72, 70, 64, 24, 247, 255, 253, 139, 28, 4, 231, 108, 76, 68, 33, - 64, 28, 32, 247, 255, 253, 106, 34, 0, 28, 33, 224, 3, 50, 1, 42, 64, 209, 0, 231, 90, 92, 163, 43, 0, 208, 248, 34, - 64, 28, 56, 247, 255, 253, 80, 28, 56, 33, 64, 247, 255, 253, 72, 36, 0, 231, 83, 35, 36, 92, 234, 42, 0, 208, 0, 231, - 116, 84, 234, 35, 37, 84, 234, 105, 43, 96, 42, 96, 106, 96, 170, 96, 234, 98, 42, 70, 154, 43, 0, 209, 0, 231, 59, - 105, 108, 247, 255, 253, 73, 70, 80, 28, 41, 28, 34, 56, 1, 49, 24, 240, 0, 248, 206, 28, 4, 231, 53, 104, 113, 104, - 178, 40, 208, 208, 59, 28, 56, 247, 255, 254, 133, 28, 4, 40, 0, 208, 0, 231, 42, 35, 37, 92, 235, 43, 0, 208, 0, 231, - 37, 231, 171, 105, 43, 43, 0, 209, 0, 231, 26, 35, 2, 231, 55, 104, 107, 43, 0, 209, 3, 105, 43, 43, 0, 209, 0, 231, - 17, 104, 115, 104, 178, 7, 155, 67, 19, 74, 24, 36, 0, 64, 19, 96, 235, 231, 14, 104, 107, 43, 0, 208, 17, 75, 21, 36, - 160, 98, 43, 2, 36, 231, 6, 105, 43, 43, 0, 208, 0, 231, 108, 96, 106, 36, 0, 230, 255, 28, 48, 70, 66, 240, 0, 249, - 175, 28, 4, 231, 122, 105, 43, 43, 0, 209, 234, 230, 239, 2, 201, 2, 82, 231, 192, 70, 66, 28, 48, 240, 0, 249, 162, - 28, 2, 30, 83, 65, 154, 231, 78, 70, 192, 19, 119, 240, 0, 19, 119, 234, 32, 127, 255, 255, 255, 19, 119, 233, 160, - 255, 255, 128, 0, 0, 5, 49, 0, 181, 240, 70, 87, 70, 78, 70, 69, 180, 224, 70, 128, 28, 14, 70, 148, 42, 0, 208, 51, - 33, 3, 28, 2, 64, 10, 35, 4, 26, 155, 28, 24, 64, 8, 69, 96, 216, 49, 40, 0, 208, 49, 36, 0, 70, 67, 85, 30, 52, 1, - 66, 160, 216, 250, 69, 132, 208, 32, 70, 99, 26, 27, 8, 159, 70, 153, 0, 187, 70, 154, 43, 0, 208, 17, 4, 51, 6, 50, - 2, 49, 67, 26, 67, 10, 28, 21, 70, 67, 67, 53, 24, 26, 33, 0, 0, 139, 49, 1, 80, 213, 66, 185, 211, 250, 68, 84, 69, - 209, 208, 6, 70, 67, 25, 24, 52, 1, 112, 6, 48, 1, 69, 164, 216, 250, 188, 28, 70, 144, 70, 153, 70, 162, 188, 240, - 188, 1, 71, 0, 70, 96, 231, 203, 36, 0, 231, 211, 70, 192, 181, 112, 76, 17, 28, 6, 104, 32, 176, 130, 28, 13, 98, 2, - 97, 6, 100, 1, 97, 65, 33, 68, 247, 255, 252, 121, 28, 48, 28, 41, 247, 255, 252, 117, 75, 10, 34, 2, 104, 24, 104, - 35, 73, 9, 147, 0, 35, 1, 247, 255, 252, 128, 28, 41, 28, 4, 28, 48, 247, 255, 252, 119, 176, 2, 28, 32, 188, 112, 188, - 2, 71, 8, 19, 119, 240, 44, 19, 119, 240, 48, 87, 70, 83, 2, 181, 240, 176, 133, 28, 4, 28, 15, 146, 3, 40, 2, 216, - 75, 77, 47, 104, 43, 43, 0, 208, 74, 78, 46, 104, 48, 40, 0, 219, 1, 247, 255, 252, 71, 74, 44, 0, 163, 88, 152, 33, - 1, 247, 255, 252, 81, 96, 48, 40, 0, 219, 66, 104, 48, 40, 0, 219, 49, 104, 40, 28, 57, 34, 6, 48, 32, 247, 255, 252, - 61, 104, 40, 169, 3, 34, 4, 48, 64, 247, 255, 252, 55, 104, 42, 36, 4, 28, 19, 51, 32, 96, 19, 104, 42, 35, 6, 96, 83, - 104, 42, 33, 68, 28, 19, 51, 64, 96, 147, 104, 43, 96, 220, 104, 40, 247, 255, 252, 33, 104, 43, 104, 48, 34, 2, 147, - 0, 73, 22, 35, 0, 247, 255, 252, 45, 104, 42, 28, 19, 51, 32, 96, 19, 104, 43, 96, 92, 104, 42, 28, 19, 51, 64, 96, - 147, 104, 43, 96, 220, 176, 5, 188, 240, 188, 2, 71, 8, 32, 1, 66, 64, 231, 248, 75, 11, 78, 8, 96, 43, 35, 1, 66, 91, - 96, 51, 231, 179, 44, 0, 209, 186, 72, 8, 33, 1, 247, 255, 252, 5, 96, 48, 231, 180, 70, 192, 19, 119, 240, 44, 19, - 119, 240, 48, 19, 119, 236, 140, 87, 70, 83, 1, 19, 119, 240, 64, 19, 119, 236, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 233, 45, 64, 128, 229, 159, 113, 80, 229, 151, 112, 0, 235, 0, 0, 45, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, - 64, 128, 229, 159, 113, 60, 229, 151, 112, 0, 235, 0, 0, 39, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, - 229, 159, 113, 40, 229, 151, 112, 0, 235, 0, 0, 33, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, 229, 159, - 113, 20, 229, 151, 112, 0, 235, 0, 0, 27, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, 229, 159, 113, 0, 229, - 151, 112, 0, 235, 0, 0, 21, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, 229, 159, 112, 236, 229, 151, 112, - 0, 235, 0, 0, 15, 232, 189, 64, 128, 225, 47, 255, 30, 230, 0, 8, 16, 225, 47, 255, 30, 230, 0, 7, 240, 225, 47, 255, - 30, 230, 0, 3, 144, 225, 47, 255, 30, 230, 0, 3, 176, 225, 47, 255, 30, 230, 0, 3, 208, 225, 47, 255, 30, 230, 0, 3, - 240, 225, 47, 255, 30, 230, 0, 4, 80, 225, 47, 255, 30, 225, 47, 255, 23, 239, 0, 0, 204, 225, 47, 255, 30, 180, 124, - 181, 0, 247, 255, 252, 254, 188, 2, 188, 124, 71, 8, 181, 112, 176, 136, 104, 133, 28, 1, 75, 34, 71, 24, 70, 192, 70, - 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 70, 114, 28, 1, 32, 4, 223, 171, 71, 16, 181, 240, 70, 95, 70, 86, 70, 77, 70, 68, 180, 240, - 75, 8, 104, 27, 71, 24, 19, 119, 224, 16, 19, 119, 224, 20, 19, 119, 224, 24, 19, 119, 224, 28, 19, 119, 224, 32, 19, - 119, 224, 36, 32, 16, 0, 213, 19, 119, 224, 12, 70, 192, 70, 192, 19, 119, 229, 58, 19, 119, 229, 108, 19, 119, 228, - 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, - 19, 119, 228, 202, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, - 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, - 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, 58, 19, 119, 228, 120, 19, 119, 229, 220, 19, 119, 228, - 120, 19, 119, 228, 120, 19, 119, 230, 24, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, - 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, - 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, - 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, - 102, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, 24, 19, 119, 228, 120, 19, 119, 228, 120, - 19, 119, 228, 196, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, - 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, - 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, - 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, - 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, - 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, - 230, 24, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, - 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, 70, 19, 119, 229, 170, 19, 119, 228, 120, 19, 119, 228, 120, - 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 158, 19, 119, 228, 120, 19, 119, 228, 120, 19, - 119, 228, 120, 19, 119, 228, 212, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, - 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, - 120, 19, 119, 228, 246, 19, 119, 228, 254, 19, 119, 229, 2, 19, 119, 229, 10, 19, 119, 229, 14, 19, 119, 229, 44, 19, - 119, 229, 48, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, - 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 229, 156, 47, 100, 101, 118, 47, 117, 115, 98, 47, 101, 104, - 99, 0, 0, 0, 0, 47, 100, 101, 118, 47, 117, 115, 98, 50, 0, 0, 0, 47, 100, 101, 118, 47, 115, 100, 105, 111, 47, 115, - 100, 104, 99, 0, 0, 19, 119, 236, 112, 19, 119, 236, 124, 19, 119, 236, 96 + 19, 119, 228, 85, 18, 52, 0, 1, 32, 34, 205, 172, 32, 32, 13, 57, 32, 32, 8, 197, 32, 32, 8, 153, 32, 32, 91, 129, 32, + 32, 0, 73, 32, 32, 40, 117, 32, 32, 54, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 119, 233, + 160, 19, 119, 233, 117, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 71, 120, 234, 0, 2, 23, 70, 192, + 71, 120, 234, 0, 2, 39, 70, 192, 71, 120, 234, 0, 2, 55, 70, 192, 71, 120, 234, 0, 2, 47, 70, 192, 71, 120, 234, 0, + 2, 21, 70, 192, 71, 120, 234, 0, 2, 7, 70, 192, 71, 120, 234, 0, 2, 45, 70, 192, 71, 120, 234, 0, 2, 41, 70, 192, 71, + 120, 234, 0, 2, 49, 181, 0, 75, 7, 176, 137, 147, 0, 70, 104, 35, 0, 33, 0, 34, 0, 147, 1, 147, 2, 240, 0, 252, 157, + 176, 9, 188, 2, 71, 8, 70, 192, 227, 0, 0, 0, 181, 16, 28, 3, 34, 32, 28, 12, 72, 13, 28, 25, 247, 255, 255, 210, 33, + 32, 72, 11, 247, 255, 255, 202, 73, 10, 34, 1, 104, 11, 66, 19, 209, 253, 34, 32, 28, 32, 73, 6, 247, 255, 255, 196, + 28, 32, 33, 32, 247, 255, 255, 188, 75, 4, 104, 24, 188, 16, 188, 2, 71, 8, 70, 192, 13, 0, 96, 0, 13, 0, 96, 28, 13, + 0, 96, 32, 181, 240, 70, 95, 70, 86, 70, 77, 70, 68, 180, 240, 10, 203, 70, 154, 75, 20, 176, 137, 37, 0, 28, 7, 28, + 14, 70, 145, 70, 108, 70, 155, 70, 168, 70, 91, 96, 35, 70, 67, 96, 99, 96, 163, 70, 83, 96, 227, 28, 56, 70, 75, 28, + 49, 97, 35, 247, 255, 255, 162, 70, 104, 28, 57, 28, 50, 240, 0, 252, 78, 53, 1, 40, 0, 209, 8, 176, 9, 188, 60, 70, + 144, 70, 153, 70, 162, 70, 171, 188, 240, 188, 2, 71, 8, 45, 15, 217, 223, 231, 243, 208, 0, 0, 0, 181, 112, 176, 136, + 75, 8, 28, 6, 28, 13, 70, 108, 147, 0, 96, 97, 146, 2, 247, 255, 255, 129, 28, 49, 28, 42, 70, 104, 240, 0, 252, 45, + 176, 8, 188, 112, 188, 2, 71, 8, 168, 0, 0, 0, 181, 240, 70, 95, 70, 86, 70, 77, 70, 68, 180, 240, 176, 143, 144, 4, + 145, 3, 146, 2, 41, 0, 209, 0, 224, 126, 10, 82, 70, 145, 35, 128, 34, 0, 1, 27, 70, 147, 34, 255, 147, 1, 3, 210, 171, + 6, 146, 0, 70, 152, 224, 7, 154, 3, 68, 179, 69, 90, 217, 62, 154, 5, 24, 179, 10, 219, 68, 153, 154, 3, 70, 91, 26, + 214, 70, 74, 2, 83, 154, 2, 66, 154, 216, 87, 35, 0, 147, 5, 36, 0, 159, 4, 34, 128, 68, 95, 28, 56, 28, 49, 1, 18, + 240, 0, 248, 103, 44, 0, 209, 47, 40, 0, 208, 45, 155, 0, 28, 6, 66, 152, 217, 1, 38, 255, 3, 246, 10, 242, 70, 146, + 36, 0, 75, 43, 70, 66, 96, 19, 35, 0, 96, 83, 96, 147, 70, 83, 96, 211, 70, 75, 97, 19, 28, 56, 28, 49, 247, 255, 255, + 38, 70, 64, 28, 57, 28, 50, 240, 0, 251, 210, 52, 1, 28, 5, 40, 0, 208, 192, 44, 15, 217, 230, 45, 0, 208, 188, 176, + 15, 28, 40, 188, 60, 70, 144, 70, 153, 70, 162, 70, 171, 188, 240, 188, 2, 71, 8, 154, 5, 25, 147, 154, 1, 66, 147, + 217, 1, 155, 5, 26, 214, 32, 128, 1, 0, 33, 32, 247, 255, 254, 251, 28, 4, 40, 0, 208, 18, 33, 128, 1, 9, 70, 74, 247, + 255, 255, 59, 28, 5, 40, 0, 208, 15, 28, 32, 247, 255, 254, 217, 231, 216, 26, 211, 0, 155, 28, 28, 147, 5, 30, 99, + 65, 156, 231, 163, 37, 1, 66, 109, 231, 208, 37, 0, 231, 206, 154, 5, 28, 56, 24, 161, 28, 50, 247, 255, 254, 214, 28, + 56, 28, 49, 247, 255, 254, 206, 231, 228, 70, 192, 208, 0, 0, 0, 181, 48, 28, 13, 28, 20, 6, 195, 209, 18, 75, 15, 66, + 152, 217, 19, 33, 0, 75, 14, 24, 194, 75, 14, 66, 154, 216, 1, 75, 13, 26, 25, 66, 161, 211, 5, 28, 8, 66, 169, 216, + 10, 30, 99, 67, 152, 224, 0, 32, 0, 188, 48, 188, 2, 71, 8, 35, 192, 4, 91, 26, 25, 231, 232, 28, 40, 30, 99, 67, 152, + 231, 244, 1, 127, 255, 255, 240, 0, 0, 0, 3, 97, 127, 255, 19, 97, 128, 0, 71, 112, 70, 192, 181, 48, 28, 4, 72, 15, + 28, 13, 104, 131, 104, 193, 176, 129, 24, 91, 24, 154, 105, 3, 43, 0, 209, 15, 104, 67, 43, 0, 209, 7, 28, 32, 28, 41, + 247, 255, 255, 13, 176, 1, 188, 48, 188, 2, 71, 8, 28, 32, 28, 41, 247, 255, 255, 27, 231, 246, 28, 32, 28, 41, 240, + 0, 249, 246, 231, 241, 70, 192, 19, 119, 240, 0, 181, 240, 79, 27, 35, 1, 28, 4, 96, 59, 176, 129, 33, 32, 247, 255, + 254, 127, 104, 227, 43, 8, 208, 8, 28, 32, 240, 0, 250, 246, 35, 0, 96, 59, 176, 1, 188, 240, 188, 2, 71, 8, 105, 163, + 37, 197, 104, 24, 104, 89, 247, 255, 254, 109, 105, 163, 1, 173, 104, 27, 28, 40, 33, 8, 104, 92, 104, 30, 247, 255, + 254, 100, 75, 10, 4, 36, 64, 30, 67, 52, 78, 9, 96, 44, 28, 40, 33, 4, 96, 52, 247, 255, 254, 73, 28, 48, 33, 4, 247, + 255, 254, 69, 35, 0, 96, 59, 32, 0, 231, 217, 70, 192, 19, 119, 240, 40, 0, 0, 255, 255, 0, 0, 49, 136, 181, 16, 73, + 20, 28, 4, 104, 139, 104, 202, 24, 154, 105, 11, 43, 0, 209, 18, 104, 75, 43, 0, 209, 11, 33, 32, 247, 255, 254, 175, + 40, 0, 219, 3, 105, 162, 75, 12, 66, 154, 208, 10, 188, 16, 188, 2, 71, 8, 33, 32, 247, 255, 254, 185, 231, 242, 33, + 32, 240, 0, 249, 149, 231, 238, 75, 6, 34, 1, 112, 26, 120, 91, 43, 0, 209, 238, 247, 255, 254, 10, 231, 235, 70, 192, + 19, 119, 240, 0, 93, 28, 158, 163, 32, 34, 205, 172, 181, 240, 70, 87, 70, 70, 180, 192, 28, 6, 120, 0, 176, 129, 28, + 15, 70, 144, 40, 224, 208, 24, 77, 145, 35, 0, 98, 43, 28, 3, 59, 112, 43, 143, 217, 13, 28, 48, 28, 57, 70, 66, 240, + 0, 250, 180, 28, 4, 176, 1, 28, 32, 188, 12, 70, 144, 70, 154, 188, 240, 188, 2, 71, 8, 74, 135, 0, 155, 88, 211, 70, + 159, 77, 132, 106, 43, 43, 0, 209, 2, 105, 43, 43, 0, 208, 230, 28, 56, 33, 0, 70, 66, 240, 0, 249, 10, 106, 43, 96, + 59, 28, 56, 70, 65, 247, 255, 253, 212, 36, 0, 231, 223, 104, 107, 43, 0, 209, 2, 105, 43, 43, 0, 208, 211, 36, 0, 231, + 215, 104, 107, 43, 0, 209, 2, 105, 43, 43, 0, 208, 203, 28, 56, 33, 0, 70, 66, 240, 0, 248, 239, 28, 56, 70, 65, 247, + 255, 253, 187, 36, 0, 231, 198, 104, 115, 36, 0, 96, 171, 231, 194, 104, 171, 231, 217, 104, 115, 36, 0, 96, 43, 231, + 188, 104, 43, 231, 211, 104, 115, 97, 43, 43, 0, 208, 6, 28, 40, 28, 49, 48, 24, 49, 8, 34, 6, 247, 255, 253, 166, 105, + 115, 36, 0, 97, 107, 231, 171, 105, 43, 231, 194, 104, 114, 35, 36, 84, 234, 36, 0, 231, 164, 104, 235, 104, 172, 70, + 154, 105, 43, 43, 0, 209, 0, 224, 170, 32, 0, 34, 0, 70, 83, 67, 35, 209, 2, 42, 0, 209, 0, 224, 142, 28, 3, 30, 90, + 65, 147, 96, 107, 28, 56, 70, 65, 247, 255, 255, 70, 28, 4, 231, 139, 35, 1, 34, 37, 84, 171, 104, 43, 43, 0, 209, 0, + 224, 132, 104, 113, 104, 178, 28, 56, 247, 255, 254, 214, 28, 4, 34, 0, 35, 37, 84, 234, 44, 0, 208, 0, 231, 120, 28, + 56, 70, 65, 247, 255, 254, 201, 231, 115, 104, 115, 72, 70, 64, 24, 247, 255, 253, 139, 28, 4, 231, 108, 76, 68, 33, + 64, 28, 32, 247, 255, 253, 106, 34, 0, 28, 33, 224, 3, 50, 1, 42, 64, 209, 0, 231, 90, 92, 163, 43, 0, 208, 248, 34, + 64, 28, 56, 247, 255, 253, 80, 28, 56, 33, 64, 247, 255, 253, 72, 36, 0, 231, 83, 35, 36, 92, 234, 42, 0, 208, 0, 231, + 116, 84, 234, 35, 37, 84, 234, 105, 43, 96, 42, 96, 106, 96, 170, 96, 234, 98, 42, 70, 154, 43, 0, 209, 0, 231, 59, + 105, 108, 247, 255, 253, 73, 70, 80, 28, 41, 28, 34, 56, 1, 49, 24, 240, 0, 248, 206, 28, 4, 231, 53, 104, 113, 104, + 178, 40, 208, 208, 59, 28, 56, 247, 255, 254, 133, 28, 4, 40, 0, 208, 0, 231, 42, 35, 37, 92, 235, 43, 0, 208, 0, 231, + 37, 231, 171, 105, 43, 43, 0, 209, 0, 231, 26, 35, 2, 231, 55, 104, 107, 43, 0, 209, 3, 105, 43, 43, 0, 209, 0, 231, + 17, 104, 115, 104, 178, 7, 155, 67, 19, 74, 24, 36, 0, 64, 19, 96, 235, 231, 14, 104, 107, 43, 0, 208, 17, 75, 21, 36, + 160, 98, 43, 2, 36, 231, 6, 105, 43, 43, 0, 208, 0, 231, 108, 96, 106, 36, 0, 230, 255, 28, 48, 70, 66, 240, 0, 249, + 175, 28, 4, 231, 122, 105, 43, 43, 0, 209, 234, 230, 239, 2, 201, 2, 82, 231, 192, 70, 66, 28, 48, 240, 0, 249, 162, + 28, 2, 30, 83, 65, 154, 231, 78, 70, 192, 19, 119, 240, 0, 19, 119, 234, 32, 127, 255, 255, 255, 19, 119, 233, 160, + 255, 255, 128, 0, 0, 5, 49, 0, 181, 240, 70, 87, 70, 78, 70, 69, 180, 224, 70, 128, 28, 14, 70, 148, 42, 0, 208, 51, + 33, 3, 28, 2, 64, 10, 35, 4, 26, 155, 28, 24, 64, 8, 69, 96, 216, 49, 40, 0, 208, 49, 36, 0, 70, 67, 85, 30, 52, 1, + 66, 160, 216, 250, 69, 132, 208, 32, 70, 99, 26, 27, 8, 159, 70, 153, 0, 187, 70, 154, 43, 0, 208, 17, 4, 51, 6, 50, + 2, 49, 67, 26, 67, 10, 28, 21, 70, 67, 67, 53, 24, 26, 33, 0, 0, 139, 49, 1, 80, 213, 66, 185, 211, 250, 68, 84, 69, + 209, 208, 6, 70, 67, 25, 24, 52, 1, 112, 6, 48, 1, 69, 164, 216, 250, 188, 28, 70, 144, 70, 153, 70, 162, 188, 240, + 188, 1, 71, 0, 70, 96, 231, 203, 36, 0, 231, 211, 70, 192, 181, 112, 76, 17, 28, 6, 104, 32, 176, 130, 28, 13, 98, 2, + 97, 6, 100, 1, 97, 65, 33, 68, 247, 255, 252, 121, 28, 48, 28, 41, 247, 255, 252, 117, 75, 10, 34, 2, 104, 24, 104, + 35, 73, 9, 147, 0, 35, 1, 247, 255, 252, 128, 28, 41, 28, 4, 28, 48, 247, 255, 252, 119, 176, 2, 28, 32, 188, 112, 188, + 2, 71, 8, 19, 119, 240, 44, 19, 119, 240, 48, 87, 70, 83, 2, 181, 240, 176, 133, 28, 4, 28, 15, 146, 3, 40, 2, 216, + 75, 77, 47, 104, 43, 43, 0, 208, 74, 78, 46, 104, 48, 40, 0, 219, 1, 247, 255, 252, 71, 74, 44, 0, 163, 88, 152, 33, + 1, 247, 255, 252, 81, 96, 48, 40, 0, 219, 66, 104, 48, 40, 0, 219, 49, 104, 40, 28, 57, 34, 6, 48, 32, 247, 255, 252, + 61, 104, 40, 169, 3, 34, 4, 48, 64, 247, 255, 252, 55, 104, 42, 36, 4, 28, 19, 51, 32, 96, 19, 104, 42, 35, 6, 96, 83, + 104, 42, 33, 68, 28, 19, 51, 64, 96, 147, 104, 43, 96, 220, 104, 40, 247, 255, 252, 33, 104, 43, 104, 48, 34, 2, 147, + 0, 73, 22, 35, 0, 247, 255, 252, 45, 104, 42, 28, 19, 51, 32, 96, 19, 104, 43, 96, 92, 104, 42, 28, 19, 51, 64, 96, + 147, 104, 43, 96, 220, 176, 5, 188, 240, 188, 2, 71, 8, 32, 1, 66, 64, 231, 248, 75, 11, 78, 8, 96, 43, 35, 1, 66, 91, + 96, 51, 231, 179, 44, 0, 209, 186, 72, 8, 33, 1, 247, 255, 252, 5, 96, 48, 231, 180, 70, 192, 19, 119, 240, 44, 19, + 119, 240, 48, 19, 119, 236, 140, 87, 70, 83, 1, 19, 119, 240, 64, 19, 119, 236, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 233, 45, 64, 128, 229, 159, 113, 80, 229, 151, 112, 0, 235, 0, 0, 45, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, + 64, 128, 229, 159, 113, 60, 229, 151, 112, 0, 235, 0, 0, 39, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, + 229, 159, 113, 40, 229, 151, 112, 0, 235, 0, 0, 33, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, 229, 159, + 113, 20, 229, 151, 112, 0, 235, 0, 0, 27, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, 229, 159, 113, 0, 229, + 151, 112, 0, 235, 0, 0, 21, 232, 189, 64, 128, 225, 47, 255, 30, 233, 45, 64, 128, 229, 159, 112, 236, 229, 151, 112, + 0, 235, 0, 0, 15, 232, 189, 64, 128, 225, 47, 255, 30, 230, 0, 8, 16, 225, 47, 255, 30, 230, 0, 7, 240, 225, 47, 255, + 30, 230, 0, 3, 144, 225, 47, 255, 30, 230, 0, 3, 176, 225, 47, 255, 30, 230, 0, 3, 208, 225, 47, 255, 30, 230, 0, 3, + 240, 225, 47, 255, 30, 230, 0, 4, 80, 225, 47, 255, 30, 225, 47, 255, 23, 239, 0, 0, 204, 225, 47, 255, 30, 180, 124, + 181, 0, 247, 255, 252, 254, 188, 2, 188, 124, 71, 8, 181, 112, 176, 136, 104, 133, 28, 1, 75, 34, 71, 24, 70, 192, 70, + 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 70, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 70, 114, 28, 1, 32, 4, 223, 171, 71, 16, 181, 240, 70, 95, 70, 86, 70, 77, 70, 68, 180, 240, + 75, 8, 104, 27, 71, 24, 19, 119, 224, 16, 19, 119, 224, 20, 19, 119, 224, 24, 19, 119, 224, 28, 19, 119, 224, 32, 19, + 119, 224, 36, 32, 16, 0, 213, 19, 119, 224, 12, 70, 192, 70, 192, 19, 119, 229, 58, 19, 119, 229, 108, 19, 119, 228, + 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, + 19, 119, 228, 202, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, + 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, + 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, 58, 19, 119, 228, 120, 19, 119, 229, 220, 19, 119, 228, + 120, 19, 119, 228, 120, 19, 119, 230, 24, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, + 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, + 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, + 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, + 102, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, 24, 19, 119, 228, 120, 19, 119, 228, 120, + 19, 119, 228, 196, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, + 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, + 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, + 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, + 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, + 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, + 230, 24, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, + 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 230, 70, 19, 119, 229, 170, 19, 119, 228, 120, 19, 119, 228, 120, + 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 158, 19, 119, 228, 120, 19, 119, 228, 120, 19, + 119, 228, 120, 19, 119, 228, 212, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, + 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, + 120, 19, 119, 228, 246, 19, 119, 228, 254, 19, 119, 229, 2, 19, 119, 229, 10, 19, 119, 229, 14, 19, 119, 229, 44, 19, + 119, 229, 48, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, + 228, 120, 19, 119, 228, 120, 19, 119, 228, 120, 19, 119, 229, 156, 47, 100, 101, 118, 47, 117, 115, 98, 47, 101, 104, + 99, 0, 0, 0, 0, 47, 100, 101, 118, 47, 117, 115, 98, 50, 0, 0, 0, 47, 100, 101, 118, 47, 115, 100, 105, 111, 47, 115, + 100, 104, 99, 0, 0, 19, 119, 236, 112, 19, 119, 236, 124, 19, 119, 236, 96 }; diff --git a/source/mload/mload.c b/source/mload/mload.c index 367d8f17..2e83a97c 100644 --- a/source/mload/mload.c +++ b/source/mload/mload.c @@ -1,4 +1,4 @@ -/* mload.c (for PPC) (c) 2009, Hermes +/* mload.c (for PPC) (c) 2009, Hermes 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 @@ -34,76 +34,85 @@ int size_external_ehcmodule=0; // to init/test if the device is running -int mload_init() { - int n; +int mload_init() +{ +int n; - if (hid<0) hid = iosCreateHeap(0x800); + if(hid<0) hid = iosCreateHeap(0x800); - if (hid<0) { - if (mload_fd>=0) - IOS_Close(mload_fd); + if(hid<0) + { + if(mload_fd>=0) + IOS_Close(mload_fd); - mload_fd=-1; + mload_fd=-1; - return hid; - } + return hid; + } - if (mload_fd>=0) { - return 0; - } + if(mload_fd>=0) + { + return 0; + } - for (n=0;n<20;n++) { // try 5 seconds - mload_fd=IOS_Open(mload_fs, 0); + for(n=0;n<20;n++) // try 5 seconds + { + mload_fd=IOS_Open(mload_fs, 0); + + if(mload_fd>=0) break; - if (mload_fd>=0) break; + usleep(250*1000); + } - usleep(250*1000); - } + if(mload_fd<0) + { + + if(hid>=0) + { + iosDestroyHeap(hid); + hid=-1; + } + } - if (mload_fd<0) { - - if (hid>=0) { - iosDestroyHeap(hid); - hid=-1; - } - } - - return mload_fd; +return mload_fd; } /*--------------------------------------------------------------------------------------------------------------*/ // to close the device (remember call it when rebooting the IOS!) -int mload_close() { - int ret; +int mload_close() +{ +int ret; - if (hid>=0) { - iosDestroyHeap(hid); - hid=-1; - } + if(hid>=0) + { + iosDestroyHeap(hid); + hid=-1; + } - if (mload_fd<0) return -1; + if(mload_fd<0) return -1; + + ret=IOS_Close(mload_fd); + + mload_fd=-1; - ret=IOS_Close(mload_fd); - - mload_fd=-1; - - return ret; +return ret; } /*--------------------------------------------------------------------------------------------------------------*/ // to get the thread id of mload -int mload_get_thread_id() { - int ret; +int mload_get_thread_id() +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_MLOAD_THREAD_ID, ":"); - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_MLOAD_THREAD_ID, ":"); - - return ret; +return ret; } @@ -111,14 +120,15 @@ int mload_get_thread_id() { // get the base and the size of the memory readable/writable to load modules -int mload_get_load_base(u32 *starlet_base, int *size) { - int ret; +int mload_get_load_base(u32 *starlet_base, int *size) +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_LOAD_BASE, ":ii",starlet_base, size); - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_LOAD_BASE, ":ii",starlet_base, size); - - return ret; +return ret; } @@ -127,50 +137,47 @@ int mload_get_load_base(u32 *starlet_base, int *size) { // load and run a module from starlet (it need to allocate MEM2 to send the elf file) // the module must be a elf made with stripios -int mload_module(void *addr, int len) { - int ret; - void *buf=NULL; +int mload_module(void *addr, int len) +{ +int ret; +void *buf=NULL; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; - if (hid>=0) { - iosDestroyHeap(hid); - hid=-1; - } + if(hid>=0) + { + iosDestroyHeap(hid); + hid=-1; + } - hid = iosCreateHeap(len+0x800); + hid = iosCreateHeap(len+0x800); + + if(hid<0) return hid; - if (hid<0) return hid; + buf= iosAlloc(hid, len); - buf= iosAlloc(hid, len); + if(!buf) {ret= -1;goto out;} - if (!buf) { - ret= -1; - goto out; - } + + memcpy(buf, addr,len); + ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_LOAD_MODULE, ":d", buf, len); - memcpy(buf, addr,len); - - ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_LOAD_MODULE, ":d", buf, len); - - if (ret<0) goto out; - - ret=IOS_IoctlvFormat(hid, mload_fd, MLOAD_RUN_MODULE, ":"); - - if (ret<0) { - ret= -666; - goto out; - } + if(ret<0) goto out; + + ret=IOS_IoctlvFormat(hid, mload_fd, MLOAD_RUN_MODULE, ":"); + if(ret<0) {ret= -666;goto out;} + out: - if (hid>=0) { - iosDestroyHeap(hid); - hid=-1; - } - - return ret; + if(hid>=0) + { + iosDestroyHeap(hid); + hid=-1; + } + +return ret; } @@ -179,94 +186,103 @@ out: // load a module from the PPC // the module must be a elf made with stripios -int mload_elf(void *my_elf, data_elf *data_elf) { - int n,m; - int p; - u8 *adr; - u32 elf=(u32) my_elf; +int mload_elf(void *my_elf, data_elf *data_elf) +{ +int n,m; +int p; +u8 *adr; +u32 elf=(u32) my_elf; - if (elf & 3) return -1; // aligned to 4 please! +if(elf & 3) return -1; // aligned to 4 please! - elfheader *head=(void *) elf; - elfphentry *entries; +elfheader *head=(void *) elf; +elfphentry *entries; - if (head->ident0!=0x7F454C46) return -1; - if (head->ident1!=0x01020161) return -1; - if (head->ident2!=0x01000000) return -1; +if(head->ident0!=0x7F454C46) return -1; +if(head->ident1!=0x01020161) return -1; +if(head->ident2!=0x01000000) return -1; - p=head->phoff; +p=head->phoff; - data_elf->start=(void *) head->entry; +data_elf->start=(void *) head->entry; - for (n=0; nphnum; n++) { - entries=(void *) (elf+p); - p+=sizeof(elfphentry); +for(n=0; nphnum; n++) + { + entries=(void *) (elf+p); + p+=sizeof(elfphentry); - if (entries->type == 4) { - adr=(void *) (elf + entries->offset); + if(entries->type == 4) + { + adr=(void *) (elf + entries->offset); - if (getbe32(0)!=0) return -2; // bad info (sure) + if(getbe32(0)!=0) return -2; // bad info (sure) - for (m=4; m < entries->memsz; m+=8) { - switch (getbe32(m)) { - case 0x9: - data_elf->start= (void *) getbe32(m+4); - break; - case 0x7D: - data_elf->prio= getbe32(m+4); - break; - case 0x7E: - data_elf->size_stack= getbe32(m+4); - break; - case 0x7F: - data_elf->stack= (void *) (getbe32(m+4)); - break; + for(m=4; m < entries->memsz; m+=8) + { + switch(getbe32(m)) + { + case 0x9: + data_elf->start= (void *) getbe32(m+4); + break; + case 0x7D: + data_elf->prio= getbe32(m+4); + break; + case 0x7E: + data_elf->size_stack= getbe32(m+4); + break; + case 0x7F: + data_elf->stack= (void *) (getbe32(m+4)); + break; + + } - } + } - } + } + else + if(entries->type == 1 && entries->memsz != 0 && entries->vaddr!=0) + { - } else - if (entries->type == 1 && entries->memsz != 0 && entries->vaddr!=0) { + if(mload_memset((void *) entries->vaddr, 0, entries->memsz)<0) return -1; + if(mload_seek(entries->vaddr, SEEK_SET)<0) return -1; + if(mload_write((void *) (elf + entries->offset), entries->filesz)<0) return -1; + + } + } - if (mload_memset((void *) entries->vaddr, 0, entries->memsz)<0) return -1; - if (mload_seek(entries->vaddr, SEEK_SET)<0) return -1; - if (mload_write((void *) (elf + entries->offset), entries->filesz)<0) return -1; - - } - } - - return 0; +return 0; } /*--------------------------------------------------------------------------------------------------------------*/ // run one thread (you can use to load modules or binary files) -int mload_run_thread(void *starlet_addr, void *starlet_top_stack, int stack_size, int priority) { - int ret; +int mload_run_thread(void *starlet_addr, void *starlet_top_stack, int stack_size, int priority) +{ +int ret; - if (mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_RUN_THREAD, "iiii:", starlet_addr,starlet_top_stack, stack_size, priority); + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_RUN_THREAD, "iiii:", starlet_addr,starlet_top_stack, stack_size, priority); - return ret; +return ret; } /*--------------------------------------------------------------------------------------------------------------*/ // stops one starlet thread -int mload_stop_thread(int id) { - int ret; +int mload_stop_thread(int id) +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_STOP_THREAD, "i:", id); - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_STOP_THREAD, "i:", id); - - return ret; +return ret; } @@ -274,150 +290,163 @@ int mload_stop_thread(int id) { // continue one stopped starlet thread -int mload_continue_thread(int id) { - int ret; +int mload_continue_thread(int id) +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_CONTINUE_THREAD, "i:", id); - - return ret; + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_CONTINUE_THREAD, "i:", id); + +return ret; } /*--------------------------------------------------------------------------------------------------------------*/ // fix starlet address to read/write (uses SEEK_SET, etc as mode) -int mload_seek(int offset, int mode) { - if (mload_init()<0) return -1; +int mload_seek(int offset, int mode) +{ + if(mload_init()<0) return -1; - return IOS_Seek(mload_fd, offset, mode); + return IOS_Seek(mload_fd, offset, mode); } /*--------------------------------------------------------------------------------------------------------------*/ // read bytes from starlet (it update the offset) -int mload_read(void* buf, u32 size) { - if (mload_init()<0) return -1; +int mload_read(void* buf, u32 size) +{ + if(mload_init()<0) return -1; - return IOS_Read(mload_fd, buf, size); + return IOS_Read(mload_fd, buf, size); } /*--------------------------------------------------------------------------------------------------------------*/ // write bytes from starlet (it update the offset) -int mload_write(const void * buf, u32 size) { - if (mload_init()<0) return -1; +int mload_write(const void * buf, u32 size) +{ + if(mload_init()<0) return -1; - return IOS_Write(mload_fd, buf, size); + return IOS_Write(mload_fd, buf, size); } /*--------------------------------------------------------------------------------------------------------------*/ // fill a block (similar to memset) -int mload_memset(void *starlet_addr, int set, int len) { - int ret; +int mload_memset(void *starlet_addr, int set, int len) +{ +int ret; - if (mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_MEMSET, "iii:", starlet_addr, set, len); + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_MEMSET, "iii:", starlet_addr, set, len); - return ret; +return ret; } /*--------------------------------------------------------------------------------------------------------------*/ // get the ehci datas ( ehcmodule.elf uses this address) -void * mload_get_ehci_data() { - int ret; +void * mload_get_ehci_data() +{ +int ret; - if (mload_init()<0) return NULL; + if(mload_init()<0) return NULL; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_EHCI_DATA, ":"); + if(ret<0) return NULL; - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_EHCI_DATA, ":"); - if (ret<0) return NULL; - - return (void *) ret; +return (void *) ret; } /*--------------------------------------------------------------------------------------------------------------*/ // set the dev/es ioctlv in routine -int mload_set_ES_ioctlv_vector(void *starlet_addr) { - int ret; +int mload_set_ES_ioctlv_vector(void *starlet_addr) +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SET_ES_IOCTLV, "i:", starlet_addr); - - return ret; + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SET_ES_IOCTLV, "i:", starlet_addr); + +return ret; } -int mload_getw(const void * addr, u32 *dat) { - int ret; +int mload_getw(const void * addr, u32 *dat) +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETW, "i:i", addr, dat); - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETW, "i:i", addr, dat); - - return ret; +return ret; } -int mload_geth(const void * addr, u16 *dat) { - int ret; +int mload_geth(const void * addr, u16 *dat) +{ +int ret; - if (mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETH, "i:h", addr, dat); - - return ret; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETH, "i:h", addr, dat); + +return ret; } -int mload_getb(const void * addr, u8 *dat) { - int ret; +int mload_getb(const void * addr, u8 *dat) +{ +int ret; - if (mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETB, "i:b", addr, dat); - - return ret; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETB, "i:b", addr, dat); + +return ret; } -int mload_setw(const void * addr, u32 dat) { - int ret; +int mload_setw(const void * addr, u32 dat) +{ +int ret; - if (mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETW, "ii:", addr, dat); - - return ret; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETW, "ii:", addr, dat); + +return ret; } -int mload_seth(const void * addr, u16 dat) { - int ret; +int mload_seth(const void * addr, u16 dat) +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETH, "ih:", addr, dat); - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETH, "ih:", addr, dat); - - return ret; +return ret; } -int mload_setb(const void * addr, u8 dat) { - int ret; +int mload_setb(const void * addr, u8 dat) +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETB, "ib:", addr, dat); + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETB, "ib:", addr, dat); - return ret; +return ret; } /*--------------------------------------------------------------------------------------------------------------*/ @@ -425,14 +454,15 @@ int mload_setb(const void * addr, u8 dat) { // to get log buffer // this function return the size of the log buffer and prepare it to read with mload_read() the datas -int mload_get_log() { - int ret; +int mload_get_log() +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_LOG, ":"); - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_LOG, ":"); - - return ret; +return ret; } @@ -441,130 +471,143 @@ int mload_get_log() { // to get IOS base for dev/es to create the cIOS -int mload_get_IOS_base() { - int ret; +int mload_get_IOS_base() +{ +int ret; - if (mload_init()<0) return -1; + if(mload_init()<0) return -1; + + ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_IOS_BASE, ":"); - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_IOS_BASE, ":"); - - return ret; +return ret; } -static u32 ios_36[16] ATTRIBUTE_ALIGN(32)= { - 0, // DI_EmulateCmd - 0, - 0x2022DDAC, // dvd_read_controlling_data - 0x20201010+1, // handle_di_cmd_reentry (thumb) - 0x20200b9c+1, // ios_shared_alloc_aligned (thumb) - 0x20200b70+1, // ios_shared_free (thumb) - 0x20205dc0+1, // ios_memcpy (thumb) - 0x20200048+1, // ios_fatal_di_error (thumb) - 0x20202b4c+1, // ios_doReadHashEncryptedState (thumb) - 0x20203934+1, // ios_printf (thumb) +static u32 ios_36[16] ATTRIBUTE_ALIGN(32)= +{ + 0, // DI_EmulateCmd + 0, + 0x2022DDAC, // dvd_read_controlling_data + 0x20201010+1, // handle_di_cmd_reentry (thumb) + 0x20200b9c+1, // ios_shared_alloc_aligned (thumb) + 0x20200b70+1, // ios_shared_free (thumb) + 0x20205dc0+1, // ios_memcpy (thumb) + 0x20200048+1, // ios_fatal_di_error (thumb) + 0x20202b4c+1, // ios_doReadHashEncryptedState (thumb) + 0x20203934+1, // ios_printf (thumb) }; -static u32 ios_38[16] ATTRIBUTE_ALIGN(32)= { - 0, // DI_EmulateCmd - 0, - 0x2022cdac, // dvd_read_controlling_data - 0x20200d38+1, // handle_di_cmd_reentry (thumb) - 0x202008c4+1, // ios_shared_alloc_aligned (thumb) - 0x20200898+1, // ios_shared_free (thumb) - 0x20205b80+1, // ios_memcpy (thumb) - 0x20200048+1, // ios_fatal_di_error (thumb) - 0x20202874+1, // ios_doReadHashEncryptedState (thumb) - 0x2020365c+1, // ios_printf (thumb) +static u32 ios_38[16] ATTRIBUTE_ALIGN(32)= +{ + 0, // DI_EmulateCmd + 0, + 0x2022cdac, // dvd_read_controlling_data + 0x20200d38+1, // handle_di_cmd_reentry (thumb) + 0x202008c4+1, // ios_shared_alloc_aligned (thumb) + 0x20200898+1, // ios_shared_free (thumb) + 0x20205b80+1, // ios_memcpy (thumb) + 0x20200048+1, // ios_fatal_di_error (thumb) + 0x20202874+1, // ios_doReadHashEncryptedState (thumb) + 0x2020365c+1, // ios_printf (thumb) }; -int load_ehc_module() { - int is_ios=0; - FILE *fp; +int load_ehc_module() +{ + int is_ios=0; + FILE *fp; - if (!external_ehcmodule) { + if(!external_ehcmodule) + { - fp=fopen("SD:/apps/usbloader_gx/ehcmodule.elf","rb"); - if (fp==NULL) - fp=fopen("SD:/apps/usbloadergx/ehcmodule.elf","rb"); + fp=fopen("SD:/apps/usbloader_gx/ehcmodule.elf","rb"); + if(fp==NULL) + fp=fopen("SD:/apps/usbloadergx/ehcmodule.elf","rb"); - if (fp!=NULL) { + if(fp!=NULL) + { - fseek(fp, 0, SEEK_END); - size_external_ehcmodule = ftell(fp); - external_ehcmodule = memalign(32, size_external_ehcmodule); - if (!external_ehcmodule) { - fclose(fp); - } else { - fseek(fp, 0, SEEK_SET); + fseek(fp, 0, SEEK_END); + size_external_ehcmodule = ftell(fp); + external_ehcmodule = memalign(32, size_external_ehcmodule); + if(!external_ehcmodule) + {fclose(fp);} + else + { + fseek(fp, 0, SEEK_SET); - if (fread(external_ehcmodule,1, size_external_ehcmodule ,fp)!=size_external_ehcmodule) { - free(external_ehcmodule); - external_ehcmodule=NULL; - } + if(fread(external_ehcmodule,1, size_external_ehcmodule ,fp)!=size_external_ehcmodule) + {free(external_ehcmodule); external_ehcmodule=NULL;} + + fclose(fp); + } + } + } + + if(!external_ehcmodule) + { + if(mload_init()<0) return -1; + mload_elf((void *) ehcmodule_frag_bin, &my_data_elf); + thread_id = mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); + if(thread_id < 0) return -1; + } + else + { + if(mload_init()<0) return -1; + mload_elf((void *) external_ehcmodule, &my_data_elf); + thread_id = mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); + if(thread_id<0) return -1; + } + usleep(350*1000); + - fclose(fp); - } - } - } + // Test for IOS + mload_seek(0x20207c84, SEEK_SET); + mload_read(patch_datas, 4); + if(patch_datas[0]==0x6e657665) + { + is_ios=38; + } + else + { + is_ios=36; + } - if (!external_ehcmodule) { - if (mload_init()<0) return -1; - mload_elf((void *) ehcmodule_frag_bin, &my_data_elf); - thread_id = mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); - if (thread_id < 0) return -1; - } else { - if (mload_init()<0) return -1; - mload_elf((void *) external_ehcmodule, &my_data_elf); - thread_id = mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); - if (thread_id<0) return -1; - } - usleep(350*1000); + if(is_ios==36) + { + // IOS 36 + memcpy(ios_36, dip_plugin, 4); // copy the entry_point + memcpy(dip_plugin, ios_36, 4*10); // copy the adresses from the array + + mload_seek(0x1377E000, SEEK_SET); // copy dip_plugin in the starlet + mload_write(dip_plugin,size_dip_plugin); + // enables DIP plugin + mload_seek(0x20209040, SEEK_SET); + mload_write(ios_36, 4); + + } + if(is_ios==38) + { + // IOS 38 - // Test for IOS - mload_seek(0x20207c84, SEEK_SET); - mload_read(patch_datas, 4); - if (patch_datas[0]==0x6e657665) { - is_ios=38; - } else { - is_ios=36; - } + memcpy(ios_38, dip_plugin, 4); // copy the entry_point + memcpy(dip_plugin, ios_38, 4*10); // copy the adresses from the array + + mload_seek(0x1377E000, SEEK_SET); // copy dip_plugin in the starlet + mload_write(dip_plugin,size_dip_plugin); - if (is_ios==36) { - // IOS 36 - memcpy(ios_36, dip_plugin, 4); // copy the entry_point - memcpy(dip_plugin, ios_36, 4*10); // copy the adresses from the array + // enables DIP plugin + mload_seek(0x20208030, SEEK_SET); + mload_write(ios_38, 4); - mload_seek(0x1377E000, SEEK_SET); // copy dip_plugin in the starlet - mload_write(dip_plugin,size_dip_plugin); + } - // enables DIP plugin - mload_seek(0x20209040, SEEK_SET); - mload_write(ios_36, 4); + mload_close(); - } - if (is_ios==38) { - // IOS 38 - - memcpy(ios_38, dip_plugin, 4); // copy the entry_point - memcpy(dip_plugin, ios_38, 4*10); // copy the adresses from the array - - mload_seek(0x1377E000, SEEK_SET); // copy dip_plugin in the starlet - mload_write(dip_plugin,size_dip_plugin); - - // enables DIP plugin - mload_seek(0x20208030, SEEK_SET); - mload_write(ios_38, 4); - - } - - mload_close(); - - return 0; +return 0; } diff --git a/source/mload/mload.h b/source/mload/mload.h index 822ef417..e068941e 100644 --- a/source/mload/mload.h +++ b/source/mload/mload.h @@ -1,4 +1,4 @@ -/* mload.c (for PPC) (c) 2009, Hermes +/* mload.c (for PPC) (c) 2009, Hermes 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 @@ -59,11 +59,12 @@ extern "C" { #define getbe32(x) ((adr[x]<<24) | (adr[x+1]<<16) | (adr[x+2]<<8) | (adr[x+3])) - typedef struct { +typedef struct +{ u32 ident0; - u32 ident1; - u32 ident2; - u32 ident3; + u32 ident1; + u32 ident2; + u32 ident3; u32 machinetype; u32 version; u32 entry; @@ -76,151 +77,153 @@ extern "C" { u16 shentsize; u16 shnum; u16 shtrndx; - } elfheader; +} elfheader; - typedef struct { - u32 type; - u32 offset; - u32 vaddr; - u32 paddr; - u32 filesz; - u32 memsz; - u32 flags; - u32 align; - } elfphentry; +typedef struct +{ + u32 type; + u32 offset; + u32 vaddr; + u32 paddr; + u32 filesz; + u32 memsz; + u32 flags; + u32 align; +} elfphentry; - typedef struct { - void *start; - int prio; - void *stack; - int size_stack; - } data_elf; +typedef struct +{ + void *start; + int prio; + void *stack; + int size_stack; +} data_elf; - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // to init/test if the device is running - int mload_init(); +int mload_init(); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // to close the device (remember call it when rebooting the IOS!) - int mload_close(); +int mload_close(); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // to get the thread id of mload - int mload_get_thread_id(); +int mload_get_thread_id(); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // get the base and the size of the memory readable/writable to load modules - int mload_get_load_base(u32 *starlet_base, int *size); +int mload_get_load_base(u32 *starlet_base, int *size); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // load and run a module from starlet (it need to allocate MEM2 to send the elf file) // the module must be a elf made with stripios - int mload_module(void *addr, int len); +int mload_module(void *addr, int len); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // load a module from the PPC // the module must be a elf made with stripios - int mload_elf(void *my_elf, data_elf *data_elf); +int mload_elf(void *my_elf, data_elf *data_elf); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // run one thread (you can use to load modules or binary files) - int mload_run_thread(void *starlet_addr, void *starlet_top_stack, int stack_size, int priority); +int mload_run_thread(void *starlet_addr, void *starlet_top_stack, int stack_size, int priority); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // stops one starlet thread - int mload_stop_thread(int id); +int mload_stop_thread(int id); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // continue one stopped starlet thread - int mload_continue_thread(int id); +int mload_continue_thread(int id); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // fix starlet address to read/write (uses SEEK_SET, etc as mode) - int mload_seek(int offset, int mode); +int mload_seek(int offset, int mode); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // read bytes from starlet (it update the offset) - int mload_read(void* buf, u32 size); +int mload_read(void* buf, u32 size); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // write bytes from starlet (it update the offset) - int mload_write(const void * buf, u32 size); +int mload_write(const void * buf, u32 size); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // fill a block (similar to memset) - int mload_memset(void *starlet_addr, int set, int len); +int mload_memset(void *starlet_addr, int set, int len); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // get the ehci datas ( ehcmodule.elf uses this address) - void * mload_get_ehci_data(); +void * mload_get_ehci_data(); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // set the dev/es ioctlv in routine - int mload_set_ES_ioctlv_vector(void *starlet_addr); +int mload_set_ES_ioctlv_vector(void *starlet_addr); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // to get log buffer // this function return the size of the log buffer and prepare it to read with mload_read() the datas - int mload_get_log(); +int mload_get_log(); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ // to get IOS base for dev/es to create the cIOS - int mload_get_IOS_base(); +int mload_get_IOS_base(); - /*--------------------------------------------------------------------------------------------------------------*/ +/*--------------------------------------------------------------------------------------------------------------*/ - int mload_getw(const void * addr, u32 *dat); - int mload_geth(const void * addr, u16 *dat); - int mload_getb(const void * addr, u8 *dat); +int mload_getw(const void * addr, u32 *dat); +int mload_geth(const void * addr, u16 *dat); +int mload_getb(const void * addr, u8 *dat); - int mload_setw(const void * addr, u32 dat); - int mload_seth(const void * addr, u16 dat); - int mload_setb(const void * addr, u8 dat); +int mload_setw(const void * addr, u32 dat); +int mload_seth(const void * addr, u16 dat); +int mload_setb(const void * addr, u8 dat); - /*--------------------------------------------------------------------------------------------------------------*/ - int load_ehc_module(); - int patch_cios_data(); +/*--------------------------------------------------------------------------------------------------------------*/ +int load_ehc_module(); +int patch_cios_data(); #ifdef __cplusplus -} + } #endif diff --git a/source/network/networkops.cpp b/source/network/networkops.cpp index ae10c665..a718e638 100644 --- a/source/network/networkops.cpp +++ b/source/network/networkops.cpp @@ -125,14 +125,17 @@ s32 network_request(const char * request, char * filename) { if (!strstr(buf, "HTTP/1.1 200 OK")) return -1; - if (filename) { + if(filename) + { /* Get filename */ ptr = strstr(buf, "filename=\""); - if (ptr) { + if(ptr) + { ptr += sizeof("filename=\"")-1; - for (cnt = 0; ptr[cnt] != '\r' && ptr[cnt] != '\n' && ptr[cnt] != '"'; cnt++) { + for(cnt = 0; ptr[cnt] != '\r' && ptr[cnt] != '\n' && ptr[cnt] != '"'; cnt++) + { filename[cnt] = ptr[cnt]; filename[cnt+1] = '\0'; } @@ -269,14 +272,14 @@ int NetworkWait() { unsigned char haxx[9]; //skip haxx net_read(connection, &haxx, 8); - wiiloadVersion[0] = haxx[4]; - wiiloadVersion[1] = haxx[5]; + wiiloadVersion[0] = haxx[4]; + wiiloadVersion[1] = haxx[5]; net_read(connection, &infilesize, 4); - if (haxx[4] > 0 || haxx[5] > 4) { - net_read(connection, &uncfilesize, 4); // Compressed protocol, read another 4 bytes - } + if (haxx[4] > 0 || haxx[5] > 4) { + net_read(connection, &uncfilesize, 4); // Compressed protocol, read another 4 bytes + } waitforanswer = true; checkincomming = false; networkHalt = true; @@ -295,25 +298,25 @@ int CheckUpdate() { int revnumber = 0; int currentrev = atoi(GetRev()); - if (Settings.beta_upgrades) { - revnumber = CheckForBetaUpdate(); - } else { + if (Settings.beta_upgrades) { + revnumber = CheckForBetaUpdate(); + } else { #ifdef FULLCHANNEL - struct block file = downloadfile("http://www.techjawa.com/usbloadergx/wadrev.txt"); + struct block file = downloadfile("http://www.techjawa.com/usbloadergx/wadrev.txt"); #else - struct block file = downloadfile("http://www.techjawa.com/usbloadergx/rev.txt"); + struct block file = downloadfile("http://www.techjawa.com/usbloadergx/rev.txt"); #endif - char revtxt[10]; + char revtxt[10]; - u8 i; - if (file.data != NULL) { - for (i=0; i<9 || i < file.size; i++) - revtxt[i] = file.data[i]; - revtxt[i] = 0; - revnumber = atoi(revtxt); - free(file.data); - } - } + u8 i; + if (file.data != NULL) { + for (i=0; i<9 || i < file.size; i++) + revtxt[i] = file.data[i]; + revtxt[i] = 0; + revnumber = atoi(revtxt); + free(file.data); + } + } if (revnumber > currentrev) return revnumber; diff --git a/source/network/update.cpp b/source/network/update.cpp index b700033e..53b1fa70 100644 --- a/source/network/update.cpp +++ b/source/network/update.cpp @@ -1,31 +1,31 @@ -/*************************************************************************** -* Copyright (C) 2009 -* by Dimok -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any -* damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any -* purpose, including commercial applications, and to alter it and -* redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you -* must not claim that you wrote the original software. If you use -* this software in a product, an acknowledgment in the product -* documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and -* must not be misrepresented as being the original software. -* -* 3. This notice may not be removed or altered from any source -* distribution. -* -* update.cpp -* -* Update operations -* for Wii-Xplorer 2009 -***************************************************************************/ + /*************************************************************************** + * Copyright (C) 2009 + * by Dimok + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any + * damages arising from the use of this software. + * + * Permission is granted to anyone to use this software for any + * purpose, including commercial applications, and to alter it and + * redistribute it freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you + * must not claim that you wrote the original software. If you use + * this software in a product, an acknowledgment in the product + * documentation would be appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and + * must not be misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source + * distribution. + * + * update.cpp + * + * Update operations + * for Wii-Xplorer 2009 + ***************************************************************************/ #include #include #include @@ -37,23 +37,28 @@ /**************************************************************************** * Checking if an Update is available ***************************************************************************/ -int CheckForBetaUpdate() { +int CheckForBetaUpdate() +{ int revnumber = 0; URL_List URLs("http://code.google.com/p/usbloader-gui/downloads/list"); int urlcount = URLs.GetURLCount(); - for (int i = 0; i < urlcount; i++) { + for(int i = 0; i < urlcount; i++) + { char *tmp = URLs.GetURL(i); - if (tmp) { + if(tmp) + { char *fileext = strrchr(tmp, '.'); - if (fileext) { - if (strcasecmp(fileext, ".dol") == 0 || strcasecmp(fileext, ".wad") == 0) { + if(fileext) + { + if(strcasecmp(fileext, ".dol") == 0 || strcasecmp(fileext, ".wad") == 0) + { char *DownloadLink = (char *) malloc(strlen(tmp)+1); sprintf(DownloadLink, "%s", tmp); - int rev = 0; + int rev = 0; char revtxt[80]; char *filename = strrchr(DownloadLink, '/')+2; u8 n = 0; @@ -62,12 +67,12 @@ int CheckForBetaUpdate() { revtxt[n] = 0; rev = atoi(revtxt); - if (rev > revnumber) { - revnumber = rev; - } - if (DownloadLink) - free(DownloadLink); - DownloadLink = NULL; + if(rev > revnumber) { + revnumber = rev; + } + if(DownloadLink) + free(DownloadLink); + DownloadLink = NULL; } } } diff --git a/source/network/update.h b/source/network/update.h index 5ab60317..8283c8cc 100644 --- a/source/network/update.h +++ b/source/network/update.h @@ -1,34 +1,34 @@ -/*************************************************************************** -* Copyright (C) 2009 -* by Dimok -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any -* damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any -* purpose, including commercial applications, and to alter it and -* redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you -* must not claim that you wrote the original software. If you use -* this software in a product, an acknowledgment in the product -* documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and -* must not be misrepresented as being the original software. -* -* 3. This notice may not be removed or altered from any source -* distribution. -* -* update.h -* -* Update operations -* for Wii-Xplorer 2009 -***************************************************************************/ -#ifndef _UPDATEOPS_H_ + /*************************************************************************** + * Copyright (C) 2009 + * by Dimok + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any + * damages arising from the use of this software. + * + * Permission is granted to anyone to use this software for any + * purpose, including commercial applications, and to alter it and + * redistribute it freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you + * must not claim that you wrote the original software. If you use + * this software in a product, an acknowledgment in the product + * documentation would be appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and + * must not be misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source + * distribution. + * + * update.h + * + * Update operations + * for Wii-Xplorer 2009 + ***************************************************************************/ +#ifndef _UPDATEOPS_H_ #define _UPDATEOPS_H_ int CheckForBetaUpdate(); -#endif +#endif diff --git a/source/patches/dvd_broadway.c b/source/patches/dvd_broadway.c index 6e9f6043..0d012392 100644 --- a/source/patches/dvd_broadway.c +++ b/source/patches/dvd_broadway.c @@ -26,15 +26,15 @@ #include #include #include -#include - +#include + #include "dvd_broadway.h" - + #define DI_CMDCTX_CNT 4 - + #define DVD_DISKIDSIZE 0x20 #define DVD_DRVINFSIZE 0x20 - + #define IOCTL_DI_INQUIRY 0x12 #define IOCTL_DI_READID 0x70 #define IOCTL_DI_READ 0x71 @@ -58,22 +58,24 @@ #define IOCTL_DI_GETCRYPTMODE 0xF3 #define IOCTL_DI_SETDVDROMMODE 0xF4 #define IOCTL_DI_GETDVDROMMODE 0xF5 - + #define _SHIFTL(v, s, w) \ ((u32) (((u32)(v) & ((0x01 << (w)) - 1)) << (s))) #define _SHIFTR(v, s, w) \ ((u32)(((u32)(v) >> (s)) & ((0x01 << (w)) - 1))) - -struct dicommand { - u32 diReg[8]; + +struct dicommand +{ + u32 diReg[8]; }; - -struct dicontext { - lwp_node node; - dvdcallbacklow cb; - struct dicommand *cmd; + +struct dicontext +{ + lwp_node node; + dvdcallbacklow cb; + struct dicommand *cmd; }; - + static s32 __dvd_fd = -1; static u32 __dvd_spinupval = 1; static lwp_queue __di_contextq; @@ -88,500 +90,524 @@ static u32 __di_regvalcache[0x08] ATTRIBUTE_ALIGN(32); static u32 __di_lastticketerror[0x08] ATTRIBUTE_ALIGN(32); static ioctlv __di_iovector[0x08] ATTRIBUTE_ALIGN(32); static char __di_fs[] ATTRIBUTE_ALIGN(32) = "/dev/di"; - + extern u32 __IPC_ClntInit(); - -static __inline__ lwp_node* __lwp_queue_head(lwp_queue *queue) { - return (lwp_node*)queue; + +static __inline__ lwp_node* __lwp_queue_head(lwp_queue *queue) +{ + return (lwp_node*)queue; } - -static __inline__ lwp_node* __lwp_queue_tail(lwp_queue *queue) { - return (lwp_node*)&queue->perm_null; + +static __inline__ lwp_node* __lwp_queue_tail(lwp_queue *queue) +{ + return (lwp_node*)&queue->perm_null; } - - -static __inline__ void __lwp_queue_init_empty(lwp_queue *queue) { - queue->first = __lwp_queue_tail(queue); - queue->perm_null = NULL; - queue->last = __lwp_queue_head(queue); + + +static __inline__ void __lwp_queue_init_empty(lwp_queue *queue) +{ + queue->first = __lwp_queue_tail(queue); + queue->perm_null = NULL; + queue->last = __lwp_queue_head(queue); } - -static struct dicontext* __dvd_getcontext(dvdcallbacklow cb) { - struct dicontext *ctx; - - ctx = (struct dicontext*)__lwp_queue_get(&__di_contextq); - if (ctx!=NULL) ctx->cb = cb; - - return ctx; + +static struct dicontext* __dvd_getcontext(dvdcallbacklow cb) +{ + struct dicontext *ctx; + + ctx = (struct dicontext*)__lwp_queue_get(&__di_contextq); + if(ctx!=NULL) ctx->cb = cb; + + return ctx; } - -static s32 __dvd_iostransactionCB(s32 result,void *usrdata) { - struct dicontext *ctx = (struct dicontext*)usrdata; - - __dvd_reqinprogress = 0; - - if (ctx->cb!=NULL) { - __dvd_cbinprogress = 1; - if (result!=0) __dvd_readlength = 0; - ctx->cb(result); - __dvd_cbinprogress = 0; - } - __lwp_queue_append(&__di_contextq,&ctx->node); - - return 0; + +static s32 __dvd_iostransactionCB(s32 result,void *usrdata) +{ + struct dicontext *ctx = (struct dicontext*)usrdata; + + __dvd_reqinprogress = 0; + + if(ctx->cb!=NULL) { + __dvd_cbinprogress = 1; + if(result!=0) __dvd_readlength = 0; + ctx->cb(result); + __dvd_cbinprogress = 0; + } + __lwp_queue_append(&__di_contextq,&ctx->node); + + return 0; } - -static s32 __dvd_ioscoverregisterCB(s32 result,void *usrdata) { - struct dicontext *ctx = (struct dicontext*)usrdata; - - __dvd_reqinprogress = 0; - __di_regvalcache[1] = __di_regbuffer[0]; - - if (ctx->cb!=NULL) { - __dvd_cbinprogress = 1; - ctx->cb(result); - __dvd_cbinprogress = 0; - } - __lwp_queue_append(&__di_contextq,&ctx->node); - - return 0; + +static s32 __dvd_ioscoverregisterCB(s32 result,void *usrdata) +{ + struct dicontext *ctx = (struct dicontext*)usrdata; + + __dvd_reqinprogress = 0; + __di_regvalcache[1] = __di_regbuffer[0]; + + if(ctx->cb!=NULL) { + __dvd_cbinprogress = 1; + ctx->cb(result); + __dvd_cbinprogress = 0; + } + __lwp_queue_append(&__di_contextq,&ctx->node); + + return 0; } - -static s32 __dvd_ioscovercloseCB(s32 result,void *usrdata) { - struct dicontext *ctx = (struct dicontext*)usrdata; - - __dvd_reqinprogress = 0; - - if (ctx->cb!=NULL) { - __dvd_cbinprogress = 1; - ctx->cb(result); - __dvd_cbinprogress = 0; - } - __lwp_queue_append(&__di_contextq,&ctx->node); - - return 0; + +static s32 __dvd_ioscovercloseCB(s32 result,void *usrdata) +{ + struct dicontext *ctx = (struct dicontext*)usrdata; + + __dvd_reqinprogress = 0; + + if(ctx->cb!=NULL) { + __dvd_cbinprogress = 1; + ctx->cb(result); + __dvd_cbinprogress = 0; + } + __lwp_queue_append(&__di_contextq,&ctx->node); + + return 0; } - -s32 bwDVD_LowInit() { - s32 i,ret = 0; - u32 ipclo,ipchi; - lwp_queue inactives; - struct dicontext *ctx; - - if (__dvd_lowinitcalled==0) { - ret = __IPC_ClntInit(); - if (ret<0) return ret; - - ipclo = (((u32)IPC_GetBufferLo()+0x1f)&~0x1f); - ipchi = (u32)IPC_GetBufferHi(); - if (ipchi>=(ipclo+(sizeof(struct dicommand)*DI_CMDCTX_CNT))) { - __di_commands = (struct dicommand*)ipclo; - IPC_SetBufferLo((void*)(ipclo+(sizeof(struct dicommand)*DI_CMDCTX_CNT))); - - memset(__di_commands,0,(sizeof(struct dicommand)*DI_CMDCTX_CNT)); - - i = 0; - __lwp_queue_init_empty(&__di_contextq); - __lwp_queue_initialize(&inactives,__di_contexts,DI_CMDCTX_CNT,sizeof(struct dicontext)); - while ((ctx=(struct dicontext*)__lwp_queue_get(&inactives))!=NULL) { - ctx->cmd = &__di_commands[i]; - ctx->cb = NULL; - __lwp_queue_append(&__di_contextq,&ctx->node); - - i++; - } - } - - ret = IOS_Open(__di_fs,0); - if (ret<0) return ret; - - __dvd_fd = ret; + +s32 bwDVD_LowInit() +{ + s32 i,ret = 0; + u32 ipclo,ipchi; + lwp_queue inactives; + struct dicontext *ctx; + + if(__dvd_lowinitcalled==0) { + ret = __IPC_ClntInit(); + if(ret<0) return ret; + + ipclo = (((u32)IPC_GetBufferLo()+0x1f)&~0x1f); + ipchi = (u32)IPC_GetBufferHi(); + if(ipchi>=(ipclo+(sizeof(struct dicommand)*DI_CMDCTX_CNT))) { + __di_commands = (struct dicommand*)ipclo; + IPC_SetBufferLo((void*)(ipclo+(sizeof(struct dicommand)*DI_CMDCTX_CNT))); + + memset(__di_commands,0,(sizeof(struct dicommand)*DI_CMDCTX_CNT)); + + i = 0; + __lwp_queue_init_empty(&__di_contextq); + __lwp_queue_initialize(&inactives,__di_contexts,DI_CMDCTX_CNT,sizeof(struct dicontext)); + while((ctx=(struct dicontext*)__lwp_queue_get(&inactives))!=NULL) { + ctx->cmd = &__di_commands[i]; + ctx->cb = NULL; + __lwp_queue_append(&__di_contextq,&ctx->node); + + i++; + } + } + + ret = IOS_Open(__di_fs,0); + if(ret<0) return ret; + + __dvd_fd = ret; // __dvd_lowinitcalled = 1; - - // printf("DVD_LowInit(%d)\n",ret); - } - return 0; + + // printf("DVD_LowInit(%d)\n",ret); + } + return 0; } - -s32 bwDVD_LowInquiry(dvddrvinfo *info,dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_INQUIRY<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_INQUIRY,cmd->diReg,sizeof(struct dicommand),info,DVD_DRVINFSIZE,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowInquiry(dvddrvinfo *info,dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_INQUIRY<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_INQUIRY,cmd->diReg,sizeof(struct dicommand),info,DVD_DRVINFSIZE,__dvd_iostransactionCB,ctx); + + return ret; } - -s32 bwDVD_LowReadID(dvddiskid *diskID,dvdcallbacklow cb) { - s32 ret = 0; - struct dicontext *ctx; - struct dicommand *cmd; - + +s32 bwDVD_LowReadID(dvddiskid *diskID,dvdcallbacklow cb) +{ + s32 ret = 0; + struct dicontext *ctx; + struct dicommand *cmd; + // printf("DVD_LowReadID()\n"); - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_READID<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READID,cmd->diReg,sizeof(struct dicommand),diskID,DVD_DISKIDSIZE,__dvd_iostransactionCB,ctx); - + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_READID<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READID,cmd->diReg,sizeof(struct dicommand),diskID,DVD_DISKIDSIZE,__dvd_iostransactionCB,ctx); + // printf("DVD_LowReadID(%d)\n",ret); - return ret; + return ret; } - -s32 bwDVD_LowRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - if (buf==NULL || ((u32)buf%32)!=0) return -1; - - __dvd_reqinprogress = 1; - __dvd_readlength = len; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_READ<<24); - cmd->diReg[1] = len; - cmd->diReg[2] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READ,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + if(buf==NULL || ((u32)buf%32)!=0) return -1; + + __dvd_reqinprogress = 1; + __dvd_readlength = len; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_READ<<24); + cmd->diReg[1] = len; + cmd->diReg[2] = offset; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READ,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); + + return ret; } // never got this function working, probably removed from wii -s32 bwDVD_LowReadVideo(void *buf,u32 len,u32 offset,dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - __dvd_readlength = len; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_READ_DVDVIDEO<<24); - cmd->diReg[1] = len; - cmd->diReg[2] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READ_DVDVIDEO,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); - - return ret; +s32 bwDVD_LowReadVideo(void *buf,u32 len,u32 offset,dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + __dvd_readlength = len; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_READ_DVDVIDEO<<24); + cmd->diReg[1] = len; + cmd->diReg[2] = offset; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READ_DVDVIDEO,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); + + return ret; } + - -s32 bwDVD_LowStopLaser(dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_STOPLASER<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_STOPLASER,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; +s32 bwDVD_LowStopLaser(dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_STOPLASER<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_STOPLASER,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); + + return ret; } // never got this function working, probably removed from wii -s32 bwDVD_EnableVideo(dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_ENABLE_DVD<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_ENABLE_DVD,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; +s32 bwDVD_EnableVideo(dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_ENABLE_DVD<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_ENABLE_DVD,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); + + return ret; } - -s32 bwDVD_LowSeek(u32 offset,dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_SEEK<<24); - cmd->diReg[1] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SEEK,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowSeek(u32 offset,dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_SEEK<<24); + cmd->diReg[1] = offset; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SEEK,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); + + return ret; } - -s32 bwDVD_LowOffset(u64 offset,dvdcallbacklow cb) { - s32 ret; - //u32 *off = (u32*)(void*)(&offset); - union { u64 off64; - u32 off32[2]; - } off; - off.off64 = offset; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_OFFSET<<24); - cmd->diReg[1] = 0; - if (off.off32[0]) cmd->diReg[1] = 1; - cmd->diReg[2] = off.off32[1]; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_OFFSET,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowOffset(u64 offset,dvdcallbacklow cb) +{ + s32 ret; + //u32 *off = (u32*)(void*)(&offset); + union { u64 off64; u32 off32[2]; } off;off.off64 = offset; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_OFFSET<<24); + cmd->diReg[1] = 0; + if(off.off32[0]) cmd->diReg[1] = 1; + cmd->diReg[2] = off.off32[1]; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_OFFSET,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); + + return ret; } - -s32 bwDVD_LowPrepareCoverRegister(dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_COVER<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_COVER,cmd->diReg,sizeof(struct dicommand),__di_regbuffer,0x20,__dvd_ioscoverregisterCB,ctx); - - return ret; + +s32 bwDVD_LowPrepareCoverRegister(dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_COVER<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_COVER,cmd->diReg,sizeof(struct dicommand),__di_regbuffer,0x20,__dvd_ioscoverregisterCB,ctx); + + return ret; } - -s32 bwDVD_LowOpenPartition(u32 offset,void *eticket,u32 certin_len,void *certificate_in,void *certificate_out,dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - if (eticket!=NULL && ((u32)eticket%32)!=0) return -1; - if (certificate_in!=NULL && ((u32)certificate_in%32)!=0) return -1; - if (certificate_out!=NULL && ((u32)certificate_out%32)!=0) return -1; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_OPENPART<<24); - cmd->diReg[1] = offset; - - __di_iovector[0].data = cmd; - __di_iovector[0].len = sizeof(struct dicommand); - - __di_iovector[1].data = eticket; - if (eticket==NULL) __di_iovector[1].len = 0; - else __di_iovector[1].len = 676; - - __di_iovector[2].data = certificate_in; - if (certificate_in==NULL) __di_iovector[2].len = 0; - else __di_iovector[2].len = certin_len; - - __di_iovector[3].data = certificate_out; - __di_iovector[3].len = 18916; - __di_iovector[4].data = __di_lastticketerror; - __di_iovector[4].len = 0x20; - ret = IOS_IoctlvAsync(__dvd_fd,IOCTL_DI_OPENPART,3,2,__di_iovector,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowOpenPartition(u32 offset,void *eticket,u32 certin_len,void *certificate_in,void *certificate_out,dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + if(eticket!=NULL && ((u32)eticket%32)!=0) return -1; + if(certificate_in!=NULL && ((u32)certificate_in%32)!=0) return -1; + if(certificate_out!=NULL && ((u32)certificate_out%32)!=0) return -1; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_OPENPART<<24); + cmd->diReg[1] = offset; + + __di_iovector[0].data = cmd; + __di_iovector[0].len = sizeof(struct dicommand); + + __di_iovector[1].data = eticket; + if(eticket==NULL) __di_iovector[1].len = 0; + else __di_iovector[1].len = 676; + + __di_iovector[2].data = certificate_in; + if(certificate_in==NULL) __di_iovector[2].len = 0; + else __di_iovector[2].len = certin_len; + + __di_iovector[3].data = certificate_out; + __di_iovector[3].len = 18916; + __di_iovector[4].data = __di_lastticketerror; + __di_iovector[4].len = 0x20; + ret = IOS_IoctlvAsync(__dvd_fd,IOCTL_DI_OPENPART,3,2,__di_iovector,__dvd_iostransactionCB,ctx); + + return ret; } - -s32 bwDVD_LowClosePartition(dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_CLOSEPART<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_CLOSEPART,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowClosePartition(dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_CLOSEPART<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_CLOSEPART,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); + + return ret; } - -s32 bwDVD_LowUnencryptedRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - __dvd_readlength = len; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_UNENCREAD<<24); - cmd->diReg[1] = len; - cmd->diReg[2] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_UNENCREAD,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowUnencryptedRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + __dvd_readlength = len; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_UNENCREAD<<24); + cmd->diReg[1] = len; + cmd->diReg[2] = offset; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_UNENCREAD,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); + + return ret; } - -s32 bwDVD_LowWaitCoverClose(dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_WAITCVRCLOSE<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_WAITCVRCLOSE,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_ioscovercloseCB,ctx); - - return ret; + +s32 bwDVD_LowWaitCoverClose(dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_WAITCVRCLOSE<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_WAITCVRCLOSE,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_ioscovercloseCB,ctx); + + return ret; } - -s32 bwDVD_LowResetNotify() { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - if (__dvd_cbinprogress==1) return -1; - - ctx = __dvd_getcontext(NULL); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_RESETNOTIFY<<24); - ret = IOS_Ioctl(__dvd_fd,IOCTL_DI_RESETNOTIFY,cmd->diReg,sizeof(struct dicommand),NULL,0); - - return ret; + +s32 bwDVD_LowResetNotify() +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + if(__dvd_cbinprogress==1) return -1; + + ctx = __dvd_getcontext(NULL); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_RESETNOTIFY<<24); + ret = IOS_Ioctl(__dvd_fd,IOCTL_DI_RESETNOTIFY,cmd->diReg,sizeof(struct dicommand),NULL,0); + + return ret; } - -s32 bwDVD_LowReset(dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - + +s32 bwDVD_LowReset(dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + // printf("DVD_LowReset()\n"); - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_RESET<<24); - cmd->diReg[1] = __dvd_spinupval; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_RESET,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); - + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_RESET<<24); + cmd->diReg[1] = __dvd_spinupval; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_RESET,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); + // printf("DVD_LowReset(%d)\n",ret); - return ret; + return ret; } - -s32 bwDVD_LowStopMotor(u8 stop1,u8 stop2,dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_STOPMOTOR<<24); - cmd->diReg[1] = (stop1<<24); - cmd->diReg[2] = (stop2<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_STOPMOTOR,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; - + +s32 bwDVD_LowStopMotor(u8 stop1,u8 stop2,dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_STOPMOTOR<<24); + cmd->diReg[1] = (stop1<<24); + cmd->diReg[2] = (stop2<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_STOPMOTOR,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); + + return ret; + } - -s32 bwDVD_LowRequestError(dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_REQERROR<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_REQERROR,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; + +s32 bwDVD_LowRequestError(dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_REQERROR<<24); + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_REQERROR,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); + + return ret; } -s32 bwDVD_SetDecryption(s32 mode, dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_SETCRYPTMODE<<24); - cmd->diReg[1] = mode; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SETCRYPTMODE,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; - +s32 bwDVD_SetDecryption(s32 mode, dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_SETCRYPTMODE<<24); + cmd->diReg[1] = mode; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SETCRYPTMODE,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); + + return ret; + } -s32 bwDVD_SetOffset(u32 offset, dvdcallbacklow cb) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if (ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_SETOFFBASE<<24); - cmd->diReg[1] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SETOFFBASE,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; - +s32 bwDVD_SetOffset(u32 offset, dvdcallbacklow cb) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext(cb); + if(ctx==NULL) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = (IOCTL_DI_SETOFFBASE<<24); + cmd->diReg[1] = offset; + ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SETOFFBASE,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); + + return ret; + } diff --git a/source/patches/dvd_broadway.h b/source/patches/dvd_broadway.h index 47072b61..e36361d2 100644 --- a/source/patches/dvd_broadway.h +++ b/source/patches/dvd_broadway.h @@ -21,33 +21,33 @@ #ifndef __DVD_BROADWAY_H__ #define __DVD_BROADWAY_H__ - + #include #include #include + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +typedef void (*dvdcallbacklow)(s32 result); + +s32 bwDVD_LowInit(); +s32 bwDVD_LowInquiry(dvddrvinfo *info,dvdcallbacklow cb); +s32 bwDVD_LowReadID(dvddiskid *diskID,dvdcallbacklow cb); +s32 bwDVD_LowClosePartition(dvdcallbacklow cb); +s32 bwDVD_LowOpenPartition(u32 offset,void *eticket,u32 certin_len,void *certificate_in,void *certificate_out,dvdcallbacklow cb); +s32 bwDVD_LowUnencryptedRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb); +s32 bwDVD_LowReset(dvdcallbacklow cb); +s32 bwDVD_LowWaitCoverClose(dvdcallbacklow cb); +s32 bwDVD_LowRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb); +s32 bwDVD_EnableVideo(dvdcallbacklow cb); +s32 bwDVD_LowReadVideo(void *buf,u32 len,u32 offset,dvdcallbacklow cb); +s32 bwDVD_SetDecryption(s32 mode, dvdcallbacklow cb); +s32 bwDVD_SetOffset(u32 offset, dvdcallbacklow cb); #ifdef __cplusplus -extern "C" { + } #endif /* __cplusplus */ - - typedef void (*dvdcallbacklow)(s32 result); - - s32 bwDVD_LowInit(); - s32 bwDVD_LowInquiry(dvddrvinfo *info,dvdcallbacklow cb); - s32 bwDVD_LowReadID(dvddiskid *diskID,dvdcallbacklow cb); - s32 bwDVD_LowClosePartition(dvdcallbacklow cb); - s32 bwDVD_LowOpenPartition(u32 offset,void *eticket,u32 certin_len,void *certificate_in,void *certificate_out,dvdcallbacklow cb); - s32 bwDVD_LowUnencryptedRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb); - s32 bwDVD_LowReset(dvdcallbacklow cb); - s32 bwDVD_LowWaitCoverClose(dvdcallbacklow cb); - s32 bwDVD_LowRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb); - s32 bwDVD_EnableVideo(dvdcallbacklow cb); - s32 bwDVD_LowReadVideo(void *buf,u32 len,u32 offset,dvdcallbacklow cb); - s32 bwDVD_SetDecryption(s32 mode, dvdcallbacklow cb); - s32 bwDVD_SetOffset(u32 offset, dvdcallbacklow cb); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - + #endif diff --git a/source/patches/fst.c b/source/patches/fst.c index feea14e8..8da88968 100644 --- a/source/patches/fst.c +++ b/source/patches/fst.c @@ -45,130 +45,133 @@ extern struct SSettings Settings; // Pre-allocate the buffer size for ocarina codes u8 filebuff[MAX_GCT_SIZE]; -u32 do_sd_code(char *filename) { - gprintf("\ndo_sd_code(%s)",filename); - printf("\ndo_sd_code(%s)",filename); +u32 do_sd_code(char *filename) +{ +gprintf("\ndo_sd_code(%s)",filename); +printf("\ndo_sd_code(%s)",filename); - FILE *fp; - //u8 *filebuff; - u32 filesize; - u32 ret; - char filepath[150]; + FILE *fp; + //u8 *filebuff; + u32 filesize; + u32 ret; + char filepath[150]; //SDCard_Init(); - //USBDevice_Init(); + //USBDevice_Init(); - sprintf(filepath, "%s%s", Settings.Cheatcodespath, filename); - filepath[strlen(Settings.Cheatcodespath)+6] = 0x2E; - filepath[strlen(Settings.Cheatcodespath)+7] = 0x67; - filepath[strlen(Settings.Cheatcodespath)+8] = 0x63; - filepath[strlen(Settings.Cheatcodespath)+9] = 0x74; - filepath[strlen(Settings.Cheatcodespath)+10] = 0; + sprintf(filepath, "%s%s", Settings.Cheatcodespath, filename); + filepath[strlen(Settings.Cheatcodespath)+6] = 0x2E; + filepath[strlen(Settings.Cheatcodespath)+7] = 0x67; + filepath[strlen(Settings.Cheatcodespath)+8] = 0x63; + filepath[strlen(Settings.Cheatcodespath)+9] = 0x74; + filepath[strlen(Settings.Cheatcodespath)+10] = 0; - fp = fopen(filepath, "rb"); - if (!fp) { + fp = fopen(filepath, "rb"); + if (!fp) { USBDevice_deInit(); SDCard_deInit(); - gprintf("\n\tcan't open %s",filepath); - printf("\n\tcan't open %s",filepath); - sleep(10); - return 0; - } + gprintf("\n\tcan't open %s",filepath); + printf("\n\tcan't open %s",filepath); + sleep(10); + return 0; + } - fseek(fp, 0, SEEK_END); - filesize = ftell(fp); - if (filesize <= 16 || filesize>MAX_GCT_SIZE) { - fclose(fp); - sleep(2); + fseek(fp, 0, SEEK_END); + filesize = ftell(fp); + if(filesize <= 16 || filesize>MAX_GCT_SIZE){ + fclose(fp); + sleep(2); USBDevice_deInit(); SDCard_deInit(); - gprintf("\n\tError. size = %d",filesize); - printf("\n\tError. size = %d",filesize); - sleep(10); - return 0; - } - fseek(fp, 0, SEEK_SET); + gprintf("\n\tError. size = %d",filesize); + printf("\n\tError. size = %d",filesize); + sleep(10); + return 0; + } + fseek(fp, 0, SEEK_SET); + - - ret = fread(&filebuff, 1, filesize, fp); - if (ret != filesize) { - fclose(fp); + ret = fread(&filebuff, 1, filesize, fp); + if(ret != filesize){ + fclose(fp); USBDevice_deInit(); SDCard_deInit(); - gprintf("\n\tError. ret != size"); - printf("\n\tError. ret != size"); - sleep(10); - return 0; - } - fclose(fp); - //USBDevice_deInit(); + gprintf("\n\tError. ret != size"); + printf("\n\tError. ret != size"); + sleep(10); + return 0; + } + fclose(fp); + //USBDevice_deInit(); //SDCard_deInit(); memcpy((void*)0x800027E8, &filebuff,filesize); *(vu8*)0x80001807 = 0x01; - //gprintf("\n\tDe-init SD & USB"); + //gprintf("\n\tDe-init SD & USB"); + + + gprintf("\n\tDone"); + printf("...Done"); - - gprintf("\n\tDone"); - printf("...Done"); - - return 1; + return 1; } -u32 do_bca_code(u8 *gameid) { - if (IOS_GetVersion() == 222 || IOS_GetVersion() == 223) { - FILE *fp; - u32 filesize; - char filepath[150]; - memset(filepath, 0, 150); - u8 bcaCode[64] ATTRIBUTE_ALIGN(32); +u32 do_bca_code(u8 *gameid) +{ + if (IOS_GetVersion() == 222 || IOS_GetVersion() == 223) + { + FILE *fp; + u32 filesize; + char filepath[150]; + memset(filepath, 0, 150); + u8 bcaCode[64] ATTRIBUTE_ALIGN(32); - sprintf(filepath, "%s%6s", Settings.BcaCodepath, gameid); - filepath[strlen(Settings.BcaCodepath)+6] = '.'; - filepath[strlen(Settings.BcaCodepath)+7] = 'b'; - filepath[strlen(Settings.BcaCodepath)+8] = 'c'; - filepath[strlen(Settings.BcaCodepath)+9] = 'a'; + sprintf(filepath, "%s%6s", Settings.BcaCodepath, gameid); + filepath[strlen(Settings.BcaCodepath)+6] = '.'; + filepath[strlen(Settings.BcaCodepath)+7] = 'b'; + filepath[strlen(Settings.BcaCodepath)+8] = 'c'; + filepath[strlen(Settings.BcaCodepath)+9] = 'a'; - fp = fopen(filepath, "rb"); - if (!fp) { - memset(filepath, 0, 150); - sprintf(filepath, "%s%3s", Settings.BcaCodepath, gameid + 1); - filepath[strlen(Settings.BcaCodepath)+3] = '.'; - filepath[strlen(Settings.BcaCodepath)+4] = 'b'; - filepath[strlen(Settings.BcaCodepath)+5] = 'c'; - filepath[strlen(Settings.BcaCodepath)+6] = 'a'; - fp = fopen(filepath, "rb"); + fp = fopen(filepath, "rb"); + if (!fp) { + memset(filepath, 0, 150); + sprintf(filepath, "%s%3s", Settings.BcaCodepath, gameid + 1); + filepath[strlen(Settings.BcaCodepath)+3] = '.'; + filepath[strlen(Settings.BcaCodepath)+4] = 'b'; + filepath[strlen(Settings.BcaCodepath)+5] = 'c'; + filepath[strlen(Settings.BcaCodepath)+6] = 'a'; + fp = fopen(filepath, "rb"); + + if (!fp) { + // Set default bcaCode + memset(bcaCode, 0, 64); + bcaCode[0x33] = 1; + } + } - if (!fp) { - // Set default bcaCode - memset(bcaCode, 0, 64); - bcaCode[0x33] = 1; - } - } + if (fp) { + u32 ret = 0; - if (fp) { - u32 ret = 0; + fseek(fp, 0, SEEK_END); + filesize = ftell(fp); + + if (filesize == 64) { + fseek(fp, 0, SEEK_SET); + ret = fread(bcaCode, 1, 64, fp); + } + fclose(fp); - fseek(fp, 0, SEEK_END); - filesize = ftell(fp); - - if (filesize == 64) { - fseek(fp, 0, SEEK_SET); - ret = fread(bcaCode, 1, 64, fp); - } - fclose(fp); - - if (ret != 64) { - // Set default bcaCode - memset(bcaCode, 0, 64); - bcaCode[0x33] = 1; - } - } - - mload_seek(*((u32 *) (dip_plugin+15*4)), SEEK_SET); // offset 15 (bca_data area) - mload_write(bcaCode, 64); - mload_close(); - } - return 0; + if (ret != 64) { + // Set default bcaCode + memset(bcaCode, 0, 64); + bcaCode[0x33] = 1; + } + } + + mload_seek(*((u32 *) (dip_plugin+15*4)), SEEK_SET); // offset 15 (bca_data area) + mload_write(bcaCode, 64); + mload_close(); + } + return 0; } diff --git a/source/patches/fst.h b/source/patches/fst.h index 40ecfb6d..254a6d2a 100644 --- a/source/patches/fst.h +++ b/source/patches/fst.h @@ -23,14 +23,15 @@ #define __FST_H__ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #define MAX_GCT_SIZE 2056 //u32 do_fst(u32 fstlocation); - u32 do_sd_code(char *filename); - u32 do_bca_code(u8 *gameid); +u32 do_sd_code(char *filename); +u32 do_bca_code(u8 *gameid); #ifdef __cplusplus } diff --git a/source/patches/fwrite_patch.h b/source/patches/fwrite_patch.h index bd47ce44..54fedcc4 100644 --- a/source/patches/fwrite_patch.h +++ b/source/patches/fwrite_patch.h @@ -1,15 +1,15 @@ unsigned char fwrite_patch_bin[] = { - 0x7c, 0x84, 0x29, 0xd6, 0x39, 0x40, 0x00, 0x00, 0x94, 0x21, 0xff, 0xf0, - 0x93, 0xe1, 0x00, 0x0c, 0x7f, 0x8a, 0x20, 0x00, 0x40, 0x9c, 0x00, 0x64, - 0x3d, 0x00, 0xcd, 0x00, 0x3d, 0x60, 0xcd, 0x00, 0x3d, 0x20, 0xcd, 0x00, - 0x61, 0x08, 0x68, 0x14, 0x61, 0x6b, 0x68, 0x24, 0x61, 0x29, 0x68, 0x20, - 0x39, 0x80, 0x00, 0xd0, 0x38, 0xc0, 0x00, 0x19, 0x38, 0xe0, 0x00, 0x00, - 0x91, 0x88, 0x00, 0x00, 0x7c, 0x03, 0x50, 0xae, 0x54, 0x00, 0xa0, 0x16, - 0x64, 0x00, 0xb0, 0x00, 0x90, 0x0b, 0x00, 0x00, 0x90, 0xc9, 0x00, 0x00, - 0x80, 0x09, 0x00, 0x00, 0x70, 0x1f, 0x00, 0x01, 0x40, 0x82, 0xff, 0xf8, - 0x80, 0x0b, 0x00, 0x00, 0x90, 0xe8, 0x00, 0x00, 0x54, 0x00, 0x37, 0xfe, - 0x7d, 0x4a, 0x02, 0x14, 0x7f, 0x8a, 0x20, 0x00, 0x41, 0x9c, 0xff, 0xc8, - 0x7c, 0xa3, 0x2b, 0x78, 0x83, 0xe1, 0x00, 0x0c, 0x38, 0x21, 0x00, 0x10, - 0x4e, 0x80, 0x00, 0x20 + 0x7c, 0x84, 0x29, 0xd6, 0x39, 0x40, 0x00, 0x00, 0x94, 0x21, 0xff, 0xf0, + 0x93, 0xe1, 0x00, 0x0c, 0x7f, 0x8a, 0x20, 0x00, 0x40, 0x9c, 0x00, 0x64, + 0x3d, 0x00, 0xcd, 0x00, 0x3d, 0x60, 0xcd, 0x00, 0x3d, 0x20, 0xcd, 0x00, + 0x61, 0x08, 0x68, 0x14, 0x61, 0x6b, 0x68, 0x24, 0x61, 0x29, 0x68, 0x20, + 0x39, 0x80, 0x00, 0xd0, 0x38, 0xc0, 0x00, 0x19, 0x38, 0xe0, 0x00, 0x00, + 0x91, 0x88, 0x00, 0x00, 0x7c, 0x03, 0x50, 0xae, 0x54, 0x00, 0xa0, 0x16, + 0x64, 0x00, 0xb0, 0x00, 0x90, 0x0b, 0x00, 0x00, 0x90, 0xc9, 0x00, 0x00, + 0x80, 0x09, 0x00, 0x00, 0x70, 0x1f, 0x00, 0x01, 0x40, 0x82, 0xff, 0xf8, + 0x80, 0x0b, 0x00, 0x00, 0x90, 0xe8, 0x00, 0x00, 0x54, 0x00, 0x37, 0xfe, + 0x7d, 0x4a, 0x02, 0x14, 0x7f, 0x8a, 0x20, 0x00, 0x41, 0x9c, 0xff, 0xc8, + 0x7c, 0xa3, 0x2b, 0x78, 0x83, 0xe1, 0x00, 0x0c, 0x38, 0x21, 0x00, 0x10, + 0x4e, 0x80, 0x00, 0x20 }; unsigned int fwrite_patch_bin_len = 136; diff --git a/source/patches/kenobiwii.h b/source/patches/kenobiwii.h index 0bf9557c..bc3d0ed1 100644 --- a/source/patches/kenobiwii.h +++ b/source/patches/kenobiwii.h @@ -4,261 +4,261 @@ Visit http://www.devkitpro.org */ const unsigned char kenobiwii[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x26, 0xa0, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x94, 0x21, 0xff, 0x58, 0x90, 0x01, 0x00, 0x08, - 0x7c, 0x08, 0x02, 0xa6, 0x90, 0x01, 0x00, 0xac, 0x7c, 0x00, 0x00, 0x26, 0x90, 0x01, 0x00, 0x0c, - 0x7c, 0x09, 0x02, 0xa6, 0x90, 0x01, 0x00, 0x10, 0x7c, 0x01, 0x02, 0xa6, 0x90, 0x01, 0x00, 0x14, - 0xbc, 0x61, 0x00, 0x18, 0x7f, 0x20, 0x00, 0xa6, 0x63, 0x3a, 0x20, 0x00, 0x73, 0x5a, 0xf9, 0xff, - 0x7f, 0x40, 0x01, 0x24, 0xd8, 0x41, 0x00, 0x98, 0xd8, 0x61, 0x00, 0xa0, 0x3f, 0xe0, 0x80, 0x00, - 0x3e, 0x80, 0xcc, 0x00, 0xa3, 0x94, 0x40, 0x10, 0x63, 0x95, 0x00, 0xff, 0xb2, 0xb4, 0x40, 0x10, - 0x48, 0x00, 0x06, 0xb1, 0x3a, 0xa0, 0x00, 0x00, 0x3a, 0xc0, 0x00, 0x19, 0x3a, 0xe0, 0x00, 0xd0, - 0x3f, 0x00, 0xcd, 0x00, 0x63, 0xf2, 0x26, 0xa0, 0x80, 0x01, 0x00, 0xac, 0x90, 0x12, 0x00, 0x04, - 0x92, 0xb8, 0x64, 0x3c, 0x48, 0x00, 0x04, 0x85, 0x41, 0x82, 0x05, 0xfc, 0x2c, 0x1d, 0x00, 0x04, - 0x40, 0x80, 0x00, 0x10, 0x2c, 0x1d, 0x00, 0x01, 0x41, 0x80, 0x05, 0xec, 0x48, 0x00, 0x03, 0xa8, - 0x41, 0x82, 0x05, 0x48, 0x2c, 0x1d, 0x00, 0x06, 0x41, 0x82, 0x00, 0x8c, 0x2c, 0x1d, 0x00, 0x07, - 0x41, 0x82, 0x03, 0x8c, 0x2c, 0x1d, 0x00, 0x08, 0x41, 0x82, 0x05, 0xd8, 0x2c, 0x1d, 0x00, 0x09, - 0x41, 0x82, 0x00, 0xa0, 0x2c, 0x1d, 0x00, 0x10, 0x41, 0x82, 0x00, 0x98, 0x2c, 0x1d, 0x00, 0x2f, - 0x41, 0x82, 0x00, 0x70, 0x2c, 0x1d, 0x00, 0x30, 0x41, 0x82, 0x00, 0x78, 0x2c, 0x1d, 0x00, 0x38, - 0x41, 0x82, 0x05, 0x80, 0x2c, 0x1d, 0x00, 0x40, 0x41, 0x82, 0x03, 0x9c, 0x2c, 0x1d, 0x00, 0x41, - 0x41, 0x82, 0x03, 0xb0, 0x2c, 0x1d, 0x00, 0x44, 0x41, 0x82, 0x00, 0x68, 0x2c, 0x1d, 0x00, 0x50, - 0x41, 0x82, 0x00, 0x20, 0x2c, 0x1d, 0x00, 0x60, 0x41, 0x82, 0x00, 0x24, 0x2c, 0x1d, 0x00, 0x89, - 0x41, 0x82, 0x00, 0x50, 0x2c, 0x1d, 0x00, 0x99, 0x41, 0x82, 0x05, 0x64, 0x48, 0x00, 0x05, 0x68, - 0x80, 0x72, 0x00, 0x00, 0x48, 0x00, 0x04, 0x81, 0x48, 0x00, 0x05, 0x5c, 0x48, 0x00, 0x05, 0xe5, - 0x48, 0x00, 0x05, 0x54, 0x38, 0x80, 0x00, 0x01, 0x90, 0x92, 0x00, 0x00, 0x48, 0x00, 0x05, 0x48, - 0x48, 0x00, 0x04, 0x61, 0x3a, 0x00, 0x00, 0xa0, 0x63, 0xec, 0x26, 0xc4, 0x48, 0x00, 0x03, 0x6c, - 0x38, 0x60, 0x01, 0x20, 0x63, 0xec, 0x26, 0xc4, 0x48, 0x00, 0x04, 0x21, 0x48, 0x00, 0x05, 0x28, - 0x2f, 0x1d, 0x00, 0x10, 0x2e, 0x9d, 0x00, 0x44, 0x63, 0xe4, 0x1a, 0xb4, 0x3c, 0x60, 0x80, 0x00, - 0x60, 0x63, 0x03, 0x00, 0x48, 0x00, 0x05, 0x65, 0x38, 0x63, 0x0a, 0x00, 0x48, 0x00, 0x05, 0x5d, - 0x38, 0x63, 0x06, 0x00, 0x48, 0x00, 0x05, 0x55, 0x63, 0xec, 0x26, 0xb4, 0x92, 0xac, 0x00, 0x00, - 0x92, 0xac, 0x00, 0x04, 0x92, 0xac, 0x00, 0x08, 0x63, 0xe4, 0x26, 0xc4, 0x81, 0x24, 0x00, 0x18, - 0x80, 0x72, 0x00, 0x00, 0x2c, 0x03, 0x00, 0x02, 0x40, 0x82, 0x00, 0x0c, 0x41, 0x96, 0x00, 0x0c, - 0x48, 0x00, 0x00, 0x20, 0x38, 0x60, 0x00, 0x00, 0x90, 0x6c, 0x00, 0x0c, 0x40, 0x82, 0x00, 0x14, - 0x40, 0x96, 0x00, 0x10, 0x61, 0x29, 0x04, 0x00, 0x91, 0x24, 0x00, 0x18, 0x48, 0x00, 0x02, 0x70, - 0x55, 0x29, 0x05, 0xa8, 0x91, 0x24, 0x00, 0x18, 0x41, 0x96, 0x04, 0xac, 0x41, 0x9a, 0x00, 0x08, - 0x39, 0x8c, 0x00, 0x04, 0x38, 0x60, 0x00, 0x04, 0x48, 0x00, 0x03, 0x61, 0x40, 0x99, 0x00, 0x10, - 0x39, 0x8c, 0x00, 0x04, 0x38, 0x60, 0x00, 0x04, 0x48, 0x00, 0x03, 0x51, 0x63, 0xe4, 0x26, 0xb4, - 0x80, 0x64, 0x00, 0x00, 0x80, 0x84, 0x00, 0x04, 0x7c, 0x72, 0xfb, 0xa6, 0x7c, 0x95, 0xfb, 0xa6, - 0x48, 0x00, 0x04, 0x74, 0x7c, 0x32, 0x43, 0xa6, 0x7c, 0x3a, 0x02, 0xa6, 0x7c, 0x73, 0x43, 0xa6, - 0x7c, 0x7b, 0x02, 0xa6, 0x54, 0x63, 0x05, 0xa8, 0x90, 0x60, 0x26, 0xdc, 0x54, 0x63, 0x06, 0x20, - 0x60, 0x63, 0x20, 0x00, 0x54, 0x63, 0x04, 0x5e, 0x7c, 0x7b, 0x03, 0xa6, 0x3c, 0x60, 0x80, 0x00, - 0x60, 0x63, 0x1a, 0xf4, 0x7c, 0x7a, 0x03, 0xa6, 0x4c, 0x00, 0x01, 0x2c, 0x7c, 0x00, 0x04, 0xac, - 0x4c, 0x00, 0x00, 0x64, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x26, 0xc4, 0x90, 0x23, 0x00, 0x14, - 0x7c, 0x61, 0x1b, 0x78, 0x7c, 0x73, 0x42, 0xa6, 0xbc, 0x41, 0x00, 0x24, 0x7c, 0x24, 0x0b, 0x78, - 0x7c, 0x32, 0x42, 0xa6, 0x90, 0x04, 0x00, 0x1c, 0x90, 0x24, 0x00, 0x20, 0x7c, 0x68, 0x02, 0xa6, - 0x90, 0x64, 0x00, 0x9c, 0x7c, 0x60, 0x00, 0x26, 0x90, 0x64, 0x00, 0x00, 0x7c, 0x61, 0x02, 0xa6, - 0x90, 0x64, 0x00, 0x04, 0x7c, 0x69, 0x02, 0xa6, 0x90, 0x64, 0x00, 0x08, 0x7c, 0x72, 0x02, 0xa6, - 0x90, 0x64, 0x00, 0x0c, 0x7c, 0x73, 0x02, 0xa6, 0x90, 0x64, 0x00, 0x10, 0x39, 0x20, 0x00, 0x00, - 0x7d, 0x32, 0xfb, 0xa6, 0x7d, 0x35, 0xfb, 0xa6, 0xd0, 0x04, 0x00, 0xa0, 0xd0, 0x24, 0x00, 0xa4, - 0xd0, 0x44, 0x00, 0xa8, 0xd0, 0x64, 0x00, 0xac, 0xd0, 0x84, 0x00, 0xb0, 0xd0, 0xa4, 0x00, 0xb4, - 0xd0, 0xc4, 0x00, 0xb8, 0xd0, 0xe4, 0x00, 0xbc, 0xd1, 0x04, 0x00, 0xc0, 0xd1, 0x24, 0x00, 0xc4, - 0xd1, 0x44, 0x00, 0xc8, 0xd1, 0x64, 0x00, 0xcc, 0xd1, 0x84, 0x00, 0xd0, 0xd1, 0xa4, 0x00, 0xd4, - 0xd1, 0xc4, 0x00, 0xd8, 0xd1, 0xe4, 0x00, 0xdc, 0xd2, 0x04, 0x00, 0xe0, 0xd2, 0x24, 0x00, 0xe4, - 0xd2, 0x44, 0x00, 0xe8, 0xd2, 0x64, 0x00, 0xec, 0xd2, 0x84, 0x00, 0xf0, 0xd2, 0xa4, 0x00, 0xf4, - 0xd2, 0xc4, 0x00, 0xf8, 0xd2, 0xe4, 0x00, 0xfc, 0xd3, 0x04, 0x01, 0x00, 0xd3, 0x24, 0x01, 0x04, - 0xd3, 0x44, 0x01, 0x08, 0xd3, 0x64, 0x01, 0x0c, 0xd3, 0x84, 0x01, 0x10, 0xd3, 0xa4, 0x01, 0x14, - 0xd3, 0xc4, 0x01, 0x18, 0xd3, 0xe4, 0x01, 0x1c, 0x3f, 0xe0, 0x80, 0x00, 0x63, 0xe5, 0x26, 0xb4, - 0x82, 0x05, 0x00, 0x00, 0x82, 0x25, 0x00, 0x04, 0x82, 0x65, 0x00, 0x0c, 0x2c, 0x13, 0x00, 0x00, - 0x41, 0x82, 0x00, 0x74, 0x2c, 0x13, 0x00, 0x02, 0x40, 0x82, 0x00, 0x18, 0x81, 0x24, 0x00, 0x14, - 0x39, 0x33, 0x00, 0x03, 0x91, 0x25, 0x00, 0x00, 0x91, 0x25, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x6c, - 0x7c, 0x10, 0x98, 0x00, 0x41, 0x82, 0x00, 0x38, 0x7c, 0x11, 0x98, 0x00, 0x41, 0x82, 0x00, 0x30, - 0x7d, 0x30, 0x8a, 0x14, 0x91, 0x25, 0x00, 0x0c, 0x82, 0x05, 0x00, 0x08, 0x2c, 0x10, 0x00, 0x00, - 0x41, 0x82, 0x00, 0x48, 0x80, 0x64, 0x00, 0x10, 0x7c, 0x10, 0x18, 0x00, 0x40, 0x82, 0x00, 0x10, - 0x3a, 0x00, 0x00, 0x00, 0x92, 0x05, 0x00, 0x08, 0x48, 0x00, 0x00, 0x30, 0x3a, 0x20, 0x00, 0x00, - 0x92, 0x25, 0x00, 0x0c, 0x81, 0x24, 0x00, 0x18, 0x61, 0x29, 0x04, 0x00, 0x91, 0x24, 0x00, 0x18, - 0x48, 0x00, 0x00, 0x30, 0x7e, 0x12, 0xfb, 0xa6, 0x7e, 0x35, 0xfb, 0xa6, 0x39, 0x20, 0x00, 0x01, - 0x91, 0x25, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x1c, 0x38, 0xa0, 0x00, 0x02, 0x63, 0xe4, 0x26, 0xa0, - 0x90, 0xa4, 0x00, 0x00, 0x38, 0x60, 0x00, 0x11, 0x48, 0x00, 0x01, 0xbd, 0x4b, 0xff, 0xfc, 0x1d, - 0x7c, 0x20, 0x00, 0xa6, 0x54, 0x21, 0x07, 0xfa, 0x54, 0x21, 0x04, 0x5e, 0x7c, 0x20, 0x01, 0x24, - 0x63, 0xe1, 0x26, 0xc4, 0x80, 0x61, 0x00, 0x00, 0x7c, 0x6f, 0xf1, 0x20, 0x80, 0x61, 0x00, 0x14, - 0x7c, 0x7a, 0x03, 0xa6, 0x80, 0x61, 0x00, 0x18, 0x7c, 0x7b, 0x03, 0xa6, 0x80, 0x61, 0x00, 0x9c, - 0x7c, 0x68, 0x03, 0xa6, 0xb8, 0x41, 0x00, 0x24, 0x80, 0x01, 0x00, 0x1c, 0x80, 0x21, 0x00, 0x20, - 0x4c, 0x00, 0x01, 0x2c, 0x7c, 0x00, 0x04, 0xac, 0x4c, 0x00, 0x00, 0x64, 0x92, 0xb2, 0x00, 0x00, - 0x48, 0x00, 0x02, 0x50, 0x2e, 0x9d, 0x00, 0x02, 0x38, 0x60, 0x00, 0x08, 0x63, 0xec, 0x26, 0xa8, - 0x48, 0x00, 0x00, 0xf9, 0x80, 0xac, 0x00, 0x00, 0x80, 0x6c, 0x00, 0x04, 0x98, 0x65, 0x00, 0x00, - 0x41, 0x94, 0x00, 0x10, 0xb0, 0x65, 0x00, 0x00, 0x41, 0x96, 0x00, 0x08, 0x90, 0x65, 0x00, 0x00, - 0x7c, 0x00, 0x28, 0xac, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x2f, 0xac, 0x4c, 0x00, 0x01, 0x2c, - 0x48, 0x00, 0x02, 0x04, 0x48, 0x00, 0x01, 0x1d, 0x38, 0x60, 0x00, 0x04, 0x63, 0xec, 0x26, 0xa8, - 0x48, 0x00, 0x00, 0xb9, 0x82, 0x0c, 0x00, 0x00, 0x63, 0xec, 0x27, 0xe8, 0x48, 0x00, 0x00, 0x1c, - 0x48, 0x00, 0x01, 0x01, 0x38, 0x60, 0x00, 0x08, 0x63, 0xec, 0x26, 0xa8, 0x48, 0x00, 0x00, 0x9d, - 0x82, 0x0c, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, 0x63, 0xfb, 0x26, 0xb0, 0x3a, 0x20, 0x0f, 0x80, - 0x48, 0x00, 0x02, 0x3d, 0x41, 0x82, 0x00, 0x20, 0x7e, 0x23, 0x8b, 0x78, 0x48, 0x00, 0x00, 0x7d, - 0x48, 0x00, 0x00, 0xd1, 0x41, 0x82, 0xff, 0xfc, 0x7d, 0x8c, 0x72, 0x14, 0x35, 0x6b, 0xff, 0xff, - 0x41, 0x81, 0xff, 0xe8, 0x80, 0x7b, 0x00, 0x00, 0x2c, 0x03, 0x00, 0x00, 0x41, 0x82, 0x00, 0x08, - 0x48, 0x00, 0x00, 0x59, 0x7c, 0x00, 0x60, 0xac, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x67, 0xac, - 0x4c, 0x00, 0x01, 0x2c, 0x48, 0x00, 0x01, 0x80, 0x7f, 0xc8, 0x02, 0xa6, 0x3c, 0x60, 0xa0, 0x00, - 0x48, 0x00, 0x00, 0x15, 0x76, 0x03, 0x08, 0x00, 0x56, 0x1d, 0x86, 0x3e, 0x7f, 0xc8, 0x03, 0xa6, - 0x4e, 0x80, 0x00, 0x20, 0x92, 0xf8, 0x68, 0x14, 0x90, 0x78, 0x68, 0x24, 0x92, 0xd8, 0x68, 0x20, - 0x80, 0xb8, 0x68, 0x20, 0x70, 0xa5, 0x00, 0x01, 0x40, 0x82, 0xff, 0xf8, 0x82, 0x18, 0x68, 0x24, - 0x90, 0xb8, 0x68, 0x14, 0x4e, 0x80, 0x00, 0x20, 0x7d, 0x48, 0x02, 0xa6, 0x7c, 0x69, 0x03, 0xa6, - 0x39, 0xc0, 0x00, 0x00, 0x48, 0x00, 0x00, 0x79, 0x48, 0x00, 0x00, 0x75, 0x4b, 0xff, 0xff, 0xad, - 0x41, 0x82, 0xff, 0xf4, 0x7f, 0xae, 0x61, 0xae, 0x39, 0xce, 0x00, 0x01, 0x42, 0x00, 0xff, 0xe8, - 0x7d, 0x48, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x7d, 0x48, 0x02, 0xa6, 0x7c, 0x69, 0x03, 0xa6, - 0x39, 0xc0, 0x00, 0x00, 0x7c, 0x6c, 0x70, 0xae, 0x48, 0x00, 0x00, 0x1d, 0x41, 0x82, 0xff, 0xf8, - 0x39, 0xce, 0x00, 0x01, 0x42, 0x00, 0xff, 0xf0, 0x7d, 0x48, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, - 0x38, 0x60, 0x00, 0xaa, 0x7f, 0xc8, 0x02, 0xa6, 0x54, 0x63, 0xa0, 0x16, 0x64, 0x63, 0xb0, 0x00, - 0x3a, 0xc0, 0x00, 0x19, 0x3a, 0xe0, 0x00, 0xd0, 0x3f, 0x00, 0xcd, 0x00, 0x4b, 0xff, 0xff, 0x69, - 0x56, 0x03, 0x37, 0xff, 0x7f, 0xc8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x7f, 0xc8, 0x02, 0xa6, - 0x3c, 0x60, 0xd0, 0x00, 0x4b, 0xff, 0xff, 0x51, 0x56, 0x03, 0x37, 0xff, 0x41, 0x82, 0xff, 0xf4, - 0x7f, 0xc8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x4b, 0xff, 0xff, 0xb9, 0x38, 0x60, 0x00, 0x08, - 0x63, 0xec, 0x26, 0xa8, 0x4b, 0xff, 0xff, 0x55, 0x80, 0xac, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, - 0x63, 0xfb, 0x26, 0xb0, 0x62, 0xb1, 0xf8, 0x00, 0x7e, 0x0c, 0x28, 0x50, 0x48, 0x00, 0x00, 0xf1, - 0x41, 0x81, 0x00, 0x10, 0x82, 0x3b, 0x00, 0x00, 0x2c, 0x11, 0x00, 0x00, 0x41, 0x82, 0x00, 0x68, - 0x7e, 0x23, 0x8b, 0x78, 0x4b, 0xff, 0xff, 0x55, 0x4b, 0xff, 0xff, 0xa5, 0x4b, 0xff, 0xff, 0xa1, - 0x4b, 0xff, 0xfe, 0xd9, 0x41, 0x82, 0xff, 0xf4, 0x2c, 0x1d, 0x00, 0xcc, 0x41, 0x82, 0x00, 0x48, - 0x2c, 0x1d, 0x00, 0xbb, 0x41, 0x82, 0xff, 0xdc, 0x2c, 0x1d, 0x00, 0xaa, 0x40, 0x82, 0xff, 0xdc, - 0x7d, 0x8c, 0x72, 0x14, 0x35, 0x6b, 0xff, 0xff, 0x41, 0x80, 0x00, 0x2c, 0x4b, 0xff, 0xff, 0xb4, - 0x7e, 0xb5, 0xfb, 0xa6, 0x7e, 0xb2, 0xfb, 0xa6, 0x63, 0xe4, 0x26, 0xc4, 0x81, 0x24, 0x00, 0x18, - 0x55, 0x29, 0x05, 0xa8, 0x91, 0x24, 0x00, 0x18, 0x48, 0x00, 0x00, 0x0c, 0x38, 0x60, 0x00, 0x80, - 0x4b, 0xff, 0xff, 0x25, 0x80, 0x92, 0x00, 0x00, 0x2c, 0x04, 0x00, 0x00, 0x40, 0x82, 0xf9, 0xf8, - 0xb3, 0x94, 0x40, 0x10, 0xc8, 0x41, 0x00, 0x98, 0xc8, 0x61, 0x00, 0xa0, 0x7f, 0x20, 0x00, 0xa6, - 0x80, 0x01, 0x00, 0xac, 0x7c, 0x08, 0x03, 0xa6, 0x80, 0x01, 0x00, 0x0c, 0x7c, 0x0f, 0xf1, 0x20, - 0x80, 0x01, 0x00, 0x10, 0x7c, 0x09, 0x03, 0xa6, 0x80, 0x01, 0x00, 0x14, 0x7c, 0x01, 0x03, 0xa6, - 0xb8, 0x61, 0x00, 0x18, 0x80, 0x01, 0x00, 0x08, 0x38, 0x21, 0x00, 0xa8, 0x4c, 0x00, 0x01, 0x2c, - 0x7c, 0x00, 0x04, 0xac, 0x4e, 0x80, 0x00, 0x20, 0x7e, 0x23, 0x20, 0x50, 0x3c, 0xa0, 0x48, 0x00, - 0x52, 0x25, 0x01, 0xba, 0x90, 0xa3, 0x00, 0x00, 0x7c, 0x00, 0x18, 0xac, 0x7c, 0x00, 0x04, 0xac, - 0x7c, 0x00, 0x1f, 0xac, 0x4c, 0x00, 0x01, 0x2c, 0x4e, 0x80, 0x00, 0x20, 0x7d, 0x70, 0x8b, 0xd7, - 0x7d, 0x4b, 0x89, 0xd6, 0x7d, 0x4a, 0x80, 0x50, 0x91, 0x5b, 0x00, 0x00, 0x4e, 0x80, 0x00, 0x20, - 0x7f, 0xa8, 0x02, 0xa6, 0x63, 0xef, 0x27, 0xe8, 0x63, 0xe7, 0x18, 0x08, 0x3c, 0xc0, 0x80, 0x00, - 0x7c, 0xd0, 0x33, 0x78, 0x39, 0x00, 0x00, 0x00, 0x3c, 0x60, 0x00, 0xd0, 0x60, 0x63, 0xc0, 0xde, - 0x80, 0x8f, 0x00, 0x00, 0x7c, 0x03, 0x20, 0x00, 0x40, 0x82, 0x00, 0x18, 0x80, 0x8f, 0x00, 0x04, - 0x7c, 0x03, 0x20, 0x00, 0x40, 0x82, 0x00, 0x0c, 0x39, 0xef, 0x00, 0x08, 0x48, 0x00, 0x00, 0x0c, - 0x7f, 0xa8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x80, 0x6f, 0x00, 0x00, 0x80, 0x8f, 0x00, 0x04, - 0x39, 0xef, 0x00, 0x08, 0x71, 0x09, 0x00, 0x01, 0x2f, 0x89, 0x00, 0x00, 0x39, 0x20, 0x00, 0x00, - 0x54, 0x6a, 0x1f, 0x7e, 0x54, 0x65, 0x3f, 0x7e, 0x74, 0x6b, 0x10, 0x00, 0x54, 0x63, 0x01, 0xfe, - 0x40, 0x82, 0x00, 0x0c, 0x54, 0xcc, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x08, 0x7e, 0x0c, 0x83, 0x78, - 0x2e, 0x05, 0x00, 0x00, 0x2c, 0x0a, 0x00, 0x01, 0x41, 0xa0, 0x00, 0x2c, 0x41, 0xa2, 0x00, 0xe4, - 0x2c, 0x0a, 0x00, 0x03, 0x41, 0xa0, 0x01, 0xb0, 0x41, 0x82, 0x02, 0x54, 0x2c, 0x0a, 0x00, 0x05, - 0x41, 0x80, 0x02, 0xdc, 0x41, 0xa2, 0x04, 0xe8, 0x2c, 0x0a, 0x00, 0x07, 0x41, 0xa0, 0x05, 0x14, - 0x48, 0x00, 0x05, 0xf8, 0x7d, 0x8c, 0x1a, 0x14, 0x2c, 0x05, 0x00, 0x03, 0x41, 0x82, 0x00, 0x48, - 0x41, 0x81, 0x00, 0x60, 0x40, 0xbe, 0xff, 0x84, 0x2e, 0x05, 0x00, 0x01, 0x41, 0x91, 0x00, 0x2c, - 0x54, 0x8a, 0x84, 0x3e, 0x41, 0x92, 0x00, 0x10, 0x7c, 0x89, 0x61, 0xae, 0x39, 0x29, 0x00, 0x01, - 0x48, 0x00, 0x00, 0x0c, 0x7c, 0x89, 0x63, 0x2e, 0x39, 0x29, 0x00, 0x02, 0x35, 0x4a, 0xff, 0xff, - 0x40, 0xa0, 0xff, 0xe4, 0x4b, 0xff, 0xff, 0x54, 0x55, 0x8c, 0x00, 0x3a, 0x90, 0x8c, 0x00, 0x00, - 0x4b, 0xff, 0xff, 0x48, 0x7c, 0x89, 0x23, 0x78, 0x40, 0x9e, 0x04, 0xd0, 0x35, 0x29, 0xff, 0xff, - 0x41, 0x80, 0x04, 0xc8, 0x7c, 0xa9, 0x78, 0xae, 0x7c, 0xa9, 0x61, 0xae, 0x4b, 0xff, 0xff, 0xf0, - 0x39, 0xef, 0x00, 0x08, 0x40, 0xbe, 0xff, 0x24, 0x80, 0xaf, 0xff, 0xf8, 0x81, 0x6f, 0xff, 0xfc, - 0x54, 0xb1, 0x04, 0x3e, 0x54, 0xaa, 0x85, 0x3e, 0x54, 0xa5, 0x27, 0x3e, 0x2e, 0x85, 0x00, 0x01, - 0x41, 0x96, 0x00, 0x10, 0x41, 0xb5, 0x00, 0x14, 0x7c, 0x89, 0x61, 0xae, 0x48, 0x00, 0x00, 0x10, - 0x7c, 0x89, 0x63, 0x2e, 0x48, 0x00, 0x00, 0x08, 0x7c, 0x89, 0x61, 0x2e, 0x7c, 0x84, 0x5a, 0x14, - 0x7d, 0x29, 0x8a, 0x14, 0x35, 0x4a, 0xff, 0xff, 0x40, 0x80, 0xff, 0xd4, 0x4b, 0xff, 0xfe, 0xdc, - 0x54, 0x69, 0x07, 0xff, 0x41, 0x82, 0x00, 0x10, 0x55, 0x08, 0xf8, 0x7e, 0x71, 0x09, 0x00, 0x01, - 0x2f, 0x89, 0x00, 0x00, 0x2e, 0x85, 0x00, 0x04, 0x2d, 0x8a, 0x00, 0x05, 0x7d, 0x13, 0x43, 0x78, - 0x52, 0x68, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x78, 0x41, 0x8d, 0x04, 0xbc, 0x7d, 0x8c, 0x1a, 0x14, - 0x41, 0x8c, 0x00, 0x0c, 0x41, 0x94, 0x00, 0x30, 0x48, 0x00, 0x00, 0x1c, 0x40, 0x94, 0x00, 0x10, - 0x55, 0x8c, 0x00, 0x3a, 0x81, 0x6c, 0x00, 0x00, 0x48, 0x00, 0x00, 0x1c, 0x55, 0x8c, 0x00, 0x3c, - 0xa1, 0x6c, 0x00, 0x00, 0x7c, 0x89, 0x20, 0xf8, 0x55, 0x29, 0x84, 0x3e, 0x7d, 0x6b, 0x48, 0x38, - 0x54, 0x84, 0x04, 0x3e, 0x7f, 0x0b, 0x20, 0x40, 0x70, 0xa9, 0x00, 0x03, 0x41, 0x82, 0x00, 0x18, - 0x2c, 0x09, 0x00, 0x02, 0x41, 0x82, 0x00, 0x18, 0x41, 0x81, 0x00, 0x1c, 0x40, 0x9a, 0x00, 0x20, - 0x48, 0x00, 0x00, 0x18, 0x41, 0x9a, 0x00, 0x18, 0x48, 0x00, 0x00, 0x10, 0x41, 0x99, 0x00, 0x10, - 0x48, 0x00, 0x00, 0x08, 0x41, 0x98, 0x00, 0x08, 0x61, 0x08, 0x00, 0x01, 0x40, 0x8e, 0xfe, 0x3c, - 0x41, 0x94, 0xfe, 0x38, 0x81, 0x6f, 0xff, 0xf8, 0x40, 0x9e, 0x00, 0x20, 0x70, 0x6c, 0x00, 0x08, - 0x41, 0x82, 0x00, 0x0c, 0x71, 0x0c, 0x00, 0x01, 0x41, 0x82, 0x00, 0x10, 0x39, 0x8b, 0x00, 0x10, - 0x51, 0x8b, 0x03, 0x36, 0x48, 0x00, 0x00, 0x08, 0x55, 0x6b, 0x07, 0x16, 0x91, 0x6f, 0xff, 0xf8, - 0x4b, 0xff, 0xfe, 0x08, 0x40, 0xbe, 0xfe, 0x04, 0x54, 0x69, 0x16, 0xba, 0x54, 0x6e, 0x87, 0xfe, - 0x2d, 0x8e, 0x00, 0x00, 0x2e, 0x05, 0x00, 0x04, 0x70, 0xae, 0x00, 0x03, 0x2e, 0x8e, 0x00, 0x02, - 0x41, 0x94, 0x00, 0x14, 0x41, 0x96, 0x00, 0x50, 0x7c, 0x64, 0x07, 0x34, 0x7c, 0x84, 0x7a, 0x14, - 0x48, 0x00, 0x00, 0x68, 0x54, 0x65, 0xa7, 0xff, 0x41, 0x82, 0x00, 0x0c, 0x7d, 0x27, 0x48, 0x2e, - 0x7c, 0x84, 0x4a, 0x14, 0x41, 0x8e, 0x00, 0x08, 0x7c, 0x8c, 0x22, 0x14, 0x2e, 0x8e, 0x00, 0x01, - 0x41, 0x96, 0x00, 0x08, 0x80, 0x84, 0x00, 0x00, 0x54, 0x63, 0x67, 0xff, 0x41, 0x82, 0x00, 0x3c, - 0x40, 0x90, 0x00, 0x0c, 0x7c, 0x84, 0x32, 0x14, 0x48, 0x00, 0x00, 0x30, 0x7c, 0x84, 0x82, 0x14, - 0x48, 0x00, 0x00, 0x28, 0x54, 0x65, 0xa7, 0xff, 0x41, 0x82, 0x00, 0x0c, 0x7d, 0x27, 0x48, 0x2e, - 0x7c, 0x84, 0x4a, 0x14, 0x40, 0x90, 0x00, 0x0c, 0x7c, 0xcc, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x7c, - 0x7e, 0x0c, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x74, 0x40, 0x90, 0x00, 0x0c, 0x7c, 0x86, 0x23, 0x78, - 0x4b, 0xff, 0xfd, 0x68, 0x7c, 0x90, 0x23, 0x78, 0x4b, 0xff, 0xfd, 0x60, 0x54, 0x89, 0x1e, 0x78, - 0x39, 0x29, 0x00, 0x40, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x80, 0x00, 0x4c, 0x54, 0x6b, 0x67, 0xbf, - 0x2c, 0x0b, 0x00, 0x01, 0x41, 0x80, 0x00, 0x14, 0x41, 0x82, 0x00, 0x08, 0x48, 0x00, 0x00, 0x10, - 0x41, 0xbe, 0xfd, 0x38, 0x48, 0x00, 0x00, 0x08, 0x40, 0xbe, 0xfd, 0x30, 0x2c, 0x05, 0x00, 0x03, - 0x41, 0x81, 0x00, 0x10, 0x41, 0xa2, 0x00, 0x10, 0x7d, 0xe7, 0x48, 0x2e, 0x4b, 0xff, 0xfd, 0x1c, - 0x7d, 0xe7, 0x49, 0x2e, 0x7c, 0x64, 0x07, 0x34, 0x54, 0x84, 0x1a, 0x78, 0x7d, 0xef, 0x22, 0x14, - 0x4b, 0xff, 0xfd, 0x08, 0x40, 0xbe, 0xfd, 0x04, 0x7c, 0xa7, 0x4a, 0x14, 0x40, 0x92, 0x00, 0x14, - 0x54, 0x64, 0x04, 0x3e, 0x91, 0xe5, 0x00, 0x00, 0x90, 0x85, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0xec, - 0x81, 0x25, 0x00, 0x04, 0x2c, 0x09, 0x00, 0x00, 0x41, 0xa2, 0xfc, 0xe0, 0x39, 0x29, 0xff, 0xff, - 0x91, 0x25, 0x00, 0x04, 0x81, 0xe5, 0x00, 0x00, 0x4b, 0xff, 0xfc, 0xd0, 0x40, 0xbe, 0xfc, 0xcc, - 0x54, 0x6b, 0x16, 0xba, 0x7f, 0x47, 0x5a, 0x14, 0x81, 0x3a, 0x00, 0x00, 0x54, 0x6e, 0x67, 0xbe, - 0x41, 0x92, 0x00, 0x84, 0x2e, 0x05, 0x00, 0x05, 0x40, 0x90, 0x01, 0x74, 0x2e, 0x05, 0x00, 0x03, - 0x40, 0x90, 0x00, 0x90, 0x2e, 0x05, 0x00, 0x01, 0x54, 0x65, 0x87, 0xff, 0x41, 0x82, 0x00, 0x08, - 0x7c, 0x8c, 0x22, 0x14, 0x2f, 0x0e, 0x00, 0x01, 0x40, 0x92, 0x00, 0x24, 0x41, 0xb9, 0x00, 0x18, - 0x41, 0x9a, 0x00, 0x0c, 0x88, 0x84, 0x00, 0x00, 0x48, 0x00, 0x00, 0xf8, 0xa0, 0x84, 0x00, 0x00, - 0x48, 0x00, 0x00, 0xf0, 0x80, 0x84, 0x00, 0x00, 0x48, 0x00, 0x00, 0xe8, 0x54, 0x73, 0xe5, 0x3e, - 0x41, 0xb9, 0x00, 0x20, 0x41, 0x9a, 0x00, 0x10, 0x99, 0x24, 0x00, 0x00, 0x38, 0x84, 0x00, 0x01, - 0x48, 0x00, 0x00, 0x18, 0xb1, 0x24, 0x00, 0x00, 0x38, 0x84, 0x00, 0x02, 0x48, 0x00, 0x00, 0x0c, - 0x91, 0x24, 0x00, 0x00, 0x38, 0x84, 0x00, 0x04, 0x36, 0x73, 0xff, 0xff, 0x40, 0x80, 0xff, 0xd4, - 0x4b, 0xff, 0xfc, 0x38, 0x54, 0x65, 0x87, 0xff, 0x41, 0x82, 0x00, 0x08, 0x7c, 0x84, 0x62, 0x14, - 0x71, 0xc5, 0x00, 0x01, 0x41, 0x82, 0x00, 0x9c, 0x7c, 0x84, 0x4a, 0x14, 0x48, 0x00, 0x00, 0x94, - 0x54, 0x6a, 0x87, 0xbe, 0x54, 0x8e, 0x16, 0xba, 0x7e, 0x67, 0x72, 0x14, 0x40, 0x92, 0x00, 0x08, - 0x3a, 0x6f, 0xff, 0xfc, 0x80, 0x9a, 0x00, 0x00, 0x81, 0x33, 0x00, 0x00, 0x71, 0x4b, 0x00, 0x01, - 0x41, 0x82, 0x00, 0x08, 0x7c, 0x9a, 0x23, 0x78, 0x71, 0x4b, 0x00, 0x02, 0x41, 0x82, 0x00, 0x10, - 0x7d, 0x33, 0x4b, 0x78, 0x40, 0xb2, 0x00, 0x08, 0x7e, 0x6c, 0x9a, 0x14, 0x54, 0x65, 0x67, 0x3f, - 0x2c, 0x05, 0x00, 0x09, 0x40, 0x80, 0x00, 0x54, 0x48, 0x00, 0x00, 0x79, 0x7c, 0x89, 0x22, 0x14, - 0x48, 0x00, 0x00, 0x40, 0x7c, 0x89, 0x21, 0xd6, 0x48, 0x00, 0x00, 0x38, 0x7d, 0x24, 0x23, 0x78, - 0x48, 0x00, 0x00, 0x30, 0x7d, 0x24, 0x20, 0x38, 0x48, 0x00, 0x00, 0x28, 0x7d, 0x24, 0x22, 0x78, - 0x48, 0x00, 0x00, 0x20, 0x7d, 0x24, 0x20, 0x30, 0x48, 0x00, 0x00, 0x18, 0x7d, 0x24, 0x24, 0x30, - 0x48, 0x00, 0x00, 0x10, 0x5d, 0x24, 0x20, 0x3e, 0x48, 0x00, 0x00, 0x08, 0x7d, 0x24, 0x26, 0x30, - 0x90, 0x9a, 0x00, 0x00, 0x4b, 0xff, 0xfb, 0x84, 0x2c, 0x05, 0x00, 0x0a, 0x41, 0x81, 0xfb, 0x7c, - 0xc0, 0x5a, 0x00, 0x00, 0xc0, 0x73, 0x00, 0x00, 0x41, 0x82, 0x00, 0x0c, 0xec, 0x43, 0x10, 0x2a, - 0x48, 0x00, 0x00, 0x08, 0xec, 0x43, 0x00, 0xb2, 0xd0, 0x5a, 0x00, 0x00, 0x4b, 0xff, 0xfb, 0x5c, - 0x7d, 0x48, 0x02, 0xa6, 0x54, 0xa5, 0x1e, 0x78, 0x7d, 0x4a, 0x2a, 0x14, 0x80, 0x9a, 0x00, 0x00, - 0x81, 0x33, 0x00, 0x00, 0x7d, 0x48, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x40, 0xbe, 0xfb, 0x3c, - 0x54, 0x69, 0xc0, 0x3e, 0x7d, 0x8e, 0x63, 0x78, 0x48, 0x00, 0x00, 0x35, 0x41, 0x92, 0x00, 0x0c, - 0x7e, 0x31, 0x22, 0x14, 0x48, 0x00, 0x00, 0x08, 0x7d, 0x29, 0x22, 0x14, 0x54, 0x64, 0xc4, 0x3f, - 0x38, 0xa0, 0x00, 0x00, 0x41, 0x82, 0xfb, 0x14, 0x7d, 0x45, 0x88, 0xae, 0x7d, 0x45, 0x49, 0xae, - 0x38, 0xa5, 0x00, 0x01, 0x7c, 0x05, 0x20, 0x00, 0x4b, 0xff, 0xff, 0xec, 0x2e, 0x8a, 0x00, 0x04, - 0x55, 0x31, 0x36, 0xba, 0x2c, 0x11, 0x00, 0x3c, 0x7e, 0x27, 0x88, 0x2e, 0x40, 0x82, 0x00, 0x08, - 0x7d, 0xd1, 0x73, 0x78, 0x41, 0x96, 0x00, 0x08, 0xa2, 0x31, 0x00, 0x00, 0x55, 0x29, 0x56, 0xba, - 0x2c, 0x09, 0x00, 0x3c, 0x7d, 0x27, 0x48, 0x2e, 0x40, 0x82, 0x00, 0x08, 0x7d, 0xc9, 0x73, 0x78, - 0x41, 0x96, 0x00, 0x08, 0xa1, 0x29, 0x00, 0x00, 0x4e, 0x80, 0x00, 0x20, 0x2c, 0x05, 0x00, 0x04, - 0x40, 0x80, 0x00, 0x28, 0x7c, 0x89, 0x23, 0x78, 0x7d, 0xc3, 0x62, 0x14, 0x55, 0xce, 0x00, 0x3c, - 0x4b, 0xff, 0xff, 0xad, 0x7c, 0x84, 0x20, 0xf8, 0x54, 0x84, 0x04, 0x3e, 0x7d, 0x2b, 0x20, 0x38, - 0x7e, 0x24, 0x20, 0x38, 0x4b, 0xff, 0xfb, 0xbc, 0x54, 0x6b, 0xe4, 0x3e, 0x4b, 0xff, 0xfb, 0xb4, - 0x7c, 0x9a, 0x23, 0x78, 0x54, 0x84, 0x18, 0x38, 0x40, 0x92, 0x00, 0x20, 0x40, 0x9e, 0x00, 0x0c, - 0x7d, 0xe8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x21, 0x7d, 0xe4, 0x7a, 0x14, 0x39, 0xef, 0x00, 0x07, - 0x55, 0xef, 0x00, 0x38, 0x4b, 0xff, 0xfa, 0x64, 0x2e, 0x05, 0x00, 0x03, 0x41, 0x91, 0x00, 0x5c, - 0x3c, 0xa0, 0x48, 0x00, 0x7d, 0x83, 0x62, 0x14, 0x55, 0x8c, 0x00, 0x3a, 0x40, 0x92, 0x00, 0x20, - 0x40, 0xbe, 0xfa, 0x48, 0x57, 0x44, 0x00, 0x3a, 0x7c, 0x8c, 0x20, 0x50, 0x50, 0x85, 0x01, 0xba, - 0x50, 0x65, 0x07, 0xfe, 0x90, 0xac, 0x00, 0x00, 0x4b, 0xff, 0xfa, 0x30, 0x40, 0xbe, 0xff, 0xbc, - 0x7d, 0x2c, 0x78, 0x50, 0x51, 0x25, 0x01, 0xba, 0x90, 0xac, 0x00, 0x00, 0x39, 0x8c, 0x00, 0x04, - 0x7d, 0x6f, 0x22, 0x14, 0x39, 0x6b, 0xff, 0xfc, 0x7d, 0x2b, 0x60, 0x50, 0x51, 0x25, 0x01, 0xba, - 0x90, 0xab, 0x00, 0x00, 0x4b, 0xff, 0xff, 0x94, 0x2e, 0x05, 0x00, 0x06, 0x41, 0x92, 0x00, 0x28, - 0x4b, 0xff, 0xfb, 0x20, 0x55, 0x8c, 0x84, 0x3e, 0x57, 0x44, 0x84, 0x3e, 0x57, 0x5a, 0x04, 0x3e, - 0x7c, 0x0c, 0x20, 0x00, 0x41, 0x80, 0xfb, 0xa4, 0x7c, 0x0c, 0xd0, 0x00, 0x40, 0x80, 0xfb, 0x9c, - 0x4b, 0xff, 0xf9, 0xd8, 0x57, 0x45, 0xff, 0xfe, 0x68, 0xa5, 0x00, 0x01, 0x71, 0x03, 0x00, 0x01, - 0x7c, 0x05, 0x18, 0x00, 0x41, 0x82, 0x00, 0x1c, 0x51, 0x1a, 0x0f, 0xbc, 0x6b, 0x5a, 0x00, 0x02, - 0x57, 0x45, 0xff, 0xff, 0x41, 0x82, 0x00, 0x08, 0x6b, 0x5a, 0x00, 0x01, 0x93, 0x4f, 0xff, 0xfc, - 0x53, 0x48, 0x07, 0xfe, 0x4b, 0xff, 0xf9, 0xa4, 0x2c, 0x0b, 0x00, 0x00, 0x40, 0x82, 0xf9, 0x94, - 0x40, 0x92, 0x00, 0x0c, 0x39, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x14, 0x54, 0x69, 0x06, 0xff, - 0x40, 0x82, 0x00, 0x08, 0x40, 0x9e, 0x00, 0x10, 0x54, 0x65, 0x67, 0xfe, 0x7d, 0x08, 0x4c, 0x30, - 0x7d, 0x08, 0x2a, 0x78, 0x54, 0x85, 0x00, 0x1f, 0x41, 0x82, 0x00, 0x08, 0x7c, 0xa6, 0x2b, 0x78, - 0x54, 0x85, 0x80, 0x1f, 0x41, 0x82, 0x00, 0x08, 0x7c, 0xb0, 0x2b, 0x78, 0x4b, 0xff, 0xf9, 0x5c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x26, 0xa0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x94, 0x21, 0xff, 0x58, 0x90, 0x01, 0x00, 0x08, + 0x7c, 0x08, 0x02, 0xa6, 0x90, 0x01, 0x00, 0xac, 0x7c, 0x00, 0x00, 0x26, 0x90, 0x01, 0x00, 0x0c, + 0x7c, 0x09, 0x02, 0xa6, 0x90, 0x01, 0x00, 0x10, 0x7c, 0x01, 0x02, 0xa6, 0x90, 0x01, 0x00, 0x14, + 0xbc, 0x61, 0x00, 0x18, 0x7f, 0x20, 0x00, 0xa6, 0x63, 0x3a, 0x20, 0x00, 0x73, 0x5a, 0xf9, 0xff, + 0x7f, 0x40, 0x01, 0x24, 0xd8, 0x41, 0x00, 0x98, 0xd8, 0x61, 0x00, 0xa0, 0x3f, 0xe0, 0x80, 0x00, + 0x3e, 0x80, 0xcc, 0x00, 0xa3, 0x94, 0x40, 0x10, 0x63, 0x95, 0x00, 0xff, 0xb2, 0xb4, 0x40, 0x10, + 0x48, 0x00, 0x06, 0xb1, 0x3a, 0xa0, 0x00, 0x00, 0x3a, 0xc0, 0x00, 0x19, 0x3a, 0xe0, 0x00, 0xd0, + 0x3f, 0x00, 0xcd, 0x00, 0x63, 0xf2, 0x26, 0xa0, 0x80, 0x01, 0x00, 0xac, 0x90, 0x12, 0x00, 0x04, + 0x92, 0xb8, 0x64, 0x3c, 0x48, 0x00, 0x04, 0x85, 0x41, 0x82, 0x05, 0xfc, 0x2c, 0x1d, 0x00, 0x04, + 0x40, 0x80, 0x00, 0x10, 0x2c, 0x1d, 0x00, 0x01, 0x41, 0x80, 0x05, 0xec, 0x48, 0x00, 0x03, 0xa8, + 0x41, 0x82, 0x05, 0x48, 0x2c, 0x1d, 0x00, 0x06, 0x41, 0x82, 0x00, 0x8c, 0x2c, 0x1d, 0x00, 0x07, + 0x41, 0x82, 0x03, 0x8c, 0x2c, 0x1d, 0x00, 0x08, 0x41, 0x82, 0x05, 0xd8, 0x2c, 0x1d, 0x00, 0x09, + 0x41, 0x82, 0x00, 0xa0, 0x2c, 0x1d, 0x00, 0x10, 0x41, 0x82, 0x00, 0x98, 0x2c, 0x1d, 0x00, 0x2f, + 0x41, 0x82, 0x00, 0x70, 0x2c, 0x1d, 0x00, 0x30, 0x41, 0x82, 0x00, 0x78, 0x2c, 0x1d, 0x00, 0x38, + 0x41, 0x82, 0x05, 0x80, 0x2c, 0x1d, 0x00, 0x40, 0x41, 0x82, 0x03, 0x9c, 0x2c, 0x1d, 0x00, 0x41, + 0x41, 0x82, 0x03, 0xb0, 0x2c, 0x1d, 0x00, 0x44, 0x41, 0x82, 0x00, 0x68, 0x2c, 0x1d, 0x00, 0x50, + 0x41, 0x82, 0x00, 0x20, 0x2c, 0x1d, 0x00, 0x60, 0x41, 0x82, 0x00, 0x24, 0x2c, 0x1d, 0x00, 0x89, + 0x41, 0x82, 0x00, 0x50, 0x2c, 0x1d, 0x00, 0x99, 0x41, 0x82, 0x05, 0x64, 0x48, 0x00, 0x05, 0x68, + 0x80, 0x72, 0x00, 0x00, 0x48, 0x00, 0x04, 0x81, 0x48, 0x00, 0x05, 0x5c, 0x48, 0x00, 0x05, 0xe5, + 0x48, 0x00, 0x05, 0x54, 0x38, 0x80, 0x00, 0x01, 0x90, 0x92, 0x00, 0x00, 0x48, 0x00, 0x05, 0x48, + 0x48, 0x00, 0x04, 0x61, 0x3a, 0x00, 0x00, 0xa0, 0x63, 0xec, 0x26, 0xc4, 0x48, 0x00, 0x03, 0x6c, + 0x38, 0x60, 0x01, 0x20, 0x63, 0xec, 0x26, 0xc4, 0x48, 0x00, 0x04, 0x21, 0x48, 0x00, 0x05, 0x28, + 0x2f, 0x1d, 0x00, 0x10, 0x2e, 0x9d, 0x00, 0x44, 0x63, 0xe4, 0x1a, 0xb4, 0x3c, 0x60, 0x80, 0x00, + 0x60, 0x63, 0x03, 0x00, 0x48, 0x00, 0x05, 0x65, 0x38, 0x63, 0x0a, 0x00, 0x48, 0x00, 0x05, 0x5d, + 0x38, 0x63, 0x06, 0x00, 0x48, 0x00, 0x05, 0x55, 0x63, 0xec, 0x26, 0xb4, 0x92, 0xac, 0x00, 0x00, + 0x92, 0xac, 0x00, 0x04, 0x92, 0xac, 0x00, 0x08, 0x63, 0xe4, 0x26, 0xc4, 0x81, 0x24, 0x00, 0x18, + 0x80, 0x72, 0x00, 0x00, 0x2c, 0x03, 0x00, 0x02, 0x40, 0x82, 0x00, 0x0c, 0x41, 0x96, 0x00, 0x0c, + 0x48, 0x00, 0x00, 0x20, 0x38, 0x60, 0x00, 0x00, 0x90, 0x6c, 0x00, 0x0c, 0x40, 0x82, 0x00, 0x14, + 0x40, 0x96, 0x00, 0x10, 0x61, 0x29, 0x04, 0x00, 0x91, 0x24, 0x00, 0x18, 0x48, 0x00, 0x02, 0x70, + 0x55, 0x29, 0x05, 0xa8, 0x91, 0x24, 0x00, 0x18, 0x41, 0x96, 0x04, 0xac, 0x41, 0x9a, 0x00, 0x08, + 0x39, 0x8c, 0x00, 0x04, 0x38, 0x60, 0x00, 0x04, 0x48, 0x00, 0x03, 0x61, 0x40, 0x99, 0x00, 0x10, + 0x39, 0x8c, 0x00, 0x04, 0x38, 0x60, 0x00, 0x04, 0x48, 0x00, 0x03, 0x51, 0x63, 0xe4, 0x26, 0xb4, + 0x80, 0x64, 0x00, 0x00, 0x80, 0x84, 0x00, 0x04, 0x7c, 0x72, 0xfb, 0xa6, 0x7c, 0x95, 0xfb, 0xa6, + 0x48, 0x00, 0x04, 0x74, 0x7c, 0x32, 0x43, 0xa6, 0x7c, 0x3a, 0x02, 0xa6, 0x7c, 0x73, 0x43, 0xa6, + 0x7c, 0x7b, 0x02, 0xa6, 0x54, 0x63, 0x05, 0xa8, 0x90, 0x60, 0x26, 0xdc, 0x54, 0x63, 0x06, 0x20, + 0x60, 0x63, 0x20, 0x00, 0x54, 0x63, 0x04, 0x5e, 0x7c, 0x7b, 0x03, 0xa6, 0x3c, 0x60, 0x80, 0x00, + 0x60, 0x63, 0x1a, 0xf4, 0x7c, 0x7a, 0x03, 0xa6, 0x4c, 0x00, 0x01, 0x2c, 0x7c, 0x00, 0x04, 0xac, + 0x4c, 0x00, 0x00, 0x64, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x26, 0xc4, 0x90, 0x23, 0x00, 0x14, + 0x7c, 0x61, 0x1b, 0x78, 0x7c, 0x73, 0x42, 0xa6, 0xbc, 0x41, 0x00, 0x24, 0x7c, 0x24, 0x0b, 0x78, + 0x7c, 0x32, 0x42, 0xa6, 0x90, 0x04, 0x00, 0x1c, 0x90, 0x24, 0x00, 0x20, 0x7c, 0x68, 0x02, 0xa6, + 0x90, 0x64, 0x00, 0x9c, 0x7c, 0x60, 0x00, 0x26, 0x90, 0x64, 0x00, 0x00, 0x7c, 0x61, 0x02, 0xa6, + 0x90, 0x64, 0x00, 0x04, 0x7c, 0x69, 0x02, 0xa6, 0x90, 0x64, 0x00, 0x08, 0x7c, 0x72, 0x02, 0xa6, + 0x90, 0x64, 0x00, 0x0c, 0x7c, 0x73, 0x02, 0xa6, 0x90, 0x64, 0x00, 0x10, 0x39, 0x20, 0x00, 0x00, + 0x7d, 0x32, 0xfb, 0xa6, 0x7d, 0x35, 0xfb, 0xa6, 0xd0, 0x04, 0x00, 0xa0, 0xd0, 0x24, 0x00, 0xa4, + 0xd0, 0x44, 0x00, 0xa8, 0xd0, 0x64, 0x00, 0xac, 0xd0, 0x84, 0x00, 0xb0, 0xd0, 0xa4, 0x00, 0xb4, + 0xd0, 0xc4, 0x00, 0xb8, 0xd0, 0xe4, 0x00, 0xbc, 0xd1, 0x04, 0x00, 0xc0, 0xd1, 0x24, 0x00, 0xc4, + 0xd1, 0x44, 0x00, 0xc8, 0xd1, 0x64, 0x00, 0xcc, 0xd1, 0x84, 0x00, 0xd0, 0xd1, 0xa4, 0x00, 0xd4, + 0xd1, 0xc4, 0x00, 0xd8, 0xd1, 0xe4, 0x00, 0xdc, 0xd2, 0x04, 0x00, 0xe0, 0xd2, 0x24, 0x00, 0xe4, + 0xd2, 0x44, 0x00, 0xe8, 0xd2, 0x64, 0x00, 0xec, 0xd2, 0x84, 0x00, 0xf0, 0xd2, 0xa4, 0x00, 0xf4, + 0xd2, 0xc4, 0x00, 0xf8, 0xd2, 0xe4, 0x00, 0xfc, 0xd3, 0x04, 0x01, 0x00, 0xd3, 0x24, 0x01, 0x04, + 0xd3, 0x44, 0x01, 0x08, 0xd3, 0x64, 0x01, 0x0c, 0xd3, 0x84, 0x01, 0x10, 0xd3, 0xa4, 0x01, 0x14, + 0xd3, 0xc4, 0x01, 0x18, 0xd3, 0xe4, 0x01, 0x1c, 0x3f, 0xe0, 0x80, 0x00, 0x63, 0xe5, 0x26, 0xb4, + 0x82, 0x05, 0x00, 0x00, 0x82, 0x25, 0x00, 0x04, 0x82, 0x65, 0x00, 0x0c, 0x2c, 0x13, 0x00, 0x00, + 0x41, 0x82, 0x00, 0x74, 0x2c, 0x13, 0x00, 0x02, 0x40, 0x82, 0x00, 0x18, 0x81, 0x24, 0x00, 0x14, + 0x39, 0x33, 0x00, 0x03, 0x91, 0x25, 0x00, 0x00, 0x91, 0x25, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x6c, + 0x7c, 0x10, 0x98, 0x00, 0x41, 0x82, 0x00, 0x38, 0x7c, 0x11, 0x98, 0x00, 0x41, 0x82, 0x00, 0x30, + 0x7d, 0x30, 0x8a, 0x14, 0x91, 0x25, 0x00, 0x0c, 0x82, 0x05, 0x00, 0x08, 0x2c, 0x10, 0x00, 0x00, + 0x41, 0x82, 0x00, 0x48, 0x80, 0x64, 0x00, 0x10, 0x7c, 0x10, 0x18, 0x00, 0x40, 0x82, 0x00, 0x10, + 0x3a, 0x00, 0x00, 0x00, 0x92, 0x05, 0x00, 0x08, 0x48, 0x00, 0x00, 0x30, 0x3a, 0x20, 0x00, 0x00, + 0x92, 0x25, 0x00, 0x0c, 0x81, 0x24, 0x00, 0x18, 0x61, 0x29, 0x04, 0x00, 0x91, 0x24, 0x00, 0x18, + 0x48, 0x00, 0x00, 0x30, 0x7e, 0x12, 0xfb, 0xa6, 0x7e, 0x35, 0xfb, 0xa6, 0x39, 0x20, 0x00, 0x01, + 0x91, 0x25, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x1c, 0x38, 0xa0, 0x00, 0x02, 0x63, 0xe4, 0x26, 0xa0, + 0x90, 0xa4, 0x00, 0x00, 0x38, 0x60, 0x00, 0x11, 0x48, 0x00, 0x01, 0xbd, 0x4b, 0xff, 0xfc, 0x1d, + 0x7c, 0x20, 0x00, 0xa6, 0x54, 0x21, 0x07, 0xfa, 0x54, 0x21, 0x04, 0x5e, 0x7c, 0x20, 0x01, 0x24, + 0x63, 0xe1, 0x26, 0xc4, 0x80, 0x61, 0x00, 0x00, 0x7c, 0x6f, 0xf1, 0x20, 0x80, 0x61, 0x00, 0x14, + 0x7c, 0x7a, 0x03, 0xa6, 0x80, 0x61, 0x00, 0x18, 0x7c, 0x7b, 0x03, 0xa6, 0x80, 0x61, 0x00, 0x9c, + 0x7c, 0x68, 0x03, 0xa6, 0xb8, 0x41, 0x00, 0x24, 0x80, 0x01, 0x00, 0x1c, 0x80, 0x21, 0x00, 0x20, + 0x4c, 0x00, 0x01, 0x2c, 0x7c, 0x00, 0x04, 0xac, 0x4c, 0x00, 0x00, 0x64, 0x92, 0xb2, 0x00, 0x00, + 0x48, 0x00, 0x02, 0x50, 0x2e, 0x9d, 0x00, 0x02, 0x38, 0x60, 0x00, 0x08, 0x63, 0xec, 0x26, 0xa8, + 0x48, 0x00, 0x00, 0xf9, 0x80, 0xac, 0x00, 0x00, 0x80, 0x6c, 0x00, 0x04, 0x98, 0x65, 0x00, 0x00, + 0x41, 0x94, 0x00, 0x10, 0xb0, 0x65, 0x00, 0x00, 0x41, 0x96, 0x00, 0x08, 0x90, 0x65, 0x00, 0x00, + 0x7c, 0x00, 0x28, 0xac, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x2f, 0xac, 0x4c, 0x00, 0x01, 0x2c, + 0x48, 0x00, 0x02, 0x04, 0x48, 0x00, 0x01, 0x1d, 0x38, 0x60, 0x00, 0x04, 0x63, 0xec, 0x26, 0xa8, + 0x48, 0x00, 0x00, 0xb9, 0x82, 0x0c, 0x00, 0x00, 0x63, 0xec, 0x27, 0xe8, 0x48, 0x00, 0x00, 0x1c, + 0x48, 0x00, 0x01, 0x01, 0x38, 0x60, 0x00, 0x08, 0x63, 0xec, 0x26, 0xa8, 0x48, 0x00, 0x00, 0x9d, + 0x82, 0x0c, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, 0x63, 0xfb, 0x26, 0xb0, 0x3a, 0x20, 0x0f, 0x80, + 0x48, 0x00, 0x02, 0x3d, 0x41, 0x82, 0x00, 0x20, 0x7e, 0x23, 0x8b, 0x78, 0x48, 0x00, 0x00, 0x7d, + 0x48, 0x00, 0x00, 0xd1, 0x41, 0x82, 0xff, 0xfc, 0x7d, 0x8c, 0x72, 0x14, 0x35, 0x6b, 0xff, 0xff, + 0x41, 0x81, 0xff, 0xe8, 0x80, 0x7b, 0x00, 0x00, 0x2c, 0x03, 0x00, 0x00, 0x41, 0x82, 0x00, 0x08, + 0x48, 0x00, 0x00, 0x59, 0x7c, 0x00, 0x60, 0xac, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x67, 0xac, + 0x4c, 0x00, 0x01, 0x2c, 0x48, 0x00, 0x01, 0x80, 0x7f, 0xc8, 0x02, 0xa6, 0x3c, 0x60, 0xa0, 0x00, + 0x48, 0x00, 0x00, 0x15, 0x76, 0x03, 0x08, 0x00, 0x56, 0x1d, 0x86, 0x3e, 0x7f, 0xc8, 0x03, 0xa6, + 0x4e, 0x80, 0x00, 0x20, 0x92, 0xf8, 0x68, 0x14, 0x90, 0x78, 0x68, 0x24, 0x92, 0xd8, 0x68, 0x20, + 0x80, 0xb8, 0x68, 0x20, 0x70, 0xa5, 0x00, 0x01, 0x40, 0x82, 0xff, 0xf8, 0x82, 0x18, 0x68, 0x24, + 0x90, 0xb8, 0x68, 0x14, 0x4e, 0x80, 0x00, 0x20, 0x7d, 0x48, 0x02, 0xa6, 0x7c, 0x69, 0x03, 0xa6, + 0x39, 0xc0, 0x00, 0x00, 0x48, 0x00, 0x00, 0x79, 0x48, 0x00, 0x00, 0x75, 0x4b, 0xff, 0xff, 0xad, + 0x41, 0x82, 0xff, 0xf4, 0x7f, 0xae, 0x61, 0xae, 0x39, 0xce, 0x00, 0x01, 0x42, 0x00, 0xff, 0xe8, + 0x7d, 0x48, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x7d, 0x48, 0x02, 0xa6, 0x7c, 0x69, 0x03, 0xa6, + 0x39, 0xc0, 0x00, 0x00, 0x7c, 0x6c, 0x70, 0xae, 0x48, 0x00, 0x00, 0x1d, 0x41, 0x82, 0xff, 0xf8, + 0x39, 0xce, 0x00, 0x01, 0x42, 0x00, 0xff, 0xf0, 0x7d, 0x48, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, + 0x38, 0x60, 0x00, 0xaa, 0x7f, 0xc8, 0x02, 0xa6, 0x54, 0x63, 0xa0, 0x16, 0x64, 0x63, 0xb0, 0x00, + 0x3a, 0xc0, 0x00, 0x19, 0x3a, 0xe0, 0x00, 0xd0, 0x3f, 0x00, 0xcd, 0x00, 0x4b, 0xff, 0xff, 0x69, + 0x56, 0x03, 0x37, 0xff, 0x7f, 0xc8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x7f, 0xc8, 0x02, 0xa6, + 0x3c, 0x60, 0xd0, 0x00, 0x4b, 0xff, 0xff, 0x51, 0x56, 0x03, 0x37, 0xff, 0x41, 0x82, 0xff, 0xf4, + 0x7f, 0xc8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x4b, 0xff, 0xff, 0xb9, 0x38, 0x60, 0x00, 0x08, + 0x63, 0xec, 0x26, 0xa8, 0x4b, 0xff, 0xff, 0x55, 0x80, 0xac, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, + 0x63, 0xfb, 0x26, 0xb0, 0x62, 0xb1, 0xf8, 0x00, 0x7e, 0x0c, 0x28, 0x50, 0x48, 0x00, 0x00, 0xf1, + 0x41, 0x81, 0x00, 0x10, 0x82, 0x3b, 0x00, 0x00, 0x2c, 0x11, 0x00, 0x00, 0x41, 0x82, 0x00, 0x68, + 0x7e, 0x23, 0x8b, 0x78, 0x4b, 0xff, 0xff, 0x55, 0x4b, 0xff, 0xff, 0xa5, 0x4b, 0xff, 0xff, 0xa1, + 0x4b, 0xff, 0xfe, 0xd9, 0x41, 0x82, 0xff, 0xf4, 0x2c, 0x1d, 0x00, 0xcc, 0x41, 0x82, 0x00, 0x48, + 0x2c, 0x1d, 0x00, 0xbb, 0x41, 0x82, 0xff, 0xdc, 0x2c, 0x1d, 0x00, 0xaa, 0x40, 0x82, 0xff, 0xdc, + 0x7d, 0x8c, 0x72, 0x14, 0x35, 0x6b, 0xff, 0xff, 0x41, 0x80, 0x00, 0x2c, 0x4b, 0xff, 0xff, 0xb4, + 0x7e, 0xb5, 0xfb, 0xa6, 0x7e, 0xb2, 0xfb, 0xa6, 0x63, 0xe4, 0x26, 0xc4, 0x81, 0x24, 0x00, 0x18, + 0x55, 0x29, 0x05, 0xa8, 0x91, 0x24, 0x00, 0x18, 0x48, 0x00, 0x00, 0x0c, 0x38, 0x60, 0x00, 0x80, + 0x4b, 0xff, 0xff, 0x25, 0x80, 0x92, 0x00, 0x00, 0x2c, 0x04, 0x00, 0x00, 0x40, 0x82, 0xf9, 0xf8, + 0xb3, 0x94, 0x40, 0x10, 0xc8, 0x41, 0x00, 0x98, 0xc8, 0x61, 0x00, 0xa0, 0x7f, 0x20, 0x00, 0xa6, + 0x80, 0x01, 0x00, 0xac, 0x7c, 0x08, 0x03, 0xa6, 0x80, 0x01, 0x00, 0x0c, 0x7c, 0x0f, 0xf1, 0x20, + 0x80, 0x01, 0x00, 0x10, 0x7c, 0x09, 0x03, 0xa6, 0x80, 0x01, 0x00, 0x14, 0x7c, 0x01, 0x03, 0xa6, + 0xb8, 0x61, 0x00, 0x18, 0x80, 0x01, 0x00, 0x08, 0x38, 0x21, 0x00, 0xa8, 0x4c, 0x00, 0x01, 0x2c, + 0x7c, 0x00, 0x04, 0xac, 0x4e, 0x80, 0x00, 0x20, 0x7e, 0x23, 0x20, 0x50, 0x3c, 0xa0, 0x48, 0x00, + 0x52, 0x25, 0x01, 0xba, 0x90, 0xa3, 0x00, 0x00, 0x7c, 0x00, 0x18, 0xac, 0x7c, 0x00, 0x04, 0xac, + 0x7c, 0x00, 0x1f, 0xac, 0x4c, 0x00, 0x01, 0x2c, 0x4e, 0x80, 0x00, 0x20, 0x7d, 0x70, 0x8b, 0xd7, + 0x7d, 0x4b, 0x89, 0xd6, 0x7d, 0x4a, 0x80, 0x50, 0x91, 0x5b, 0x00, 0x00, 0x4e, 0x80, 0x00, 0x20, + 0x7f, 0xa8, 0x02, 0xa6, 0x63, 0xef, 0x27, 0xe8, 0x63, 0xe7, 0x18, 0x08, 0x3c, 0xc0, 0x80, 0x00, + 0x7c, 0xd0, 0x33, 0x78, 0x39, 0x00, 0x00, 0x00, 0x3c, 0x60, 0x00, 0xd0, 0x60, 0x63, 0xc0, 0xde, + 0x80, 0x8f, 0x00, 0x00, 0x7c, 0x03, 0x20, 0x00, 0x40, 0x82, 0x00, 0x18, 0x80, 0x8f, 0x00, 0x04, + 0x7c, 0x03, 0x20, 0x00, 0x40, 0x82, 0x00, 0x0c, 0x39, 0xef, 0x00, 0x08, 0x48, 0x00, 0x00, 0x0c, + 0x7f, 0xa8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x80, 0x6f, 0x00, 0x00, 0x80, 0x8f, 0x00, 0x04, + 0x39, 0xef, 0x00, 0x08, 0x71, 0x09, 0x00, 0x01, 0x2f, 0x89, 0x00, 0x00, 0x39, 0x20, 0x00, 0x00, + 0x54, 0x6a, 0x1f, 0x7e, 0x54, 0x65, 0x3f, 0x7e, 0x74, 0x6b, 0x10, 0x00, 0x54, 0x63, 0x01, 0xfe, + 0x40, 0x82, 0x00, 0x0c, 0x54, 0xcc, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x08, 0x7e, 0x0c, 0x83, 0x78, + 0x2e, 0x05, 0x00, 0x00, 0x2c, 0x0a, 0x00, 0x01, 0x41, 0xa0, 0x00, 0x2c, 0x41, 0xa2, 0x00, 0xe4, + 0x2c, 0x0a, 0x00, 0x03, 0x41, 0xa0, 0x01, 0xb0, 0x41, 0x82, 0x02, 0x54, 0x2c, 0x0a, 0x00, 0x05, + 0x41, 0x80, 0x02, 0xdc, 0x41, 0xa2, 0x04, 0xe8, 0x2c, 0x0a, 0x00, 0x07, 0x41, 0xa0, 0x05, 0x14, + 0x48, 0x00, 0x05, 0xf8, 0x7d, 0x8c, 0x1a, 0x14, 0x2c, 0x05, 0x00, 0x03, 0x41, 0x82, 0x00, 0x48, + 0x41, 0x81, 0x00, 0x60, 0x40, 0xbe, 0xff, 0x84, 0x2e, 0x05, 0x00, 0x01, 0x41, 0x91, 0x00, 0x2c, + 0x54, 0x8a, 0x84, 0x3e, 0x41, 0x92, 0x00, 0x10, 0x7c, 0x89, 0x61, 0xae, 0x39, 0x29, 0x00, 0x01, + 0x48, 0x00, 0x00, 0x0c, 0x7c, 0x89, 0x63, 0x2e, 0x39, 0x29, 0x00, 0x02, 0x35, 0x4a, 0xff, 0xff, + 0x40, 0xa0, 0xff, 0xe4, 0x4b, 0xff, 0xff, 0x54, 0x55, 0x8c, 0x00, 0x3a, 0x90, 0x8c, 0x00, 0x00, + 0x4b, 0xff, 0xff, 0x48, 0x7c, 0x89, 0x23, 0x78, 0x40, 0x9e, 0x04, 0xd0, 0x35, 0x29, 0xff, 0xff, + 0x41, 0x80, 0x04, 0xc8, 0x7c, 0xa9, 0x78, 0xae, 0x7c, 0xa9, 0x61, 0xae, 0x4b, 0xff, 0xff, 0xf0, + 0x39, 0xef, 0x00, 0x08, 0x40, 0xbe, 0xff, 0x24, 0x80, 0xaf, 0xff, 0xf8, 0x81, 0x6f, 0xff, 0xfc, + 0x54, 0xb1, 0x04, 0x3e, 0x54, 0xaa, 0x85, 0x3e, 0x54, 0xa5, 0x27, 0x3e, 0x2e, 0x85, 0x00, 0x01, + 0x41, 0x96, 0x00, 0x10, 0x41, 0xb5, 0x00, 0x14, 0x7c, 0x89, 0x61, 0xae, 0x48, 0x00, 0x00, 0x10, + 0x7c, 0x89, 0x63, 0x2e, 0x48, 0x00, 0x00, 0x08, 0x7c, 0x89, 0x61, 0x2e, 0x7c, 0x84, 0x5a, 0x14, + 0x7d, 0x29, 0x8a, 0x14, 0x35, 0x4a, 0xff, 0xff, 0x40, 0x80, 0xff, 0xd4, 0x4b, 0xff, 0xfe, 0xdc, + 0x54, 0x69, 0x07, 0xff, 0x41, 0x82, 0x00, 0x10, 0x55, 0x08, 0xf8, 0x7e, 0x71, 0x09, 0x00, 0x01, + 0x2f, 0x89, 0x00, 0x00, 0x2e, 0x85, 0x00, 0x04, 0x2d, 0x8a, 0x00, 0x05, 0x7d, 0x13, 0x43, 0x78, + 0x52, 0x68, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x78, 0x41, 0x8d, 0x04, 0xbc, 0x7d, 0x8c, 0x1a, 0x14, + 0x41, 0x8c, 0x00, 0x0c, 0x41, 0x94, 0x00, 0x30, 0x48, 0x00, 0x00, 0x1c, 0x40, 0x94, 0x00, 0x10, + 0x55, 0x8c, 0x00, 0x3a, 0x81, 0x6c, 0x00, 0x00, 0x48, 0x00, 0x00, 0x1c, 0x55, 0x8c, 0x00, 0x3c, + 0xa1, 0x6c, 0x00, 0x00, 0x7c, 0x89, 0x20, 0xf8, 0x55, 0x29, 0x84, 0x3e, 0x7d, 0x6b, 0x48, 0x38, + 0x54, 0x84, 0x04, 0x3e, 0x7f, 0x0b, 0x20, 0x40, 0x70, 0xa9, 0x00, 0x03, 0x41, 0x82, 0x00, 0x18, + 0x2c, 0x09, 0x00, 0x02, 0x41, 0x82, 0x00, 0x18, 0x41, 0x81, 0x00, 0x1c, 0x40, 0x9a, 0x00, 0x20, + 0x48, 0x00, 0x00, 0x18, 0x41, 0x9a, 0x00, 0x18, 0x48, 0x00, 0x00, 0x10, 0x41, 0x99, 0x00, 0x10, + 0x48, 0x00, 0x00, 0x08, 0x41, 0x98, 0x00, 0x08, 0x61, 0x08, 0x00, 0x01, 0x40, 0x8e, 0xfe, 0x3c, + 0x41, 0x94, 0xfe, 0x38, 0x81, 0x6f, 0xff, 0xf8, 0x40, 0x9e, 0x00, 0x20, 0x70, 0x6c, 0x00, 0x08, + 0x41, 0x82, 0x00, 0x0c, 0x71, 0x0c, 0x00, 0x01, 0x41, 0x82, 0x00, 0x10, 0x39, 0x8b, 0x00, 0x10, + 0x51, 0x8b, 0x03, 0x36, 0x48, 0x00, 0x00, 0x08, 0x55, 0x6b, 0x07, 0x16, 0x91, 0x6f, 0xff, 0xf8, + 0x4b, 0xff, 0xfe, 0x08, 0x40, 0xbe, 0xfe, 0x04, 0x54, 0x69, 0x16, 0xba, 0x54, 0x6e, 0x87, 0xfe, + 0x2d, 0x8e, 0x00, 0x00, 0x2e, 0x05, 0x00, 0x04, 0x70, 0xae, 0x00, 0x03, 0x2e, 0x8e, 0x00, 0x02, + 0x41, 0x94, 0x00, 0x14, 0x41, 0x96, 0x00, 0x50, 0x7c, 0x64, 0x07, 0x34, 0x7c, 0x84, 0x7a, 0x14, + 0x48, 0x00, 0x00, 0x68, 0x54, 0x65, 0xa7, 0xff, 0x41, 0x82, 0x00, 0x0c, 0x7d, 0x27, 0x48, 0x2e, + 0x7c, 0x84, 0x4a, 0x14, 0x41, 0x8e, 0x00, 0x08, 0x7c, 0x8c, 0x22, 0x14, 0x2e, 0x8e, 0x00, 0x01, + 0x41, 0x96, 0x00, 0x08, 0x80, 0x84, 0x00, 0x00, 0x54, 0x63, 0x67, 0xff, 0x41, 0x82, 0x00, 0x3c, + 0x40, 0x90, 0x00, 0x0c, 0x7c, 0x84, 0x32, 0x14, 0x48, 0x00, 0x00, 0x30, 0x7c, 0x84, 0x82, 0x14, + 0x48, 0x00, 0x00, 0x28, 0x54, 0x65, 0xa7, 0xff, 0x41, 0x82, 0x00, 0x0c, 0x7d, 0x27, 0x48, 0x2e, + 0x7c, 0x84, 0x4a, 0x14, 0x40, 0x90, 0x00, 0x0c, 0x7c, 0xcc, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x7c, + 0x7e, 0x0c, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x74, 0x40, 0x90, 0x00, 0x0c, 0x7c, 0x86, 0x23, 0x78, + 0x4b, 0xff, 0xfd, 0x68, 0x7c, 0x90, 0x23, 0x78, 0x4b, 0xff, 0xfd, 0x60, 0x54, 0x89, 0x1e, 0x78, + 0x39, 0x29, 0x00, 0x40, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x80, 0x00, 0x4c, 0x54, 0x6b, 0x67, 0xbf, + 0x2c, 0x0b, 0x00, 0x01, 0x41, 0x80, 0x00, 0x14, 0x41, 0x82, 0x00, 0x08, 0x48, 0x00, 0x00, 0x10, + 0x41, 0xbe, 0xfd, 0x38, 0x48, 0x00, 0x00, 0x08, 0x40, 0xbe, 0xfd, 0x30, 0x2c, 0x05, 0x00, 0x03, + 0x41, 0x81, 0x00, 0x10, 0x41, 0xa2, 0x00, 0x10, 0x7d, 0xe7, 0x48, 0x2e, 0x4b, 0xff, 0xfd, 0x1c, + 0x7d, 0xe7, 0x49, 0x2e, 0x7c, 0x64, 0x07, 0x34, 0x54, 0x84, 0x1a, 0x78, 0x7d, 0xef, 0x22, 0x14, + 0x4b, 0xff, 0xfd, 0x08, 0x40, 0xbe, 0xfd, 0x04, 0x7c, 0xa7, 0x4a, 0x14, 0x40, 0x92, 0x00, 0x14, + 0x54, 0x64, 0x04, 0x3e, 0x91, 0xe5, 0x00, 0x00, 0x90, 0x85, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0xec, + 0x81, 0x25, 0x00, 0x04, 0x2c, 0x09, 0x00, 0x00, 0x41, 0xa2, 0xfc, 0xe0, 0x39, 0x29, 0xff, 0xff, + 0x91, 0x25, 0x00, 0x04, 0x81, 0xe5, 0x00, 0x00, 0x4b, 0xff, 0xfc, 0xd0, 0x40, 0xbe, 0xfc, 0xcc, + 0x54, 0x6b, 0x16, 0xba, 0x7f, 0x47, 0x5a, 0x14, 0x81, 0x3a, 0x00, 0x00, 0x54, 0x6e, 0x67, 0xbe, + 0x41, 0x92, 0x00, 0x84, 0x2e, 0x05, 0x00, 0x05, 0x40, 0x90, 0x01, 0x74, 0x2e, 0x05, 0x00, 0x03, + 0x40, 0x90, 0x00, 0x90, 0x2e, 0x05, 0x00, 0x01, 0x54, 0x65, 0x87, 0xff, 0x41, 0x82, 0x00, 0x08, + 0x7c, 0x8c, 0x22, 0x14, 0x2f, 0x0e, 0x00, 0x01, 0x40, 0x92, 0x00, 0x24, 0x41, 0xb9, 0x00, 0x18, + 0x41, 0x9a, 0x00, 0x0c, 0x88, 0x84, 0x00, 0x00, 0x48, 0x00, 0x00, 0xf8, 0xa0, 0x84, 0x00, 0x00, + 0x48, 0x00, 0x00, 0xf0, 0x80, 0x84, 0x00, 0x00, 0x48, 0x00, 0x00, 0xe8, 0x54, 0x73, 0xe5, 0x3e, + 0x41, 0xb9, 0x00, 0x20, 0x41, 0x9a, 0x00, 0x10, 0x99, 0x24, 0x00, 0x00, 0x38, 0x84, 0x00, 0x01, + 0x48, 0x00, 0x00, 0x18, 0xb1, 0x24, 0x00, 0x00, 0x38, 0x84, 0x00, 0x02, 0x48, 0x00, 0x00, 0x0c, + 0x91, 0x24, 0x00, 0x00, 0x38, 0x84, 0x00, 0x04, 0x36, 0x73, 0xff, 0xff, 0x40, 0x80, 0xff, 0xd4, + 0x4b, 0xff, 0xfc, 0x38, 0x54, 0x65, 0x87, 0xff, 0x41, 0x82, 0x00, 0x08, 0x7c, 0x84, 0x62, 0x14, + 0x71, 0xc5, 0x00, 0x01, 0x41, 0x82, 0x00, 0x9c, 0x7c, 0x84, 0x4a, 0x14, 0x48, 0x00, 0x00, 0x94, + 0x54, 0x6a, 0x87, 0xbe, 0x54, 0x8e, 0x16, 0xba, 0x7e, 0x67, 0x72, 0x14, 0x40, 0x92, 0x00, 0x08, + 0x3a, 0x6f, 0xff, 0xfc, 0x80, 0x9a, 0x00, 0x00, 0x81, 0x33, 0x00, 0x00, 0x71, 0x4b, 0x00, 0x01, + 0x41, 0x82, 0x00, 0x08, 0x7c, 0x9a, 0x23, 0x78, 0x71, 0x4b, 0x00, 0x02, 0x41, 0x82, 0x00, 0x10, + 0x7d, 0x33, 0x4b, 0x78, 0x40, 0xb2, 0x00, 0x08, 0x7e, 0x6c, 0x9a, 0x14, 0x54, 0x65, 0x67, 0x3f, + 0x2c, 0x05, 0x00, 0x09, 0x40, 0x80, 0x00, 0x54, 0x48, 0x00, 0x00, 0x79, 0x7c, 0x89, 0x22, 0x14, + 0x48, 0x00, 0x00, 0x40, 0x7c, 0x89, 0x21, 0xd6, 0x48, 0x00, 0x00, 0x38, 0x7d, 0x24, 0x23, 0x78, + 0x48, 0x00, 0x00, 0x30, 0x7d, 0x24, 0x20, 0x38, 0x48, 0x00, 0x00, 0x28, 0x7d, 0x24, 0x22, 0x78, + 0x48, 0x00, 0x00, 0x20, 0x7d, 0x24, 0x20, 0x30, 0x48, 0x00, 0x00, 0x18, 0x7d, 0x24, 0x24, 0x30, + 0x48, 0x00, 0x00, 0x10, 0x5d, 0x24, 0x20, 0x3e, 0x48, 0x00, 0x00, 0x08, 0x7d, 0x24, 0x26, 0x30, + 0x90, 0x9a, 0x00, 0x00, 0x4b, 0xff, 0xfb, 0x84, 0x2c, 0x05, 0x00, 0x0a, 0x41, 0x81, 0xfb, 0x7c, + 0xc0, 0x5a, 0x00, 0x00, 0xc0, 0x73, 0x00, 0x00, 0x41, 0x82, 0x00, 0x0c, 0xec, 0x43, 0x10, 0x2a, + 0x48, 0x00, 0x00, 0x08, 0xec, 0x43, 0x00, 0xb2, 0xd0, 0x5a, 0x00, 0x00, 0x4b, 0xff, 0xfb, 0x5c, + 0x7d, 0x48, 0x02, 0xa6, 0x54, 0xa5, 0x1e, 0x78, 0x7d, 0x4a, 0x2a, 0x14, 0x80, 0x9a, 0x00, 0x00, + 0x81, 0x33, 0x00, 0x00, 0x7d, 0x48, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x40, 0xbe, 0xfb, 0x3c, + 0x54, 0x69, 0xc0, 0x3e, 0x7d, 0x8e, 0x63, 0x78, 0x48, 0x00, 0x00, 0x35, 0x41, 0x92, 0x00, 0x0c, + 0x7e, 0x31, 0x22, 0x14, 0x48, 0x00, 0x00, 0x08, 0x7d, 0x29, 0x22, 0x14, 0x54, 0x64, 0xc4, 0x3f, + 0x38, 0xa0, 0x00, 0x00, 0x41, 0x82, 0xfb, 0x14, 0x7d, 0x45, 0x88, 0xae, 0x7d, 0x45, 0x49, 0xae, + 0x38, 0xa5, 0x00, 0x01, 0x7c, 0x05, 0x20, 0x00, 0x4b, 0xff, 0xff, 0xec, 0x2e, 0x8a, 0x00, 0x04, + 0x55, 0x31, 0x36, 0xba, 0x2c, 0x11, 0x00, 0x3c, 0x7e, 0x27, 0x88, 0x2e, 0x40, 0x82, 0x00, 0x08, + 0x7d, 0xd1, 0x73, 0x78, 0x41, 0x96, 0x00, 0x08, 0xa2, 0x31, 0x00, 0x00, 0x55, 0x29, 0x56, 0xba, + 0x2c, 0x09, 0x00, 0x3c, 0x7d, 0x27, 0x48, 0x2e, 0x40, 0x82, 0x00, 0x08, 0x7d, 0xc9, 0x73, 0x78, + 0x41, 0x96, 0x00, 0x08, 0xa1, 0x29, 0x00, 0x00, 0x4e, 0x80, 0x00, 0x20, 0x2c, 0x05, 0x00, 0x04, + 0x40, 0x80, 0x00, 0x28, 0x7c, 0x89, 0x23, 0x78, 0x7d, 0xc3, 0x62, 0x14, 0x55, 0xce, 0x00, 0x3c, + 0x4b, 0xff, 0xff, 0xad, 0x7c, 0x84, 0x20, 0xf8, 0x54, 0x84, 0x04, 0x3e, 0x7d, 0x2b, 0x20, 0x38, + 0x7e, 0x24, 0x20, 0x38, 0x4b, 0xff, 0xfb, 0xbc, 0x54, 0x6b, 0xe4, 0x3e, 0x4b, 0xff, 0xfb, 0xb4, + 0x7c, 0x9a, 0x23, 0x78, 0x54, 0x84, 0x18, 0x38, 0x40, 0x92, 0x00, 0x20, 0x40, 0x9e, 0x00, 0x0c, + 0x7d, 0xe8, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x21, 0x7d, 0xe4, 0x7a, 0x14, 0x39, 0xef, 0x00, 0x07, + 0x55, 0xef, 0x00, 0x38, 0x4b, 0xff, 0xfa, 0x64, 0x2e, 0x05, 0x00, 0x03, 0x41, 0x91, 0x00, 0x5c, + 0x3c, 0xa0, 0x48, 0x00, 0x7d, 0x83, 0x62, 0x14, 0x55, 0x8c, 0x00, 0x3a, 0x40, 0x92, 0x00, 0x20, + 0x40, 0xbe, 0xfa, 0x48, 0x57, 0x44, 0x00, 0x3a, 0x7c, 0x8c, 0x20, 0x50, 0x50, 0x85, 0x01, 0xba, + 0x50, 0x65, 0x07, 0xfe, 0x90, 0xac, 0x00, 0x00, 0x4b, 0xff, 0xfa, 0x30, 0x40, 0xbe, 0xff, 0xbc, + 0x7d, 0x2c, 0x78, 0x50, 0x51, 0x25, 0x01, 0xba, 0x90, 0xac, 0x00, 0x00, 0x39, 0x8c, 0x00, 0x04, + 0x7d, 0x6f, 0x22, 0x14, 0x39, 0x6b, 0xff, 0xfc, 0x7d, 0x2b, 0x60, 0x50, 0x51, 0x25, 0x01, 0xba, + 0x90, 0xab, 0x00, 0x00, 0x4b, 0xff, 0xff, 0x94, 0x2e, 0x05, 0x00, 0x06, 0x41, 0x92, 0x00, 0x28, + 0x4b, 0xff, 0xfb, 0x20, 0x55, 0x8c, 0x84, 0x3e, 0x57, 0x44, 0x84, 0x3e, 0x57, 0x5a, 0x04, 0x3e, + 0x7c, 0x0c, 0x20, 0x00, 0x41, 0x80, 0xfb, 0xa4, 0x7c, 0x0c, 0xd0, 0x00, 0x40, 0x80, 0xfb, 0x9c, + 0x4b, 0xff, 0xf9, 0xd8, 0x57, 0x45, 0xff, 0xfe, 0x68, 0xa5, 0x00, 0x01, 0x71, 0x03, 0x00, 0x01, + 0x7c, 0x05, 0x18, 0x00, 0x41, 0x82, 0x00, 0x1c, 0x51, 0x1a, 0x0f, 0xbc, 0x6b, 0x5a, 0x00, 0x02, + 0x57, 0x45, 0xff, 0xff, 0x41, 0x82, 0x00, 0x08, 0x6b, 0x5a, 0x00, 0x01, 0x93, 0x4f, 0xff, 0xfc, + 0x53, 0x48, 0x07, 0xfe, 0x4b, 0xff, 0xf9, 0xa4, 0x2c, 0x0b, 0x00, 0x00, 0x40, 0x82, 0xf9, 0x94, + 0x40, 0x92, 0x00, 0x0c, 0x39, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x14, 0x54, 0x69, 0x06, 0xff, + 0x40, 0x82, 0x00, 0x08, 0x40, 0x9e, 0x00, 0x10, 0x54, 0x65, 0x67, 0xfe, 0x7d, 0x08, 0x4c, 0x30, + 0x7d, 0x08, 0x2a, 0x78, 0x54, 0x85, 0x00, 0x1f, 0x41, 0x82, 0x00, 0x08, 0x7c, 0xa6, 0x2b, 0x78, + 0x54, 0x85, 0x80, 0x1f, 0x41, 0x82, 0x00, 0x08, 0x7c, 0xb0, 0x2b, 0x78, 0x4b, 0xff, 0xf9, 0x5c, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; const int kenobiwii_size = sizeof(kenobiwii); diff --git a/source/patches/patchcode.c b/source/patches/patchcode.c index 23254d5f..cedda4cc 100644 --- a/source/patches/patchcode.c +++ b/source/patches/patchcode.c @@ -58,35 +58,35 @@ extern void vipatch(u32 address, u32 len); extern u32 regionfreeselect; static const u32 viwiihooks[4] = { - 0x7CE33B78,0x38870034,0x38A70038,0x38C7004C + 0x7CE33B78,0x38870034,0x38A70038,0x38C7004C }; static const u32 multidolpatch1[2] = { - 0x3C03FFB4,0x28004F43 -}; + 0x3C03FFB4,0x28004F43 +}; static const u32 healthcheckhook[2] = { - 0x41810010,0x881D007D -}; + 0x41810010,0x881D007D +}; static const u32 updatecheckhook[3] = { - 0x80650050,0x80850054,0xA0A50058 + 0x80650050,0x80850054,0xA0A50058 }; static const u32 multidolpatch2[2] = { - 0x3F608000, 0x807B0018 + 0x3F608000, 0x807B0018 }; static const u32 recoveryhooks[3] = { - 0xA00100AC,0x5400073E,0x2C00000F + 0xA00100AC,0x5400073E,0x2C00000F }; static const u32 nocopyflag1[3] = { - 0x540007FF, 0x4182001C, 0x80630068 + 0x540007FF, 0x4182001C, 0x80630068 }; static const u32 nocopyflag2[3] = { - 0x540007FF, 0x41820024, 0x387E12E2 + 0x540007FF, 0x41820024, 0x387E12E2 }; // this one is for the GH3 and VC saves @@ -95,177 +95,188 @@ static const u32 nocopyflag2[3] = { //}; static const u32 nocopyflag3[5] = { - 0x2C030000, 0x41820200,0x48000058,0x38610100 + 0x2C030000, 0x41820200,0x48000058,0x38610100 }; // this removes the display warning for no copy VC and GH3 saves static const u32 nocopyflag4[4] = { - 0x80010008, 0x2C000000, 0x4182000C, 0x3BE00001 + 0x80010008, 0x2C000000, 0x4182000C, 0x3BE00001 }; static const u32 nocopyflag5[3] = { - 0x801D0024,0x540007FF,0x41820024 + 0x801D0024,0x540007FF,0x41820024 }; static const u32 movedvdpatch[3] = { - 0x2C040000, 0x41820120, 0x3C608109 + 0x2C040000, 0x41820120, 0x3C608109 }; - + static const u32 regionfreehooks[5] = { - 0x7C600774, 0x2C000001, 0x41820030,0x40800010,0x2C000000 + 0x7C600774, 0x2C000001, 0x41820030,0x40800010,0x2C000000 }; static const u32 fwritepatch[8] = { - 0x9421FFD0,0x7C0802A6,0x90010034,0xBF210014,0x7C9B2378,0x7CDC3378,0x7C7A1B78,0x7CB92B78 // bushing fwrite + 0x9421FFD0,0x7C0802A6,0x90010034,0xBF210014,0x7C9B2378,0x7CDC3378,0x7C7A1B78,0x7CB92B78 // bushing fwrite }; static const u32 kpadhooks[4] = { - 0x9A3F005E,0x38AE0080,0x389FFFFC,0x7E0903A6 + 0x9A3F005E,0x38AE0080,0x389FFFFC,0x7E0903A6 }; static const u32 kpadoldhooks[6] = { - 0x801D0060, 0x901E0060, 0x801D0064, 0x901E0064, 0x801D0068, 0x901E0068 + 0x801D0060, 0x901E0060, 0x801D0064, 0x901E0064, 0x801D0068, 0x901E0068 }; static const u32 joypadhooks[4] = { - 0x3AB50001, 0x3A73000C, 0x2C150004, 0x3B18000C + 0x3AB50001, 0x3A73000C, 0x2C150004, 0x3B18000C }; static const u32 langpatch[3] = { - 0x7C600775, 0x40820010, 0x38000000 + 0x7C600775, 0x40820010, 0x38000000 }; static const u32 vipatchcode[3] = { - 0x4182000C,0x4180001C,0x48000018 + 0x4182000C,0x4180001C,0x48000018 }; static const u32 wpadlibogc[5] = { // 0x38A00140, 0x7C095878, 0x7D600078, 0x901F0010,0x913F0014 // 0x7FA00124, 0x8001001C, 0x83810008, 0x83A1000C,0x7C0803A6 - 0x90A402E0,0x806502E4,0x908502E4,0x2C030000,0x906402E4 + 0x90A402E0,0x806502E4,0x908502E4,0x2C030000,0x906402E4 }; -void dogamehooks(void *addr, u32 len, bool vpatch) { - void *addr_start = addr; - void *addr_end = addr+len; +void dogamehooks(void *addr, u32 len, bool vpatch) +{ + void *addr_start = addr; + void *addr_end = addr+len; - while (addr_start < addr_end) { + while(addr_start < addr_end) + { + + switch(hooktype) + { + + case 0: + + break; + + case 1: + if(memcmp(addr_start, viwiihooks, sizeof(viwiihooks))==0){ + // printf("\n\n\n"); + // printf("found at address %x\n", addr_start); + // sleep(2); + patchhook((u32)addr_start, len); + patched = 1; + hooktype = 1; + } + break; - switch (hooktype) { + case 2: - case 0: + if(memcmp(addr_start, viwiihooks, sizeof(viwiihooks))==0){ + patchhook2((u32)addr_start, len); + } + + break; - break; + // multidol + case 3: - case 1: - if (memcmp(addr_start, viwiihooks, sizeof(viwiihooks))==0) { - // printf("\n\n\n"); - // printf("found at address %x\n", addr_start); - // sleep(2); - patchhook((u32)addr_start, len); - patched = 1; - hooktype = 1; - } - break; - - case 2: - - if (memcmp(addr_start, viwiihooks, sizeof(viwiihooks))==0) { - patchhook2((u32)addr_start, len); - } - - break; - - // multidol - case 3: - - if (memcmp(addr_start, multidolpatch1, sizeof(multidolpatch1))==0) { - multidolpatchone((u32)addr_start, len); - } - if (memcmp(addr_start, multidolpatch2, sizeof(multidolpatch2))==0) { - multidolpatchtwo((u32)addr_start, len); - } - break; + if(memcmp(addr_start, multidolpatch1, sizeof(multidolpatch1))==0){ + multidolpatchone((u32)addr_start, len); + } + if(memcmp(addr_start, multidolpatch2, sizeof(multidolpatch2))==0){ + multidolpatchtwo((u32)addr_start, len); + } + break; } - - if (vpatch) { - if (memcmp(addr_start, vipatchcode, sizeof(vipatchcode))==0) { - vipatch((u32)addr_start, len); - } - } - - if (memcmp(addr_start, langpatch, sizeof(langpatch))==0) { - if (configbytes[0] != 0xCD) { - langvipatch((u32)addr_start, len, configbytes[0]); - } - } - - - addr_start += 4; + + if (vpatch){ + if(memcmp(addr_start, vipatchcode, sizeof(vipatchcode))==0) { + vipatch((u32)addr_start, len); + } + } + + if(memcmp(addr_start, langpatch, sizeof(langpatch))==0) { + if(configbytes[0] != 0xCD){ + langvipatch((u32)addr_start, len, configbytes[0]); + } + } + + + addr_start += 4; } } // Not used yet, for patching DOL once loaded into memory and befor execution -void patchdol(void *addr, u32 len) { +void patchdol(void *addr, u32 len) +{ + + void *addr_start = addr; + void *addr_end = addr+len; - void *addr_start = addr; - void *addr_end = addr+len; - - while (addr_start < addr_end) { - if (memcmp(addr_start, wpadlibogc, sizeof(wpadlibogc))==0) { - // printf("\n\n\n"); - // printf("found at address %x\n", addr_start); - // sleep(10); - // patchhookdol((u32)addr_start, len); - patched = 1; - break; - } - addr_start += 4; - } + while(addr_start < addr_end) + { + if(memcmp(addr_start, wpadlibogc, sizeof(wpadlibogc))==0) { + // printf("\n\n\n"); + // printf("found at address %x\n", addr_start); + // sleep(10); + // patchhookdol((u32)addr_start, len); + patched = 1; + break; + } + addr_start += 4; + } } -void langpatcher(void *addr, u32 len) { +void langpatcher(void *addr, u32 len) +{ + + void *addr_start = addr; + void *addr_end = addr+len; - void *addr_start = addr; - void *addr_end = addr+len; - - while (addr_start < addr_end) { - - if (memcmp(addr_start, langpatch, sizeof(langpatch))==0) { - if (configbytes[0] != 0xCD) { - langvipatch((u32)addr_start, len, configbytes[0]); - } - } - addr_start += 4; - } + while(addr_start < addr_end) + { + + if(memcmp(addr_start, langpatch, sizeof(langpatch))==0) { + if(configbytes[0] != 0xCD){ + langvipatch((u32)addr_start, len, configbytes[0]); + } + } + addr_start += 4; + } } -void patchdebug(void *addr, u32 len) { +void patchdebug(void *addr, u32 len) +{ + + void *addr_start = addr; + void *addr_end = addr+len; - void *addr_start = addr; - void *addr_end = addr+len; + while(addr_start < addr_end) + { + + if(memcmp(addr_start, fwritepatch, sizeof(fwritepatch))==0) { - while (addr_start < addr_end) { - - if (memcmp(addr_start, fwritepatch, sizeof(fwritepatch))==0) { - - memcpy(addr_start,fwrite_patch_bin,fwrite_patch_bin_len); - // apply patch - } - addr_start += 4; - } + memcpy(addr_start,fwrite_patch_bin,fwrite_patch_bin_len); + // apply patch + } + addr_start += 4; + } } -void vidolpatcher(void *addr, u32 len) { +void vidolpatcher(void *addr, u32 len) +{ + + void *addr_start = addr; + void *addr_end = addr+len; - void *addr_start = addr; - void *addr_end = addr+len; - - while (addr_start < addr_end) { - if (memcmp(addr_start, vipatchcode, sizeof(vipatchcode))==0) { - vipatch((u32)addr_start, len); - } - addr_start += 4; - } + while(addr_start < addr_end) + { + if(memcmp(addr_start, vipatchcode, sizeof(vipatchcode))==0) { + vipatch((u32)addr_start, len); + } + addr_start += 4; + } } diff --git a/source/patches/patchcode.h b/source/patches/patchcode.h index a501583d..1d1c1a9e 100644 --- a/source/patches/patchcode.h +++ b/source/patches/patchcode.h @@ -22,19 +22,20 @@ #ifndef __PATCHCODE_H__ #define __PATCHCODE_H__ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif // Globals - u32 hooktype; - int patched; - u8 configbytes[2]; - u32 regionfree; +u32 hooktype; +int patched; +u8 configbytes[2]; +u32 regionfree; // Function prototypes - void dogamehooks(void *addr, u32 len, bool vpatch); - void langpatcher(void *addr, u32 len); - void vidolpatcher(void *addr, u32 len); - void patchdebug(void *addr, u32 len); +void dogamehooks(void *addr, u32 len, bool vpatch); +void langpatcher(void *addr, u32 len); +void vidolpatcher(void *addr, u32 len); +void patchdebug(void *addr, u32 len); diff --git a/source/patches/patchhook.S b/source/patches/patchhook.S index 1d545f35..865e3417 100644 --- a/source/patches/patchhook.S +++ b/source/patches/patchhook.S @@ -1,530 +1,505 @@ .text -.set r0,0; -.set sp,1; -.set r2,2; -.set r3,3; -.set r4,4 -.set r5,5; -.set r6,6; -.set r7,7; -.set r8,8; -.set r9,9 -.set r10,10; -.set r11,11; -.set r12,12; -.set r13,13; -.set r14,14 -.set r15,15; -.set r16,16; -.set r17,17; -.set r18,18; -.set r19,19 -.set r20,20; -.set r21,21; -.set r22,22; -.set r23,23; -.set r24,24 -.set r25,25; -.set r26,26; -.set r27,27; -.set r28,28; -.set r29,29 -.set r30,30; -.set r31,31 +.set r0,0; .set sp,1; .set r2,2; .set r3,3; .set r4,4 +.set r5,5; .set r6,6; .set r7,7; .set r8,8; .set r9,9 +.set r10,10; .set r11,11; .set r12,12; .set r13,13; .set r14,14 +.set r15,15; .set r16,16; .set r17,17; .set r18,18; .set r19,19 +.set r20,20; .set r21,21; .set r22,22; .set r23,23; .set r24,24 +.set r25,25; .set r26,26; .set r27,27; .set r28,28; .set r29,29 +.set r30,30; .set r31,31 .globl patchhook # r3 address patchhook: -mtctr r4 -lis r6, 0x4E80 -ori r6, r6, 0x0020 # blr + mtctr r4 + lis r6, 0x4E80 + ori r6, r6, 0x0020 # blr findblr: -lwz r5, 0(r3) -cmpw r6, r5 -beq writebranch -addi r3, r3, 4 # next word -bdnz findblr # loop length -b exit # stop unhooked game hanging + lwz r5, 0(r3) + cmpw r6, r5 + beq writebranch + addi r3, r3, 4 # next word + bdnz findblr # loop length + b exit # stop unhooked game hanging writebranch: -lis r4, 0x8000 # 800018A0 hook location (source) -ori r4, r4, 0x18A8 -subf r4, r3, r4 # subtract r3 from r4 and place in r4 -lis r5, 0x3FF -ori r5, r5, 0xFFFF # 0x3FFFFFF -and r4, r4, r5 -lis r5, 0x4800 # 0x48000000 -or r4, r4, r5 -stw r4, 0(r3) # result in r3 -dcbf r0, r3 # data cache block flush -icbi r0, r3 + lis r4, 0x8000 # 800018A0 hook location (source) + ori r4, r4, 0x18A8 + subf r4, r3, r4 # subtract r3 from r4 and place in r4 + lis r5, 0x3FF + ori r5, r5, 0xFFFF # 0x3FFFFFF + and r4, r4, r5 + lis r5, 0x4800 # 0x48000000 + or r4, r4, r5 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 exit: -blr # return + blr # return + + .globl patchhook2 # r3 address +patchhook2: + mtctr r4 + lis r6, 0x4E80 + ori r6, r6, 0x0020 # blr +findblr2: + lwz r5, 0(r3) + cmpw r6, r5 + beq writebranch2 + addi r3, r3, 4 # next word + bdnz findblr2 # loop length + b exit2 # stop unhooked game hanging - .globl patchhook2 # r3 address - patchhook2: - mtctr r4 - lis r6, 0x4E80 - ori r6, r6, 0x0020 # blr - findblr2: - lwz r5, 0(r3) - cmpw r6, r5 - beq writebranch2 - addi r3, r3, 4 # next word - bdnz findblr2 # loop length - b exit2 # stop unhooked game hanging +writebranch2: + lis r4, 0x8000 # 81700000 our temp patcher + ori r4, r4, 0x18a8 + subf r4, r3, r4 # subtract r3 from r4 and place in r4 + lis r5, 0x3FF + ori r5, r5, 0xFFFF # 0x3FFFFFF + and r4, r4, r5 + lis r5, 0x4800 # 0x48000000 + or r4, r4, r5 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exit2: + blr # return - writebranch2: - lis r4, 0x8000 # 81700000 our temp patcher - ori r4, r4, 0x18a8 - subf r4, r3, r4 # subtract r3 from r4 and place in r4 - lis r5, 0x3FF - ori r5, r5, 0xFFFF # 0x3FFFFFF - and r4, r4, r5 - lis r5, 0x4800 # 0x48000000 - or r4, r4, r5 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exit2: - blr # return +.globl patchhook3 # r3 address +patchhook3: + mtctr r4 + lis r6, 0x4BFF + ori r6, r6, 0xE955 # blr +findbne: + lwz r5, 0(r3) + cmpw r6, r5 + beq writebl + addi r3, r3, 4 # next word + bdnz findbne # loop length + b exit3 # stop unhooked game hanging - .globl patchhook3 # r3 address - patchhook3: - mtctr r4 - lis r6, 0x4BFF - ori r6, r6, 0xE955 # blr - findbne: - lwz r5, 0(r3) - cmpw r6, r5 - beq writebl - addi r3, r3, 4 # next word - bdnz findbne # loop length - b exit3 # stop unhooked game hanging +writebl: + lis r4, 0x4BFF # 81700000 our temp patcher + ori r4, r4, 0xEA91 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exit3: + blr # return - writebl: - lis r4, 0x4BFF # 81700000 our temp patcher - ori r4, r4, 0xEA91 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exit3: - blr # return +.globl multidolpatchone # r3 address +multidolpatchone: + mtctr r4 + lis r6, 0x3800 + ori r6, r6, 0x0001 # (li r0,1) +findmulti: + lwz r5, 0(r3) + cmpw r6, r5 + beq writemulti + subi r3, r3, 4 # go back + bdnz findmulti # loop length + b exit5 # stop unhooked game hanging - .globl multidolpatchone # r3 address - multidolpatchone: - mtctr r4 - lis r6, 0x3800 - ori r6, r6, 0x0001 # (li r0,1) - findmulti: - lwz r5, 0(r3) - cmpw r6, r5 - beq writemulti - subi r3, r3, 4 # go back - bdnz findmulti # loop length - b exit5 # stop unhooked game hanging +writemulti: + lis r4, 0x8170 # 81700000 + ori r4, r4, 0x0020 + subf r18, r3, r4 # subf r18,(source),(dest) + lis r6, 0x4800 + ori r6,r6,1 + rlwimi r6,r18,0,6,29 + stw r6,0(r3) + stw r6,0(r19) + stw r3,4(r19) + dcbf r0, r3 + sync + icbi r0, r3 + isync +exit5: + blr # return - writemulti: - lis r4, 0x8170 # 81700000 - ori r4, r4, 0x0020 - subf r18, r3, r4 # subf r18,(source),(dest) - lis r6, 0x4800 - ori r6,r6,1 - rlwimi r6,r18,0,6,29 - stw r6,0(r3) - stw r6,0(r19) - stw r3,4(r19) - dcbf r0, r3 - sync - icbi r0, r3 - isync - exit5: - blr # return +.globl multidolpatchtwo # r3 address +multidolpatchtwo: + mtctr r4 + lis r6, 0x3F60 + ori r6, r6, 0x8000 # (lis r27,-32768) +findmulti2: + lwz r5, 0(r3) + cmpw r6, r5 + beq writemulti2 + addi r3, r3, 4 # go forward + bdnz findmulti2 # loop length + b exit6 # stop unhooked game hanging - .globl multidolpatchtwo # r3 address - multidolpatchtwo: - mtctr r4 - lis r6, 0x3F60 - ori r6, r6, 0x8000 # (lis r27,-32768) - findmulti2: - lwz r5, 0(r3) - cmpw r6, r5 - beq writemulti2 - addi r3, r3, 4 # go forward - bdnz findmulti2 # loop length - b exit6 # stop unhooked game hanging - - writemulti2: - lis r4, 0x8170 # 81700020 - ori r4, r4, 0x0000 - subf r18, r3, r4 # subf r18,(source),(dest) - lis r6, 0x4800 - ori r6,r6,1 - rlwimi r6,r18,0,6,29 - stw r6,0(r3) - stw r6,0(r19) - stw r3,4(r19) - dcbf r0, r3 - sync - icbi r0, r3 - isync - exit6: - blr # return - - .globl multidolhook # r3 address - multidolhook: - lis r4, 0x8000 # 80001000 hook location (source) - ori r4, r4, 0x1000 - subf r4, r3, r4 # subtract r3 from r4 and place in r4 - lis r5, 0x3FF - ori r5, r5, 0xFFFF # 0x3FFFFFF - and r4, r4, r5 - lis r5, 0x4800 # 0x48000000 - or r4, r4, r5 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - blr # return +writemulti2: + lis r4, 0x8170 # 81700020 + ori r4, r4, 0x0000 + subf r18, r3, r4 # subf r18,(source),(dest) + lis r6, 0x4800 + ori r6,r6,1 + rlwimi r6,r18,0,6,29 + stw r6,0(r3) + stw r6,0(r19) + stw r3,4(r19) + dcbf r0, r3 + sync + icbi r0, r3 + isync +exit6: + blr # return + +.globl multidolhook # r3 address +multidolhook: + lis r4, 0x8000 # 80001000 hook location (source) + ori r4, r4, 0x1000 + subf r4, r3, r4 # subtract r3 from r4 and place in r4 + lis r5, 0x3FF + ori r5, r5, 0xFFFF # 0x3FFFFFF + and r4, r4, r5 + lis r5, 0x4800 # 0x48000000 + or r4, r4, r5 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 + blr # return - .globl langvipatch # r3 address, r4 len, r5 lang byte - langvipatch: - mtctr r4 - lis r6, 0x8861 - ori r6, r6, 0x0008 # lbz r3, 8(sp) - findlang: - lwz r7, 0(r3) - cmpw r6, r7 - beq patchlang - addi r3, r3, 4 # next word - bdnz findlang # loop length - b exitlang # stop unhooked game hanging +.globl langvipatch # r3 address, r4 len, r5 lang byte +langvipatch: + mtctr r4 + lis r6, 0x8861 + ori r6, r6, 0x0008 # lbz r3, 8(sp) +findlang: + lwz r7, 0(r3) + cmpw r6, r7 + beq patchlang + addi r3, r3, 4 # next word + bdnz findlang # loop length + b exitlang # stop unhooked game hanging - patchlang: +patchlang: + + lis r4, 0x3860 # 0x38600001 li %r3, 1 # eng + add r4, r4, r5 +gofinal: + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitlang: + blr # return + +.globl vipatch # r3 address +vipatch: + mtctr r4 + lis r6, 0x5400 + ori r6, r6, 0xFFFE +findvi: + lwz r5, 0(r3) + cmpw r6, r5 + beq patchvi + addi r3, r3, 4 # next word + bdnz findvi # loop length + b exitvi # stop unhooked game hanging - lis r4, 0x3860 # 0x38600001 li %r3, 1 # eng - add r4, r4, r5 - gofinal: - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitlang: - blr # return +patchvi: + lis r4, 0x8000 + ori r4, r4, 0x0003 + lbz r5, 0(r4) + cmpwi r5, 0x45 # USA + beq patchusa + cmpwi r5, 0x4A + beq patchjap2 # JAP + b exitvi +patchjap2: + lis r4, 0x3800 + ori r4, r4, 0x0001 + b gofinal2 +patchusa: + lis r4, 0x3800 + ori r4, r4, 0x0000 +gofinal2: + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitvi: + blr # return - .globl vipatch # r3 address - vipatch: - mtctr r4 - lis r6, 0x5400 - ori r6, r6, 0xFFFE - findvi: - lwz r5, 0(r3) - cmpw r6, r5 - beq patchvi - addi r3, r3, 4 # next word - bdnz findvi # loop length - b exitvi # stop unhooked game hanging +.globl regionfreejap # r3 address +regionfreejap: + mtctr r4 + lis r6, 0x2C1B + ori r6, r6, 0x0000 # blr +findjap: + lwz r5, 0(r3) + cmpw r6, r5 + beq writenop + addi r3, r3, 4 # next word + bdnz findjap # loop length + b exitjap # stop unhooked game hanging - patchvi: - lis r4, 0x8000 - ori r4, r4, 0x0003 - lbz r5, 0(r4) - cmpwi r5, 0x45 # USA - beq patchusa - cmpwi r5, 0x4A - beq patchjap2 # JAP - b exitvi - patchjap2: - lis r4, 0x3800 - ori r4, r4, 0x0001 - b gofinal2 - patchusa: - lis r4, 0x3800 - ori r4, r4, 0x0000 - gofinal2: - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitvi: - blr # return +writenop: + addi r3, r3, 4 # next word + lis r4, 0x6000 # nop + ori r4, r4, 0x0000 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitjap: + blr # return - .globl regionfreejap # r3 address - regionfreejap: - mtctr r4 - lis r6, 0x2C1B - ori r6, r6, 0x0000 # blr - findjap: - lwz r5, 0(r3) - cmpw r6, r5 - beq writenop - addi r3, r3, 4 # next word - bdnz findjap # loop length - b exitjap # stop unhooked game hanging +.globl regionfreeusa # r3 address +regionfreeusa: + mtctr r4 + lis r6, 0x281B + ori r6, r6, 0x0001 # blr +findusa: + lwz r5, 0(r3) + cmpw r6, r5 + beq writenop1 + addi r3, r3, 4 # next word + bdnz findusa # loop length + b exitusa # stop unhooked game hanging - writenop: - addi r3, r3, 4 # next word - lis r4, 0x6000 # nop - ori r4, r4, 0x0000 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitjap: - blr # return +writenop1: + addi r3, r3, 4 # next word + lis r4, 0x6000 # nop + ori r4, r4, 0x0000 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitusa: + blr # return - .globl regionfreeusa # r3 address - regionfreeusa: - mtctr r4 - lis r6, 0x281B - ori r6, r6, 0x0001 # blr - findusa: - lwz r5, 0(r3) - cmpw r6, r5 - beq writenop1 - addi r3, r3, 4 # next word - bdnz findusa # loop length - b exitusa # stop unhooked game hanging +.globl regionfreepal # r3 address +regionfreepal: + mtctr r4 + lis r6, 0x281B + ori r6, r6, 0x0002 # blr +findpal: + lwz r5, 0(r3) + cmpw r6, r5 + beq writenop2 + addi r3, r3, 4 # next word + bdnz findpal # loop length + b exitpal # stop unhooked game hanging - writenop1: - addi r3, r3, 4 # next word - lis r4, 0x6000 # nop - ori r4, r4, 0x0000 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitusa: - blr # return +writenop2: + addi r3, r3, 4 # next word + lis r4, 0x6000 # nop + ori r4, r4, 0x0000 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 - .globl regionfreepal # r3 address - regionfreepal: - mtctr r4 - lis r6, 0x281B - ori r6, r6, 0x0002 # blr - findpal: - lwz r5, 0(r3) - cmpw r6, r5 - beq writenop2 - addi r3, r3, 4 # next word - bdnz findpal # loop length - b exitpal # stop unhooked game hanging + lis r6, 0x4082 + ori r6, r6, 0x001C # bne loc_81377A2C +findextra: #this is just the bne to b patch + lwz r5, 0(r3) + cmpw r6, r5 + beq writeb + addi r3, r3, 4 # next word + bdnz findextra # loop length + b exitpal # stop unhooked game hanging - writenop2: - addi r3, r3, 4 # next word - lis r4, 0x6000 # nop - ori r4, r4, 0x0000 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 +writeb: + addi r3, r3, 4 # next word + lis r4, 0x4800 + ori r4, r4, 0x001c # b loc_81377A2C + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitpal: + blr # return - lis r6, 0x4082 - ori r6, r6, 0x001C # bne loc_81377A2C - findextra: #this is just the bne to b patch - lwz r5, 0(r3) - cmpw r6, r5 - beq writeb - addi r3, r3, 4 # next word - bdnz findextra # loop length - b exitpal # stop unhooked game hanging +.globl removehealthcheck # r3 address +removehealthcheck: + mtctr r4 + lis r6, 0x4182 + ori r6, r6, 0x004C # blr +findhe: + lwz r5, 0(r3) + cmpw r6, r5 + beq writebhe + addi r3, r3, 4 # next word + bdnz findhe # loop length + b exithe # stop unhooked game hanging - writeb: - addi r3, r3, 4 # next word - lis r4, 0x4800 - ori r4, r4, 0x001c # b loc_81377A2C - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitpal: - blr # return +writebhe: + lis r4, 0x6000 + ori r4, r4, 0x0000 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exithe: + blr # return - .globl removehealthcheck # r3 address - removehealthcheck: - mtctr r4 - lis r6, 0x4182 - ori r6, r6, 0x004C # blr - findhe: - lwz r5, 0(r3) - cmpw r6, r5 - beq writebhe - addi r3, r3, 4 # next word - bdnz findhe # loop length - b exithe # stop unhooked game hanging + - writebhe: - lis r4, 0x6000 - ori r4, r4, 0x0000 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exithe: - blr # return +.globl patchupdatecheck # r3 address +patchupdatecheck: + mtctr r4 + lis r6, 0x4082 + ori r6, r6, 0x0020 # blr +finduc: + lwz r5, 0(r3) + cmpw r6, r5 + beq writenopuc + addi r3, r3, 4 # next word + bdnz finduc # loop length + b exituc # stop unhooked game hanging - - - .globl patchupdatecheck # r3 address - patchupdatecheck: - mtctr r4 - lis r6, 0x4082 - ori r6, r6, 0x0020 # blr - finduc: - lwz r5, 0(r3) - cmpw r6, r5 - beq writenopuc - addi r3, r3, 4 # next word - bdnz finduc # loop length - b exituc # stop unhooked game hanging - - writenopuc: - lis r4, 0x6000 - ori r4, r4, 0x0000 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exituc: - blr # return +writenopuc: + lis r4, 0x6000 + ori r4, r4, 0x0000 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exituc: + blr # return - .globl copyflagcheck1 # r3 address - copyflagcheck1: - mtctr r4 - lis r6, 0x5400 - ori r6, r6, 0x07FF - findncf1: - lwz r5, 0(r3) - cmpw r6, r5 - beq writencf1 - subi r3, r3, 4 # next word - bdnz findncf1 # loop length - b exitncf1 # stop unhooked game hanging +.globl copyflagcheck1 # r3 address +copyflagcheck1: + mtctr r4 + lis r6, 0x5400 + ori r6, r6, 0x07FF +findncf1: + lwz r5, 0(r3) + cmpw r6, r5 + beq writencf1 + subi r3, r3, 4 # next word + bdnz findncf1 # loop length + b exitncf1 # stop unhooked game hanging - writencf1: - lis r4, 0x7C00 - ori r4, r4, 0x0000 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitncf1: - blr # return +writencf1: + lis r4, 0x7C00 + ori r4, r4, 0x0000 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitncf1: + blr # return - .globl copyflagcheck2 # r3 address - copyflagcheck2: - mtctr r4 - lis r6, 0x5400 - ori r6, r6, 0x07FF - findncf2: - lwz r5, 0(r3) - cmpw r6, r5 - beq writencf2 - subi r3, r3, 4 # next word - bdnz findncf2 # loop length - b exitncf2 # stop unhooked game hanging +.globl copyflagcheck2 # r3 address +copyflagcheck2: + mtctr r4 + lis r6, 0x5400 + ori r6, r6, 0x07FF +findncf2: + lwz r5, 0(r3) + cmpw r6, r5 + beq writencf2 + subi r3, r3, 4 # next word + bdnz findncf2 # loop length + b exitncf2 # stop unhooked game hanging - writencf2: - lis r4, 0x7C00 - ori r4, r4, 0x0000 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitncf2: - blr # return +writencf2: + lis r4, 0x7C00 + ori r4, r4, 0x0000 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitncf2: + blr # return - .globl copyflagcheck3 # r3 address - copyflagcheck3: - findncf3: - addi r3, r3, 20 # go back one dword (4 bytes) - lwz r5, 0(r3) - writencf3: - lis r4, 0x3860 - ori r4, r4, 0x0001 # li r3,1 - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitncf3: - blr # return +.globl copyflagcheck3 # r3 address +copyflagcheck3: +findncf3: + addi r3, r3, 20 # go back one dword (4 bytes) + lwz r5, 0(r3) +writencf3: + lis r4, 0x3860 + ori r4, r4, 0x0001 # li r3,1 + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitncf3: + blr # return - .globl copyflagcheck4 # r3 address - copyflagcheck4: - mtctr r4 - lis r6, 0x3BE0 - ori r6, r6, 0x0001 # li r31,1 - findncf4: - lwz r5, 0(r3) - cmpw r6, r5 - beq writencf4 - addi r3, r3, 4 # next word - bdnz findncf4 # loop length - b exitncf4 # stop unhooked game hanging +.globl copyflagcheck4 # r3 address +copyflagcheck4: + mtctr r4 + lis r6, 0x3BE0 + ori r6, r6, 0x0001 # li r31,1 +findncf4: + lwz r5, 0(r3) + cmpw r6, r5 + beq writencf4 + addi r3, r3, 4 # next word + bdnz findncf4 # loop length + b exitncf4 # stop unhooked game hanging - writencf4: - lis r4, 0x3BE0 - ori r4, r4, 0x0000 # change this to 3BE00000 (li r31,0) - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitncf4: - blr # return +writencf4: + lis r4, 0x3BE0 + ori r4, r4, 0x0000 # change this to 3BE00000 (li r31,0) + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitncf4: + blr # return - .globl copyflagcheck5 # r3 address - copyflagcheck5: - mtctr r4 - lis r6, 0x4182 - ori r6, r6, 0x0024 # beq loc_8134AA60 - findncf5: - lwz r5, 0(r3) - cmpw r6, r5 - beq writencf5 - addi r3, r3, 4 # next word - bdnz findncf5 # loop length - b exitncf5 # stop unhooked game hanging +.globl copyflagcheck5 # r3 address +copyflagcheck5: + mtctr r4 + lis r6, 0x4182 + ori r6, r6, 0x0024 # beq loc_8134AA60 +findncf5: + lwz r5, 0(r3) + cmpw r6, r5 + beq writencf5 + addi r3, r3, 4 # next word + bdnz findncf5 # loop length + b exitncf5 # stop unhooked game hanging - writencf5: -#addi r3, r3, 8 # skip 2 +writencf5: + #addi r3, r3, 8 # skip 2 + + lis r4, 0x801D + ori r4, r4, 0x0024 # change to 801D0024 (lwz r0,36(r29)) + stw r4, 0(r3) + dcbf r0, r3 + icbi r0, r3 + + addi r3, r3, 4 # next word - lis r4, 0x801D - ori r4, r4, 0x0024 # change to 801D0024 (lwz r0,36(r29)) - stw r4, 0(r3) - dcbf r0, r3 - icbi r0, r3 + lis r4, 0x5400 + ori r4, r4, 0x003C # change to 5400003C (rlwinm r0,r0,0,0,30) + stw r4, 0(r3) + dcbf r0, r3 + icbi r0, r3 - addi r3, r3, 4 # next word + addi r3, r3, 4 # next word - lis r4, 0x5400 - ori r4, r4, 0x003C # change to 5400003C (rlwinm r0,r0,0,0,30) - stw r4, 0(r3) - dcbf r0, r3 - icbi r0, r3 + lis r4, 0x901D + ori r4, r4, 0x0024 # change to 901D0024 (stw r0,36(r29)) + stw r4, 0(r3) + dcbf r0, r3 + icbi r0, r3 - addi r3, r3, 4 # next word + addi r3, r3, 4 # next word - lis r4, 0x901D - ori r4, r4, 0x0024 # change to 901D0024 (stw r0,36(r29)) - stw r4, 0(r3) - dcbf r0, r3 - icbi r0, r3 + lis r4, 0x4800 + ori r4, r4, 0x0018 # change to 48000018 (b 0x8134aa60) + stw r4, 0(r3) + dcbf r0, r3 + icbi r0, r3 +exitncf5: + blr # return - addi r3, r3, 4 # next word - - lis r4, 0x4800 - ori r4, r4, 0x0018 # change to 48000018 (b 0x8134aa60) - stw r4, 0(r3) - dcbf r0, r3 - icbi r0, r3 - exitncf5: - blr # return - - .globl movedvdhooks # r3 address - movedvdhooks: - lis r6, 0x4182 - ori r6, r6, 0x0120 # beq loc_813A7938 - findmd1: - addi r3, r3, 4 # next word - lwz r5, 0(r3) - writemd1: - lis r4, 0x6000 - ori r4, r4, 0x0000 # nop - stw r4, 0(r3) # result in r3 - dcbf r0, r3 # data cache block flush - icbi r0, r3 - exitmd1: - blr # return +.globl movedvdhooks # r3 address +movedvdhooks: + lis r6, 0x4182 + ori r6, r6, 0x0120 # beq loc_813A7938 +findmd1: + addi r3, r3, 4 # next word + lwz r5, 0(r3) +writemd1: + lis r4, 0x6000 + ori r4, r4, 0x0000 # nop + stw r4, 0(r3) # result in r3 + dcbf r0, r3 # data cache block flush + icbi r0, r3 +exitmd1: + blr # return diff --git a/source/patches/wip.c b/source/patches/wip.c index 7fa38e53..2ec25094 100644 --- a/source/patches/wip.c +++ b/source/patches/wip.c @@ -9,108 +9,120 @@ u32 doltableoffset[64]; u32 doltablelength[64]; u32 doltableentries; -void wipreset() { - doltableentries = 0; +void wipreset() +{ + doltableentries = 0; } -void wipregisteroffset(u32 dst, u32 len) { - doltableoffset[doltableentries] = dst; - doltablelength[doltableentries] = len; - doltableentries++; +void wipregisteroffset(u32 dst, u32 len) +{ + doltableoffset[doltableentries] = dst; + doltablelength[doltableentries] = len; + doltableentries++; } -void patchu8(u32 offset, u8 value) { - u32 i = 0; - u32 tempoffset = 0; +void patchu8(u32 offset, u8 value) +{ + u32 i = 0; + u32 tempoffset = 0; - while ((doltablelength[i] <= offset-tempoffset) && (i+1 < doltableentries)) { - tempoffset+=doltablelength[i]; - i++; - } - if (offset-tempoffset < doltablelength[i]) { - *(u8 *)(offset-tempoffset+doltableoffset[i]) = value; - } + while ((doltablelength[i] <= offset-tempoffset) && (i+1 < doltableentries)) + { + tempoffset+=doltablelength[i]; + i++; + } + if (offset-tempoffset < doltablelength[i]) + { + *(u8 *)(offset-tempoffset+doltableoffset[i]) = value; + } } void wipparsebuffer(u8 *buffer, u32 length) // The buffer needs a 0 at the end to properly terminate the string functions { - u32 pos = 0; - u32 offset; - char buf[10]; + u32 pos = 0; + u32 offset; + char buf[10]; + + while (pos < length) + { + if ( *(char *)(buffer + pos) != '#' && *(char *)(buffer + pos) != ';' && *(char *)(buffer + pos) != 10 && *(char *)(buffer + pos) != 13 && *(char *)(buffer + pos) != 32 && *(char *)(buffer + pos) != 0 ) + { + memcpy(buf, (char *)(buffer + pos), 8); + buf[8] = 0; + offset = strtol(buf,NULL,16); - while (pos < length) { - if ( *(char *)(buffer + pos) != '#' && *(char *)(buffer + pos) != ';' && *(char *)(buffer + pos) != 10 && *(char *)(buffer + pos) != 13 && *(char *)(buffer + pos) != 32 && *(char *)(buffer + pos) != 0 ) { - memcpy(buf, (char *)(buffer + pos), 8); - buf[8] = 0; - offset = strtol(buf,NULL,16); - - pos += (u32)strchr((char *)(buffer + pos), 32)-(u32)(buffer + pos) + 1; - pos += (u32)strchr((char *)(buffer + pos), 32)-(u32)(buffer + pos) + 1; - - while (*(char *)(buffer + pos) != 10 && *(char *)(buffer + pos) != 13 && *(char *)(buffer + pos) != 0) { - memcpy(buf, (char *)(buffer + pos), 2); - buf[2] = 0; - - patchu8(offset, strtol(buf,NULL,16)); - offset++; - pos +=2; - } - } - if (strchr((char *)(buffer + pos), 10) == NULL) { - return; - } else { - pos += (u32)strchr((char *)(buffer + pos), 10)-(u32)(buffer + pos) + 1; - } - } + pos += (u32)strchr((char *)(buffer + pos), 32)-(u32)(buffer + pos) + 1; + pos += (u32)strchr((char *)(buffer + pos), 32)-(u32)(buffer + pos) + 1; + + while (*(char *)(buffer + pos) != 10 && *(char *)(buffer + pos) != 13 && *(char *)(buffer + pos) != 0) + { + memcpy(buf, (char *)(buffer + pos), 2); + buf[2] = 0; + + patchu8(offset, strtol(buf,NULL,16)); + offset++; + pos +=2; + } + } + if (strchr((char *)(buffer + pos), 10) == NULL) + { + return; + } else + { + pos += (u32)strchr((char *)(buffer + pos), 10)-(u32)(buffer + pos) + 1; + } + } } -u32 do_wip_code(u8 *gameid) { - FILE *fp; - u32 filesize; - char filepath[150]; - memset(filepath, 0, 150); - u8 *wipCode; +u32 do_wip_code(u8 *gameid) +{ + FILE *fp; + u32 filesize; + char filepath[150]; + memset(filepath, 0, 150); + u8 *wipCode; - sprintf(filepath, "%s%6s", Settings.WipCodepath, gameid); - filepath[strlen(Settings.WipCodepath)+6] = '.'; - filepath[strlen(Settings.WipCodepath)+7] = 'w'; - filepath[strlen(Settings.WipCodepath)+8] = 'i'; - filepath[strlen(Settings.WipCodepath)+9] = 'p'; + sprintf(filepath, "%s%6s", Settings.WipCodepath, gameid); + filepath[strlen(Settings.WipCodepath)+6] = '.'; + filepath[strlen(Settings.WipCodepath)+7] = 'w'; + filepath[strlen(Settings.WipCodepath)+8] = 'i'; + filepath[strlen(Settings.WipCodepath)+9] = 'p'; - fp = fopen(filepath, "rb"); - if (!fp) { - memset(filepath, 0, 150); - sprintf(filepath, "%s%3s", Settings.WipCodepath, gameid + 1); - filepath[strlen(Settings.WipCodepath)+3] = '.'; - filepath[strlen(Settings.WipCodepath)+4] = 'w'; - filepath[strlen(Settings.WipCodepath)+5] = 'i'; - filepath[strlen(Settings.WipCodepath)+6] = 'p'; - fp = fopen(filepath, "rb"); + fp = fopen(filepath, "rb"); + if (!fp) { + memset(filepath, 0, 150); + sprintf(filepath, "%s%3s", Settings.WipCodepath, gameid + 1); + filepath[strlen(Settings.WipCodepath)+3] = '.'; + filepath[strlen(Settings.WipCodepath)+4] = 'w'; + filepath[strlen(Settings.WipCodepath)+5] = 'i'; + filepath[strlen(Settings.WipCodepath)+6] = 'p'; + fp = fopen(filepath, "rb"); + + if (!fp) { + return -1; + } + } - if (!fp) { - return -1; - } - } + if (fp) { + u32 ret = 0; - if (fp) { - u32 ret = 0; - - fseek(fp, 0, SEEK_END); - filesize = ftell(fp); - - wipCode = malloc(filesize + 1); - wipCode[filesize] = 0; // Wip code functions need a 0 termination - - fseek(fp, 0, SEEK_SET); - ret = fread(wipCode, 1, filesize, fp); - fclose(fp); - - if (ret == filesize) { - // Apply wip patch - wipparsebuffer(wipCode, filesize + 1); - return 0; - } - } - return -2; + fseek(fp, 0, SEEK_END); + filesize = ftell(fp); + + wipCode = malloc(filesize + 1); + wipCode[filesize] = 0; // Wip code functions need a 0 termination + + fseek(fp, 0, SEEK_SET); + ret = fread(wipCode, 1, filesize, fp); + fclose(fp); + + if (ret == filesize) + { + // Apply wip patch + wipparsebuffer(wipCode, filesize + 1); + return 0; + } + } + return -2; } diff --git a/source/prompts/DiscBrowser.cpp b/source/prompts/DiscBrowser.cpp index 073725ba..d05efae6 100644 --- a/source/prompts/DiscBrowser.cpp +++ b/source/prompts/DiscBrowser.cpp @@ -35,62 +35,63 @@ extern u8 mountMethod; *Disk Browser *********************************************************************************/ int DiscBrowse(struct discHdr * header) { - gprintf("\nDiscBrowser() started"); + gprintf("\nDiscBrowser() started"); bool exit = false; int ret, choice; u64 offset; - HaltGui(); - if (!mountMethod) { - ret = Disc_SetUSB(header->id); - if (ret < 0) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Could not set USB."), tr("OK")); - return ret; - } - } - - ret = Disc_Open(); + HaltGui(); + if (!mountMethod) + { + ret = Disc_SetUSB(header->id); + if (ret < 0) { + ResumeGui(); + WindowPrompt(tr("ERROR:"), tr("Could not set USB."), tr("OK")); + return ret; + } + } + + ret = Disc_Open(); if (ret < 0) { - ResumeGui(); + ResumeGui(); WindowPrompt(tr("ERROR:"), tr("Could not open Disc"), tr("OK")); return ret; } ret = __Disc_FindPartition(&offset); if (ret < 0) { - ResumeGui(); + ResumeGui(); WindowPrompt(tr("ERROR:"), tr("Could not find a WBFS partition."), tr("OK")); return ret; } ret = WDVD_OpenPartition(offset); if (ret < 0) { - ResumeGui(); + ResumeGui(); WindowPrompt(tr("ERROR:"), tr("Could not open WBFS partition"), tr("OK")); return ret; } - - int *buffer = (int*)allocate_memory(0x20); + + int *buffer = (int*)allocate_memory(0x20); if (buffer == NULL) { - ResumeGui(); + ResumeGui(); WindowPrompt(tr("ERROR:"), tr("Not enough free memory."), tr("OK")); return -1; } ret = WDVD_Read(buffer, 0x20, 0x420); if (ret < 0) { - ResumeGui(); + ResumeGui(); WindowPrompt(tr("ERROR:"), tr("Could not read the disc."), tr("OK")); return ret; } - - void *fstbuffer = allocate_memory(buffer[2]*4); + + void *fstbuffer = allocate_memory(buffer[2]*4); FST_ENTRY *fst = (FST_ENTRY *)fstbuffer; if (fst == NULL) { - ResumeGui(); + ResumeGui(); WindowPrompt(tr("ERROR:"), tr("Not enough free memory."), tr("OK")); free(buffer); return -1; @@ -99,13 +100,13 @@ int DiscBrowse(struct discHdr * header) { ret = WDVD_Read(fstbuffer, buffer[2]*4, buffer[1]*4); if (ret < 0) { - ResumeGui(); + ResumeGui(); WindowPrompt(tr("ERROR:"), tr("Could not read the disc."), tr("OK")); free(buffer); free(fstbuffer); return ret; } - ResumeGui(); + ResumeGui(); free(buffer); WDVD_Reset(); @@ -133,7 +134,7 @@ int DiscBrowse(struct discHdr * header) { dolfilecount++; } } - gprintf("\n%i alt dols found",dolfilecount); + gprintf("\n%i alt dols found",dolfilecount); if (dolfilecount <= 0) { WindowPrompt(tr("ERROR"), tr("No DOL file found on disc."), tr("OK")); free(fstbuffer); @@ -141,9 +142,9 @@ int DiscBrowse(struct discHdr * header) { } GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; @@ -217,13 +218,13 @@ int DiscBrowse(struct discHdr * header) { if (choice) { //ret = offsetselect[ret]; strlcpy(alternatedname, temp, sizeof(alternatedname)); - exit = true; + exit = true; } } if (cancelBtn.GetState() == STATE_CLICKED) { - ret = 696969; - exit = true; + ret = 696969; + exit = true; } } @@ -239,251 +240,251 @@ int DiscBrowse(struct discHdr * header) { int autoSelectDol(const char *id, bool force) { - gprintf("\nautoSelectDol() started"); - - char id4[10]; - sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); + gprintf("\nautoSelectDol() started"); + char id4[10]; + sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); + ////// games that can be forced (always need alt dol) - //Boogie + //Boogie if (strcmp(id,"RBOP69") == 0) return 675;//previous value was 657 if (strcmp(id,"RBOE69") == 0) return 675;//starstremr - - //Fifa 08 + + //Fifa 08 if (strcmp(id,"RF8E69") == 0) return 439;//from isostar if (strcmp(id,"RF8P69") == 0) return 463;//from isostar if (strcmp(id,"RF8X69") == 0) return 464;//from isostar - - //Madden NFL07 + + //Madden NFL07 if (strcmp(id,"RMDP69") == 0) return 39;//from isostar - - //Madden NFL08 + + //Madden NFL08 if (strcmp(id,"RNFP69") == 0) return 1079;//from isostar - - //Medal of Honor: Heroes 2 - if (strcmp(id,"RM2X69") == 0)return 601;//dj_skual - if (strcmp(id,"RM2P69") == 0)return 517;//MZottel - if (strcmp(id,"RM2E69") == 0) return 492;//Old8oy - - //Mortal Kombat + + //Medal of Honor: Heroes 2 + if (strcmp(id,"RM2X69") == 0)return 601;//dj_skual + if (strcmp(id,"RM2P69") == 0)return 517;//MZottel + if (strcmp(id,"RM2E69") == 0) return 492;//Old8oy + + //Mortal Kombat if (strcmp(id,"RKMP5D") == 0) return 290;//from isostar if (strcmp(id,"RKME5D") == 0) return 290;//starstremr - //NBA 08 + //NBA 08 if (strcmp(id,"RNBX69") == 0) return 964;//from isostar - //Pangya! Golf with Style + //Pangya! Golf with Style if (strcmp(id,"RPYP9B") == 0) return 12490;//from isostar - - //Redsteel + + //Redsteel if (strcmp(id,"REDP41") == 0) return 1957;//from isostar if (strcmp(id,"REDE41") == 0) return 1957;//starstremr - //SSX + //SSX if (strcmp(id,"RSXP69") == 0) return 377;//previous value was 337 if (strcmp(id,"RSXE69") == 0) return 377;//previous value was 337 - - //Wii Sports Resort, needs alt dol one time only, to show the Motion Plus video - //if (strcmp(id,"RZTP01") == 0 && CheckForSave(id4)==0) return 952;//from isostar - //if (strcmp(id,"RZTE01") == 0 && CheckForSave(id4)==0) return 674;//from starstremr - //as well as Grand Slam Tennis, Tiger Woods 10, Virtual Tennis 2009 - + + //Wii Sports Resort, needs alt dol one time only, to show the Motion Plus video + //if (strcmp(id,"RZTP01") == 0 && CheckForSave(id4)==0) return 952;//from isostar + //if (strcmp(id,"RZTE01") == 0 && CheckForSave(id4)==0) return 674;//from starstremr + //as well as Grand Slam Tennis, Tiger Woods 10, Virtual Tennis 2009 + ///// games that can't be forced (alt dol is not always needed) - if (!force) { - - //Grand Slam Tennis - if (strcmp(id,"R5TP69") == 0) return 1493;//from isostar - if (strcmp(id,"R5TE69") == 0) return 1493;//starstremr - - //Medal of Honor Heroes - if (strcmp(id,"RMZX69") == 0) return 492;//from isostar - if (strcmp(id,"RMZP69") == 0) return 492;//from isostar - if (strcmp(id,"RMZE69") == 0) return 492;//starstremr - - //Tiger Woods 10 - if (strcmp(id,"R9OP69") == 0) return 1991;//from isostar - if (strcmp(id,"R9OE69") == 0) return 1973;//starstremr - - //Virtual Tennis 2009 - if (strcmp(id,"RVUP8P") == 0) return 16426;//from isostar - if (strcmp(id,"RVUE8P") == 0) return 16405;//from isostar - - //Wii Sports Resort - if (strcmp(id,"RZTP01") == 0) return 952;//from isostar - if (strcmp(id,"RZTE01") == 0) return 674;//from starstremr - } - + if (!force) { + + //Grand Slam Tennis + if (strcmp(id,"R5TP69") == 0) return 1493;//from isostar + if (strcmp(id,"R5TE69") == 0) return 1493;//starstremr + + //Medal of Honor Heroes + if (strcmp(id,"RMZX69") == 0) return 492;//from isostar + if (strcmp(id,"RMZP69") == 0) return 492;//from isostar + if (strcmp(id,"RMZE69") == 0) return 492;//starstremr + + //Tiger Woods 10 + if (strcmp(id,"R9OP69") == 0) return 1991;//from isostar + if (strcmp(id,"R9OE69") == 0) return 1973;//starstremr + + //Virtual Tennis 2009 + if (strcmp(id,"RVUP8P") == 0) return 16426;//from isostar + if (strcmp(id,"RVUE8P") == 0) return 16405;//from isostar + + //Wii Sports Resort + if (strcmp(id,"RZTP01") == 0) return 952;//from isostar + if (strcmp(id,"RZTE01") == 0) return 674;//from starstremr + } + return -1; } int autoSelectDolMenu(const char *id, bool force) { - /* - char id4[10]; - sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); - - switch (CheckForSave(id4)) { - case 0: - WindowPrompt(tr("NO save"),0,tr("OK")); - break; - case 1: - WindowPrompt(tr("save"),0,tr("OK")); - break; - default: - char test[10]; - sprintf(test,"%d",CheckForSave(id4)); - WindowPrompt(test,0,tr("OK")); + /* + char id4[10]; + sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); + + switch (CheckForSave(id4)) { + case 0: + WindowPrompt(tr("NO save"),0,tr("OK")); + break; + case 1: + WindowPrompt(tr("save"),0,tr("OK")); + break; + default: + char test[10]; + sprintf(test,"%d",CheckForSave(id4)); + WindowPrompt(test,0,tr("OK")); break; - } - return -1; - */ - - //Indiana Jones and the Staff of Kings (Fate of Atlantis) - if (strcmp(id,"RJ8E64") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Fate of Atlantis", tr("Default")); + } + return -1; + */ + + //Indiana Jones and the Staff of Kings (Fate of Atlantis) + if (strcmp(id,"RJ8E64") == 0) { + int choice = WindowPrompt(tr("Select a DOL"), 0, "Fate of Atlantis", tr("Default")); + switch (choice) { + case 1: + choice = 8; //from starstremr + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + if (strcmp(id,"RJ8P64") == 0) { + int choice = WindowPrompt(tr("Select a DOL"), 0, "Fate of Atlantis", tr("Default")); + switch (choice) { + case 1: + choice = 8; //from isostar + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + + //Metal Slug Anthology (Metal Slug 6) + if (strcmp(id,"RMLEH4") == 0) { + int choice = WindowPrompt(tr("Select a DOL"), 0, "Metal Slug 6", tr("Default")); + switch (choice) { + case 1: + choice = 54; //from lustar + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + if (strcmp(id,"RMLP7U") == 0) { + int choice = WindowPrompt(tr("Select a DOL"), 0, "Metal Slug 6", tr("Default")); + switch (choice) { + case 1: + choice = 56; //from isostar + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + + //Metroid Prime Trilogy + if (strcmp(id,"R3ME01") == 0) { + //do not use any alt dol if there is no save game in the nand + /* + if (CheckForSave(id4)==0 && force) { + WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); + return -1; + } + */ + int choice = WindowPrompt(tr("Select a DOL"), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr("Default")); switch (choice) { - case 1: - choice = 8; //from starstremr - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - if (strcmp(id,"RJ8P64") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Fate of Atlantis", tr("Default")); + case 1: + choice = 780; + break; + case 2: + choice = 781; + break; + case 3: + choice = 782; + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + if (strcmp(id,"R3MP01") == 0) { + /* + if (CheckForSave(id4)==0 && force) { + WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); + return -1; + } + */ + int choice = WindowPrompt(tr("Select a DOL"), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr("Default")); switch (choice) { - case 1: - choice = 8; //from isostar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //Metal Slug Anthology (Metal Slug 6) - if (strcmp(id,"RMLEH4") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metal Slug 6", tr("Default")); + case 1: + choice = 782; + break; + case 2: + choice = 783; + break; + case 3: + choice = 784; + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + + //Rampage: Total Destruction (M1.dol=Rampage, jarvos.dol=Rampage World Tour) + if (strcmp(id,"RPGP5D") == 0) { + int choice = WindowPrompt(tr("Select a DOL"), 0, "Rampage", "World Tour", tr("Default")); switch (choice) { - case 1: - choice = 54; //from lustar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - if (strcmp(id,"RMLP7U") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metal Slug 6", tr("Default")); - switch (choice) { - case 1: - choice = 56; //from isostar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //Metroid Prime Trilogy - if (strcmp(id,"R3ME01") == 0) { - //do not use any alt dol if there is no save game in the nand - /* - if (CheckForSave(id4)==0 && force) { - WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); - return -1; - } - */ - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr("Default")); - switch (choice) { - case 1: - choice = 780; - break; - case 2: - choice = 781; - break; - case 3: - choice = 782; - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - if (strcmp(id,"R3MP01") == 0) { - /* - if (CheckForSave(id4)==0 && force) { - WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); - return -1; - } - */ - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr("Default")); - switch (choice) { - case 1: - choice = 782; - break; - case 2: - choice = 783; - break; - case 3: - choice = 784; - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //Rampage: Total Destruction (M1.dol=Rampage, jarvos.dol=Rampage World Tour) - if (strcmp(id,"RPGP5D") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Rampage", "World Tour", tr("Default")); - switch (choice) { - case 1: - choice = 369; //from Ramzee - break; - case 2: - choice = 368; //from Ramzee - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //The House Of The Dead 2 & 3 Return (only to play 2) - if (strcmp(id,"RHDE8P") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "HotD 2", tr("Default")); - switch (choice) { - case 1: - choice = 149; //from starstremr - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - if (strcmp(id,"RHDP8P") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "HotD 2", tr("Default")); - switch (choice) { - case 1: - choice = 149; //from isostar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } + case 1: + choice = 369; //from Ramzee + break; + case 2: + choice = 368; //from Ramzee + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + + //The House Of The Dead 2 & 3 Return (only to play 2) + if (strcmp(id,"RHDE8P") == 0) { + int choice = WindowPrompt(tr("Select a DOL"), 0, "HotD 2", tr("Default")); + switch (choice) { + case 1: + choice = 149; //from starstremr + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + if (strcmp(id,"RHDP8P") == 0) { + int choice = WindowPrompt(tr("Select a DOL"), 0, "HotD 2", tr("Default")); + switch (choice) { + case 1: + choice = 149; //from isostar + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } return -1; @@ -495,39 +496,40 @@ int autoSelectDolMenu(const char *id, bool force) { *********************************************************************************/ static vu32 dvddone = 0; static dvddiskid *g_diskID = (dvddiskid*)0x80000000; // If you change this address, the read functions will FAIL! -void __dvd_readidcb(s32 result) { - dvddone = result; +void __dvd_readidcb(s32 result) +{ + dvddone = result; } u8 DiscMount(discHdr *header) { - gprintf("\nDiscMount() "); + gprintf("\nDiscMount() "); int ret; - HaltGui(); + HaltGui(); + + u8 *tmpBuff = (u8 *) malloc(0x60); + memcpy(tmpBuff, g_diskID, 0x60); // Make a backup of the first 96 bytes at 0x80000000 - u8 *tmpBuff = (u8 *) malloc(0x60); - memcpy(tmpBuff, g_diskID, 0x60); // Make a backup of the first 96 bytes at 0x80000000 + ret = bwDVD_LowInit(); + dvddone = 0; + ret = bwDVD_LowReset(__dvd_readidcb); + while(ret>=0 && dvddone==0); + + dvddone = 0; + ret = bwDVD_LowReadID(g_diskID, __dvd_readidcb); // Leave this one here, or you'll get an IOCTL error + while(ret>=0 && dvddone==0); - ret = bwDVD_LowInit(); - dvddone = 0; - ret = bwDVD_LowReset(__dvd_readidcb); - while (ret>=0 && dvddone==0); + dvddone = 0; + ret = bwDVD_LowUnencryptedRead(g_diskID, 0x60, 0x00, __dvd_readidcb); // Overwrite the g_diskID thing + while(ret>=0 && dvddone==0); + + memcpy(header, g_diskID, 0x60); + memcpy(g_diskID, tmpBuff, 0x60); // Put the backup back, or games won't load + free(tmpBuff); - dvddone = 0; - ret = bwDVD_LowReadID(g_diskID, __dvd_readidcb); // Leave this one here, or you'll get an IOCTL error - while (ret>=0 && dvddone==0); - - dvddone = 0; - ret = bwDVD_LowUnencryptedRead(g_diskID, 0x60, 0x00, __dvd_readidcb); // Overwrite the g_diskID thing - while (ret>=0 && dvddone==0); - - memcpy(header, g_diskID, 0x60); - memcpy(g_diskID, tmpBuff, 0x60); // Put the backup back, or games won't load - free(tmpBuff); - - - ResumeGui(); - if (dvddone != 1) { - return 0; - } - return (header->magic == 0x5D1C9EA3) ? 1 : 2; // Don't check gamecube magic (0xC2339F3D) + + ResumeGui(); + if (dvddone != 1) { + return 0; + } + return (header->magic == 0x5D1C9EA3) ? 1 : 2; // Don't check gamecube magic (0xC2339F3D) } diff --git a/source/prompts/ProgressWindow.cpp b/source/prompts/ProgressWindow.cpp index c81278ae..b1ae11f7 100644 --- a/source/prompts/ProgressWindow.cpp +++ b/source/prompts/ProgressWindow.cpp @@ -58,7 +58,7 @@ static void GameInstallProgress() { GetProgressValue(&gameinstalldone, &gameinstalltotal); - if ((oldinstalldone == gameinstalldone) && (gameinstalldone > 0)) + if((oldinstalldone == gameinstalldone) && (gameinstalldone > 0)) return; if (gameinstalldone > gameinstalltotal) @@ -257,7 +257,8 @@ static void ProgressWindow(const char *title, const char *msg1, const char *msg2 GameInstallProgress(); - if (changed) { + if(changed) + { changed = false; tmp = static_cast(progressbarImg.GetWidth()*progressDone); @@ -324,7 +325,8 @@ void ProgressStop() { * Callbackfunction for updating the progress values * Use this function as standard callback ***************************************************************************/ -void ShowProgress(const char *title, const char *msg1, char *dynmsg2, f32 done, f32 total, bool swSize, bool swTime) { +void ShowProgress(const char *title, const char *msg1, char *dynmsg2, f32 done, f32 total, bool swSize, bool swTime) +{ if (total <= 0) return; diff --git a/source/prompts/PromptWindows.cpp b/source/prompts/PromptWindows.cpp index f5d2098c..cc6d0b5e 100644 --- a/source/prompts/PromptWindows.cpp +++ b/source/prompts/PromptWindows.cpp @@ -70,13 +70,13 @@ extern void HaltGui(); * into the specified variable. ***************************************************************************/ int OnScreenNumpad(char * var, u32 maxlen) { - int save = -1; - - GuiNumpad numpad(var, maxlen); - + int save = -1; + + GuiNumpad numpad(var, maxlen); + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size,Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size,Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -104,7 +104,7 @@ int OnScreenNumpad(char * var, u32 maxlen) { GuiButton cancelBtn(&cancelBtnImg,&cancelBtnImg, 1, 4, -5, -15, &trigA, &btnSoundOver, btnClick2,1); cancelBtn.SetLabel(&cancelBtnTxt); cancelBtn.SetTrigger(&trigB); - + numpad.Append(&okBtn); numpad.Append(&cancelBtn); @@ -131,8 +131,8 @@ int OnScreenNumpad(char * var, u32 maxlen) { mainWindow->Remove(&numpad); mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - gprintf("\t%s",(save == 1?"saved":"discarded")); - return save; + gprintf("\t%s",(save == 1?"saved":"discarded")); + return save; } /**************************************************************************** @@ -151,14 +151,14 @@ int OnScreenKeyboard(char * var, u32 maxlen, int min) { else if (Settings.keyset == azerty) keyset = 3; else if (Settings.keyset == qwerty) keyset = 4; - gprintf("\nOnScreenKeyboard(%s, %i, %i) \n\tkeyset = %i",var,maxlen,min,keyset); + gprintf("\nOnScreenKeyboard(%s, %i, %i) \n\tkeyset = %i",var,maxlen,min,keyset); GuiKeyboard keyboard(var, maxlen, min, keyset); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size,Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size,Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -213,7 +213,7 @@ int OnScreenKeyboard(char * var, u32 maxlen, int min) { mainWindow->Remove(&keyboard); mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - gprintf("\t%s",(save?"saved":"discarded")); + gprintf("\t%s",(save?"saved":"discarded")); return save; } @@ -222,7 +222,7 @@ int OnScreenKeyboard(char * var, u32 maxlen, int min) { * Display credits ***************************************************************************/ void WindowCredits() { - gprintf("\nWindowCredits()"); + gprintf("\nWindowCredits()"); int angle = 0; GuiSound * creditsMusic = NULL; @@ -276,7 +276,7 @@ void WindowCredits() { - txt[i] = new GuiText(SvnRev, 16, (GXColor) {255, 255, 255, 255}); + txt[i] = new GuiText(SvnRev, 16, (GXColor) { 255, 255, 255, 255}); txt[i]->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); txt[i]->SetPosition(0,y); i++; @@ -453,33 +453,33 @@ void WindowCredits() { * Display screensaver ***************************************************************************/ int WindowScreensaver() { - gprintf("\nWindowScreenSaver()"); - int i = 0; - bool exit = false; - char imgPath[100];//uncomment for themable screensaver + gprintf("\nWindowScreenSaver()"); + int i = 0; + bool exit = false; + char imgPath[100];//uncomment for themable screensaver - /* initialize random seed: */ - srand ( time(NULL) ); + /* initialize random seed: */ + srand ( time(NULL) ); - snprintf(imgPath, sizeof(imgPath), "%sscreensaver.png", CFG.theme_path);//uncomment for themable screensaver - GuiImageData GXlogo(imgPath, gxlogo_png);//uncomment for themable screensaver - //GuiImageData GXlogo(gxlogo_png);//comment for themable screensaver - GuiImage GXlogoImg(&GXlogo); - GXlogoImg.SetPosition(172,152); - GXlogoImg.SetAlignment(ALIGN_LEFT,ALIGN_TOP); + snprintf(imgPath, sizeof(imgPath), "%sscreensaver.png", CFG.theme_path);//uncomment for themable screensaver + GuiImageData GXlogo(imgPath, gxlogo_png);//uncomment for themable screensaver + //GuiImageData GXlogo(gxlogo_png);//comment for themable screensaver + GuiImage GXlogoImg(&GXlogo); + GXlogoImg.SetPosition(172,152); + GXlogoImg.SetAlignment(ALIGN_LEFT,ALIGN_TOP); - GuiImage BackgroundImg(640,480,(GXColor) {0, 0, 0, 255}); - BackgroundImg.SetPosition(0,0); - BackgroundImg.SetAlignment(ALIGN_LEFT,ALIGN_TOP); + GuiImage BackgroundImg(640,480,(GXColor) {0, 0, 0, 255}); + BackgroundImg.SetPosition(0,0); + BackgroundImg.SetAlignment(ALIGN_LEFT,ALIGN_TOP); - GuiWindow screensaverWindow(screenwidth,screenheight); - screensaverWindow.Append(&BackgroundImg); - screensaverWindow.Append(&GXlogoImg); + GuiWindow screensaverWindow(screenwidth,screenheight); + screensaverWindow.Append(&BackgroundImg); + screensaverWindow.Append(&GXlogoImg); - HaltGui(); - mainWindow->SetState(STATE_DISABLED); - mainWindow->Append(&screensaverWindow); - ResumeGui(); + HaltGui(); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&screensaverWindow); + ResumeGui(); while (!exit) { i++; @@ -512,11 +512,11 @@ int WindowScreensaver() { * place. ***************************************************************************/ int WindowPrompt(const char *title, const char *msg, const char *btn1Label, - const char *btn2Label, const char *btn3Label, - const char *btn4Label, int wait) { + const char *btn2Label, const char *btn3Label, + const char *btn4Label, int wait) { int choice = -1; int count = wait; - gprintf("\nWindowPrompt(%s, %s, %s, %s, %s, %s, %i)",title,msg,btn1Label,btn2Label, btn3Label,btn4Label,wait); + gprintf("\nWindowPrompt(%s, %s, %s, %s, %s, %s, %i)",title,msg,btn1Label,btn2Label, btn3Label,btn4Label,wait); GuiWindow promptWindow(472,320); @@ -524,9 +524,9 @@ int WindowPrompt(const char *title, const char *msg, const char *btn1Label, promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); GuiImageData btnOutline(imgPath, button_dialogue_box_png); @@ -746,12 +746,12 @@ int WindowPrompt(const char *title, const char *msg, const char *btn1Label, choice = 3; } else if (btn4.GetState() == STATE_CLICKED) { choice = 0; - } else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); - } + } else if (screenShotBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tscreenShotBtn clicked"); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf("...It's easy, mmmmmmKay"); + } if (count>0)count--; if (count==0) choice = 1; } @@ -762,7 +762,7 @@ int WindowPrompt(const char *title, const char *msg, const char *btn1Label, mainWindow->Remove(&promptWindow); mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - gprintf(" = %i",choice); + gprintf(" = %i",choice); return choice; } @@ -777,8 +777,9 @@ int WindowPrompt(const char *title, const char *msg, const char *btn1Label, * If titel/subtitle or one of the buttons is not needed give him a 0 on that * place. ***************************************************************************/ -int WindowExitPrompt() { - gprintf("\nWindowExitPrompt()"); +int WindowExitPrompt() +{ + gprintf("\nWindowExitPrompt()"); GuiSound * homein = NULL; homein = new GuiSound(menuin_ogg, menuin_ogg_size, Settings.sfxvolume); @@ -794,18 +795,18 @@ int WindowExitPrompt() { int choice = -1; char imgPath[100]; - u64 oldstub = getStubDest(); - loadStub(); - if (oldstub != 0x00010001554c4e52ll && oldstub != 0x00010001554e454fll) - Set_Stub(oldstub); + u64 oldstub = getStubDest(); + loadStub(); + if (oldstub != 0x00010001554c4e52ll && oldstub != 0x00010001554e454fll) + Set_Stub(oldstub); - GuiWindow promptWindow(640,480); + GuiWindow promptWindow(640,480); promptWindow.SetAlignment(ALIGN_LEFT, ALIGN_TOP); promptWindow.SetPosition(0, 0); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); GuiImageData top(exit_top_png); GuiImageData topOver(exit_top_over_png); @@ -817,9 +818,9 @@ int WindowExitPrompt() { snprintf(imgPath, sizeof(imgPath), "%sbattery_white.png", CFG.theme_path); GuiImageData battery(imgPath, battery_white_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_white.png", CFG.theme_path); + snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_white.png", CFG.theme_path); GuiImageData batteryBar(imgPath, battery_bar_white_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", CFG.theme_path); + snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", CFG.theme_path); GuiImageData batteryRed(imgPath, battery_red_png); snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_red.png", CFG.theme_path); GuiImageData batteryBarRed(imgPath, battery_bar_red_png); @@ -835,7 +836,7 @@ int WindowExitPrompt() { sprintf(txt, "P%d", i+1); - batteryTxt[i] = new GuiText(txt, 22, (GXColor) {255,255,255, 255}); + batteryTxt[i] = new GuiText(txt, 22, (GXColor) {255,255,255, 255}); batteryTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); batteryImg[i] = new GuiImage(&battery); batteryImg[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); @@ -860,7 +861,7 @@ int WindowExitPrompt() { batteryBtn[2]->SetPosition(388, 150); batteryBtn[3]->SetPosition(494, 150); - GuiTrigger trigA; + GuiTrigger trigA; trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); GuiTrigger trigB; trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); @@ -962,11 +963,11 @@ int WindowExitPrompt() { if (level <= 1) { batteryBarImg[i]->SetImage(&batteryBarRed); batteryImg[i]->SetImage(&batteryRed); - } else { + } else { batteryBarImg[i]->SetImage(&batteryBar); - } + } - batteryImg[i]->SetTile(level); + batteryImg[i]->SetTile(level); batteryBtn[i]->SetAlpha(255); } else { // controller not connected @@ -1053,7 +1054,8 @@ int WindowExitPrompt() { return choice; } -void SetupFavoriteButton(GuiButton *btnFavorite, int xPos, GuiImage *img, GuiSound *sndOver, GuiSound *sndClick, GuiTrigger *trig) { +void SetupFavoriteButton(GuiButton *btnFavorite, int xPos, GuiImage *img, GuiSound *sndOver, GuiSound *sndClick, GuiTrigger *trig) +{ btnFavorite->SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); btnFavorite->SetPosition(xPos, -60); btnFavorite->SetImage(img); @@ -1063,26 +1065,28 @@ void SetupFavoriteButton(GuiButton *btnFavorite, int xPos, GuiImage *img, GuiSou btnFavorite->SetEffectGrow(); } -u8 SetFavorite(GuiButton *fav1, GuiButton *fav2, GuiButton *fav3, GuiButton *fav4, GuiButton *fav5, u8* gameId, u8 favorite) { - struct Game_NUM * game_num = CFG_get_game_num(gameId); - if (game_num) { - favoritevar = game_num->favorite; - playcount = game_num->count; - } else { - favoritevar = 0; - playcount = 0; - } - favoritevar = (favorite == favoritevar) ? 0 : favorite; // Press the current rank to reset the rank - CFG_save_game_num(gameId); - return favoritevar; +u8 SetFavorite(GuiButton *fav1, GuiButton *fav2, GuiButton *fav3, GuiButton *fav4, GuiButton *fav5, u8* gameId, u8 favorite) +{ + struct Game_NUM * game_num = CFG_get_game_num(gameId); + if (game_num) { + favoritevar = game_num->favorite; + playcount = game_num->count; + } else { + favoritevar = 0; + playcount = 0; + } + favoritevar = (favorite == favoritevar) ? 0 : favorite; // Press the current rank to reset the rank + CFG_save_game_num(gameId); + return favoritevar; } -void SetFavoriteImages(GuiImage *b1, GuiImage *b2, GuiImage *b3, GuiImage *b4, GuiImage *b5, GuiImageData *on, GuiImageData *off) { - b1->SetImage(favoritevar >= 1 ? on : off); - b2->SetImage(favoritevar >= 2 ? on : off); - b3->SetImage(favoritevar >= 3 ? on : off); - b4->SetImage(favoritevar >= 4 ? on : off); - b5->SetImage(favoritevar >= 5 ? on : off); +void SetFavoriteImages(GuiImage *b1, GuiImage *b2, GuiImage *b3, GuiImage *b4, GuiImage *b5, GuiImageData *on, GuiImageData *off) +{ + b1->SetImage(favoritevar >= 1 ? on : off); + b2->SetImage(favoritevar >= 2 ? on : off); + b3->SetImage(favoritevar >= 3 ? on : off); + b4->SetImage(favoritevar >= 4 ? on : off); + b5->SetImage(favoritevar >= 5 ? on : off); } /**************************************************************************** @@ -1104,9 +1108,9 @@ int GameWindowPrompt() { promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -1245,11 +1249,11 @@ int GameWindowPrompt() { GuiButton btnFavorite4(imgFavorite.GetWidth(), imgFavorite.GetHeight()); GuiButton btnFavorite5(imgFavorite.GetWidth(), imgFavorite.GetHeight()); - SetupFavoriteButton(&btnFavorite1, -198, &btnFavoriteImg1, &btnSoundOver, btnClick2, &trigA); - SetupFavoriteButton(&btnFavorite2, -171, &btnFavoriteImg2, &btnSoundOver, btnClick2, &trigA); - SetupFavoriteButton(&btnFavorite3, -144, &btnFavoriteImg3, &btnSoundOver, btnClick2, &trigA); - SetupFavoriteButton(&btnFavorite4, -117, &btnFavoriteImg4, &btnSoundOver, btnClick2, &trigA); - SetupFavoriteButton(&btnFavorite5, -90, &btnFavoriteImg5, &btnSoundOver, btnClick2, &trigA); + SetupFavoriteButton(&btnFavorite1, -198, &btnFavoriteImg1, &btnSoundOver, btnClick2, &trigA); + SetupFavoriteButton(&btnFavorite2, -171, &btnFavoriteImg2, &btnSoundOver, btnClick2, &trigA); + SetupFavoriteButton(&btnFavorite3, -144, &btnFavoriteImg3, &btnSoundOver, btnClick2, &trigA); + SetupFavoriteButton(&btnFavorite4, -117, &btnFavoriteImg4, &btnSoundOver, btnClick2, &trigA); + SetupFavoriteButton(&btnFavorite5, -90, &btnFavoriteImg5, &btnSoundOver, btnClick2, &trigA); GuiImage btnLeftImg(&imgLeft); if (Settings.wsprompt == yes) { @@ -1272,16 +1276,17 @@ int GameWindowPrompt() { promptWindow.Append(&playcntTxt); promptWindow.Append(&screenShotBtn); promptWindow.Append(&btn2); - if (!mountMethod) { //stuff we don't show if it is a DVD mounted - promptWindow.Append(&sizeTxt); - promptWindow.Append(&btnLeft); - promptWindow.Append(&btnRight); - promptWindow.Append(&btnFavorite1); - promptWindow.Append(&btnFavorite2); - promptWindow.Append(&btnFavorite3); - promptWindow.Append(&btnFavorite4); - promptWindow.Append(&btnFavorite5); - } + if (!mountMethod)//stuff we don't show if it is a DVD mounted + { + promptWindow.Append(&sizeTxt); + promptWindow.Append(&btnLeft); + promptWindow.Append(&btnRight); + promptWindow.Append(&btnFavorite1); + promptWindow.Append(&btnFavorite2); + promptWindow.Append(&btnFavorite3); + promptWindow.Append(&btnFavorite4); + promptWindow.Append(&btnFavorite5); + } //check if unlocked if (Settings.godmode == 1 && mountMethod!=2 && mountMethod!=3) { @@ -1290,7 +1295,7 @@ int GameWindowPrompt() { promptWindow.Append(&diskImg2); promptWindow.Append(&btn1); - + short changed = -1; GuiImageData * diskCover = NULL; GuiImageData * diskCover2 = NULL; @@ -1313,27 +1318,30 @@ int GameWindowPrompt() { //load disc image based or what game is seleted struct discHdr * header = (mountMethod==1||mountMethod==2?dvdheader:&gameList[gameSelected]); - if (Settings.gamesoundvolume > 0) { - if (gameSound) { - gameSound->Stop(); - delete gameSound; - gameSound = NULL; - } - u32 gameSoundDataLen; + if(Settings.gamesoundvolume > 0) + { + if(gameSound) + { + gameSound->Stop(); + delete gameSound; + gameSound = NULL; + } + u32 gameSoundDataLen; const u8 *gameSoundData = LoadBannerSound(header->id, &gameSoundDataLen); - if (gameSoundData) { - gameSound = new GuiSound(gameSoundData, gameSoundDataLen, Settings.gamesoundvolume, false, true); - bgMusic->SetVolume(0); - if (Settings.gamesound == 2) + if(gameSoundData) + { + gameSound = new GuiSound(gameSoundData, gameSoundDataLen, Settings.gamesoundvolume, false, true); + bgMusic->SetVolume(0); + if(Settings.gamesound == 2) gameSound->SetLoop(1); - gameSound->Play(); - } + gameSound->Play(); + } } snprintf (ID,sizeof(ID),"%c%c%c", header->id[0], header->id[1], header->id[2]); snprintf (IDFull,sizeof(IDFull),"%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); gprintf("\n\t%s",IDFull); - if (diskCover) + if (diskCover) delete diskCover; @@ -1408,12 +1416,13 @@ int GameWindowPrompt() { } else diskImg.SetImage(diskCover); - if (!mountMethod) { - WBFS_GameSize(header->id, &size); - sizeTxt.SetTextf("%.2fGB", size); //set size text; - } + if (!mountMethod) + { + WBFS_GameSize(header->id, &size); + sizeTxt.SetTextf("%.2fGB", size); //set size text; + } - nameTxt.SetText(get_title(header)); + nameTxt.SetText(get_title(header)); struct Game_NUM* game_num = CFG_get_game_num(header->id); if (game_num) { @@ -1424,7 +1433,7 @@ int GameWindowPrompt() { favoritevar = 0; } playcntTxt.SetTextf("%s: %i",tr("Play Count"), playcount); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); nameTxt.SetPosition(0, 1); @@ -1437,18 +1446,19 @@ int GameWindowPrompt() { ResumeGui(); changed = 0; - while (choice == -1) { + while (choice == -1) + { VIDEO_WaitVSync (); diskImg.SetSpin(btn1.GetState() == STATE_SELECTED); diskImg2.SetSpin(btn1.GetState() == STATE_SELECTED); if (shutdown == 1) { //for power button - promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); mainWindow->SetState(STATE_DEFAULT); - while (promptWindow.GetEffect() > 0) usleep(50); - HaltGui(); - mainWindow->Remove(&promptWindow); - ResumeGui(); + while (promptWindow.GetEffect() > 0) usleep(50); + HaltGui(); + mainWindow->Remove(&promptWindow); + ResumeGui(); wiilight(0); Sys_Shutdown(); } @@ -1456,9 +1466,11 @@ int GameWindowPrompt() { if (reset == 1) //for reset button Sys_Reboot(); - if (gameSound) { - if (!gameSound->IsPlaying()) { - if (Settings.gamesound == 1) + if(gameSound) + { + if(!gameSound->IsPlaying()) + { + if(Settings.gamesound == 1) bgMusic->SetVolume(Settings.volume); } } @@ -1496,42 +1508,48 @@ int GameWindowPrompt() { else if (nameBtn.GetState() == STATE_CLICKED) { //rename choice = 3; promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); - } else if (btnFavorite1.GetState() == STATE_CLICKED) {//switch favorite + } + else if (btnFavorite1.GetState() == STATE_CLICKED) {//switch favorite if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 1); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 1); + SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); } btnFavorite1.ResetState(); - } else if (btnFavorite2.GetState() == STATE_CLICKED) {//switch favorite + } + else if (btnFavorite2.GetState() == STATE_CLICKED) {//switch favorite if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 2); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 2); + SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); } btnFavorite2.ResetState(); - } else if (btnFavorite3.GetState() == STATE_CLICKED) {//switch favorite + } + else if (btnFavorite3.GetState() == STATE_CLICKED) {//switch favorite if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 3); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 3); + SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); } btnFavorite3.ResetState(); - } else if (btnFavorite4.GetState() == STATE_CLICKED) {//switch favorite + } + else if (btnFavorite4.GetState() == STATE_CLICKED) {//switch favorite if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 4); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 4); + SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); } btnFavorite4.ResetState(); - } else if (btnFavorite5.GetState() == STATE_CLICKED) {//switch favorite + } + else if (btnFavorite5.GetState() == STATE_CLICKED) {//switch favorite if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 5); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 5); + SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); } btnFavorite5.ResetState(); - } else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); } + else if (screenShotBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tscreenShotBtn clicked"); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf("...It's easy, mmmmmmKay"); + } // this next part is long because nobody could agree on what the left/right buttons should do else if ((btnRight.GetState() == STATE_CLICKED) && (Settings.xflip == no)) {//next game promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); @@ -1636,9 +1654,10 @@ int GameWindowPrompt() { delete diskCover; delete diskCover2; - if (gameSound) { + if(gameSound) + { gameSound->Stop(); - delete gameSound; + delete gameSound; gameSound = NULL; } bgMusic->SetVolume(Settings.volume); @@ -1659,9 +1678,9 @@ DiscWait(const char *title, const char *msg, const char *btn1Label, const char * promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -1753,14 +1772,14 @@ DiscWait(const char *title, const char *msg, const char *btn1Label, const char * while (i >= 0) { VIDEO_WaitVSync(); timerTxt.SetTextf("%u %s", i,tr("seconds left")); - /* HaltGui(); - if (Settings.cios == ios222) { - ret = IOS_ReloadIOS(222); - load_ehc_module(); - } else { - ret = IOS_ReloadIOS(249); - } - ResumeGui();*/ + /* HaltGui(); + if (Settings.cios == ios222) { + ret = IOS_ReloadIOS(222); + load_ehc_module(); + } else { + ret = IOS_ReloadIOS(249); + } + ResumeGui();*/ sleep(1); USBDevice_deInit(); USBDevice_Init(); @@ -1852,15 +1871,15 @@ FormatingPartition(const char *title, partitionEntry *entry) { ***************************************************************************/ bool SearchMissingImages(int choice2) { - gprintf("\nSearchMissingImages(%i)",choice2); + gprintf("\nSearchMissingImages(%i)",choice2); GuiWindow promptWindow(472,320); promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -1899,78 +1918,78 @@ bool SearchMissingImages(int choice2) { //make sure that all games are added to the gamelist __Menu_GetEntries(1); - cntMissFiles = 0; - u32 i = 0; - char filename[11]; + cntMissFiles = 0; + u32 i = 0; + char filename[11]; - //add IDs of games that are missing covers to cntMissFiles - bool found1 = false; - bool found2 = false; - bool found3 = false; - for (i = 0; i < gameCnt && cntMissFiles < 500; i++) { - struct discHdr* header = &gameList[i]; - if (choice2 != 3) { + //add IDs of games that are missing covers to cntMissFiles + bool found1 = false; + bool found2 = false; + bool found3 = false; + for (i = 0; i < gameCnt && cntMissFiles < 500; i++) { + struct discHdr* header = &gameList[i]; + if (choice2 != 3) { - char *covers_path = choice2==1 ? Settings.covers2d_path : Settings.covers_path; + char *covers_path = choice2==1 ? Settings.covers2d_path : Settings.covers_path; - snprintf (filename,sizeof(filename),"%c%c%c.png", header->id[0], header->id[1], header->id[2]); - found2 = findfile(filename, covers_path); + snprintf (filename,sizeof(filename),"%c%c%c.png", header->id[0], header->id[1], header->id[2]); + found2 = findfile(filename, covers_path); - snprintf (filename,sizeof(filename),"%c%c%c%c.png", header->id[0], header->id[1], header->id[2], header->id[3]); - found3 = findfile(filename, covers_path); + snprintf (filename,sizeof(filename),"%c%c%c%c.png", header->id[0], header->id[1], header->id[2], header->id[3]); + found3 = findfile(filename, covers_path); - snprintf(filename,sizeof(filename),"%c%c%c%c%c%c.png",header->id[0], header->id[1], header->id[2], - header->id[3], header->id[4], header->id[5]); //full id - found1 = findfile(filename, covers_path); - if (!found1 && !found2 && !found3) { //if could not find any image - snprintf(missingFiles[cntMissFiles],11,"%s",filename); - cntMissFiles++; - } - } else if (choice2 == 3) { - snprintf (filename,sizeof(filename),"%c%c%c.png", header->id[0], header->id[1], header->id[2]); - found2 = findfile(filename, Settings.disc_path); - snprintf(filename,sizeof(filename),"%c%c%c%c%c%c.png",header->id[0], header->id[1], header->id[2], - header->id[3], header->id[4], header->id[5]); //full id - found1 = findfile(filename,Settings.disc_path); - if (!found1 && !found2) { - snprintf(missingFiles[cntMissFiles],11,"%s",filename); - cntMissFiles++; - } - } - } - if (cntMissFiles == 0) { - msgTxt.SetText(tr("No file missing!")); + snprintf(filename,sizeof(filename),"%c%c%c%c%c%c.png",header->id[0], header->id[1], header->id[2], + header->id[3], header->id[4], header->id[5]); //full id + found1 = findfile(filename, covers_path); + if (!found1 && !found2 && !found3) { //if could not find any image + snprintf(missingFiles[cntMissFiles],11,"%s",filename); + cntMissFiles++; + } + } else if (choice2 == 3) { + snprintf (filename,sizeof(filename),"%c%c%c.png", header->id[0], header->id[1], header->id[2]); + found2 = findfile(filename, Settings.disc_path); + snprintf(filename,sizeof(filename),"%c%c%c%c%c%c.png",header->id[0], header->id[1], header->id[2], + header->id[3], header->id[4], header->id[5]); //full id + found1 = findfile(filename,Settings.disc_path); + if (!found1 && !found2) { + snprintf(missingFiles[cntMissFiles],11,"%s",filename); + cntMissFiles++; + } + } + } + if (cntMissFiles == 0) { + msgTxt.SetText(tr("No file missing!")); sleep(1); - } + } - promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); while (promptWindow.GetEffect() > 0) usleep(50); HaltGui(); mainWindow->Remove(&promptWindow); mainWindow->SetState(STATE_DEFAULT); - __Menu_GetEntries(); + __Menu_GetEntries(); ResumeGui(); - gprintf(" = %i",cntMissFiles); + gprintf(" = %i",cntMissFiles); if (cntMissFiles > 0) { //&& !IsNetworkInit()) { - NetworkInitPrompt(); - } + NetworkInitPrompt(); + } - if (cntMissFiles == 0) { - return false; - } else { - return true; - } + if (cntMissFiles == 0) { + return false; + } else { + return true; + } } /**************************************************************************** * NetworkInitPrompt ***************************************************************************/ bool NetworkInitPrompt() { - gprintf("\nNetworkinitPrompt()"); + gprintf("\nNetworkinitPrompt()"); if (IsNetworkInit()) - return true; + return true; bool success = true; @@ -1979,9 +1998,9 @@ bool NetworkInitPrompt() { promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -2081,9 +2100,9 @@ ProgressDownloadWindow(int choice2) { promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -2234,7 +2253,7 @@ ProgressDownloadWindow(int choice2) { //Creates URL depending from which Country the game is switch (missingFiles[i][3]) { case 'J': - sprintf(URLFile,"%sJA/%s",server3d,missingFiles[i]); + sprintf(URLFile,"%sJA/%s",server3d,missingFiles[i]); break; case 'W': sprintf(URLFile,"%sZH/%s",server3d,missingFiles[i]); @@ -2281,47 +2300,47 @@ ProgressDownloadWindow(int choice2) { //Creates URL depending from which Country the game is switch (missingFiles[i][3]) { case 'J': - if (Settings.discart == 0) { + if(Settings.discart == 0) { sprintf(URLFile,"%sJA/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 1) { + } else if(Settings.discart == 1) { sprintf(URLFile,"%sJA/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 0) { + } else if(Settings.discart == 2 && tries == 0) { sprintf(URLFile,"%sJA/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 1) { + } else if(Settings.discart == 2 && tries == 1) { sprintf(URLFile,"%sJA/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 0) { + } else if(Settings.discart == 3 && tries == 0) { sprintf(URLFile,"%sJA/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 1) { + } else if(Settings.discart == 3 && tries == 1) { sprintf(URLFile,"%sJA/%s",serverDisc,missingFiles[i]); } break; case 'W': - if (Settings.discart == 0) { + if(Settings.discart == 0) { sprintf(URLFile,"%sZH/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 1) { + } else if(Settings.discart == 1) { sprintf(URLFile,"%sZH/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 0) { + } else if(Settings.discart == 2 && tries == 0) { sprintf(URLFile,"%sZH/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 1) { + } else if(Settings.discart == 2 && tries == 1) { sprintf(URLFile,"%sZH/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 0) { + } else if(Settings.discart == 3 && tries == 0) { sprintf(URLFile,"%sZH/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 1) { + } else if(Settings.discart == 3 && tries == 1) { sprintf(URLFile,"%sZH/%s",serverDisc,missingFiles[i]); } break; case 'K': - if (Settings.discart == 0) { + if(Settings.discart == 0) { sprintf(URLFile,"%sKO/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 1) { + } else if(Settings.discart == 1) { sprintf(URLFile,"%sKO/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 0) { + } else if(Settings.discart == 2 && tries == 0) { sprintf(URLFile,"%sKO/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 1) { + } else if(Settings.discart == 2 && tries == 1) { sprintf(URLFile,"%sKO/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 0) { + } else if(Settings.discart == 3 && tries == 0) { sprintf(URLFile,"%sKO/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 1) { + } else if(Settings.discart == 3 && tries == 1) { sprintf(URLFile,"%sKO/%s",serverDisc,missingFiles[i]); } break; @@ -2335,32 +2354,32 @@ ProgressDownloadWindow(int choice2) { case 'X': case 'Y': case 'Z': - if (Settings.discart == 0) { + if(Settings.discart == 0) { sprintf(URLFile,"%s%s/%s",serverDisc,Settings.db_language,missingFiles[i]); - } else if (Settings.discart == 1) { + } else if(Settings.discart == 1) { sprintf(URLFile,"%s%s/%s",serverDiscCustom,Settings.db_language,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 0) { + } else if(Settings.discart == 2 && tries == 0) { sprintf(URLFile,"%s%s/%s",serverDisc,Settings.db_language,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 1) { + } else if(Settings.discart == 2 && tries == 1) { sprintf(URLFile,"%s%s/%s",serverDiscCustom,Settings.db_language,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 0) { + } else if(Settings.discart == 3 && tries == 0) { sprintf(URLFile,"%s%s/%s",serverDiscCustom,Settings.db_language,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 1) { + } else if(Settings.discart == 3 && tries == 1) { sprintf(URLFile,"%s%s/%s",serverDisc,Settings.db_language,missingFiles[i]); } break; case 'E': - if (Settings.discart == 0) { + if(Settings.discart == 0) { sprintf(URLFile,"%sUS/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 1) { + } else if(Settings.discart == 1) { sprintf(URLFile,"%sUS/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 0) { + } else if(Settings.discart == 2 && tries == 0) { sprintf(URLFile,"%sUS/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 1) { + } else if(Settings.discart == 2 && tries == 1) { sprintf(URLFile,"%sUS/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 0) { + } else if(Settings.discart == 3 && tries == 0) { sprintf(URLFile,"%sUS/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 1) { + } else if(Settings.discart == 3 && tries == 1) { sprintf(URLFile,"%sUS/%s",serverDisc,missingFiles[i]); } break; @@ -2371,17 +2390,17 @@ ProgressDownloadWindow(int choice2) { if (!(file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size == 4446 || file.data == NULL)) { break; } else { - if (Settings.discart == 0) { + if(Settings.discart == 0) { sprintf(URLFile,"%sEN/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 1) { + } else if(Settings.discart == 1) { sprintf(URLFile,"%sEN/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 0) { + } else if(Settings.discart == 2 && tries == 0) { sprintf(URLFile,"%sEN/%s",serverDisc,missingFiles[i]); - } else if (Settings.discart == 2 && tries == 1) { + } else if(Settings.discart == 2 && tries == 1) { sprintf(URLFile,"%sEN/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 0) { + } else if(Settings.discart == 3 && tries == 0) { sprintf(URLFile,"%sEN/%s",serverDiscCustom,missingFiles[i]); - } else if (Settings.discart == 3 && tries == 1) { + } else if(Settings.discart == 3 && tries == 1) { sprintf(URLFile,"%sEN/%s",serverDisc,missingFiles[i]); } file = downloadfile(URLFile); @@ -2398,7 +2417,7 @@ ProgressDownloadWindow(int choice2) { //Creates URL depending from which Country the game is switch (missingFiles[i][3]) { case 'J': - sprintf(URLFile,"%sJA/%s",server2d,missingFiles[i]); + sprintf(URLFile,"%sJA/%s",server2d,missingFiles[i]); break; case 'W': sprintf(URLFile,"%sZH/%s",server2d,missingFiles[i]); @@ -2563,9 +2582,9 @@ int ProgressUpdateWindow() { promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, SOUND_PCM, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, SOUND_PCM, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -2671,8 +2690,8 @@ int ProgressUpdateWindow() { } //make the URL to get XML based on our games - char XMLurl[3540]; - build_XML_URL(XMLurl,sizeof(XMLurl)); + char XMLurl[3540]; + build_XML_URL(XMLurl,sizeof(XMLurl)); char dolpath[150]; // char dolpathsuccess[150];//use coverspath as a folder for the update wad so we dont make a new folder and have to delete it @@ -2712,26 +2731,26 @@ int ProgressUpdateWindow() { msgTxt.SetPosition(0,100); msgTxt.SetTextf("%s", tr("Updating WiiTDB.zip")); - char wiitdbpath[200]; - char wiitdbpathtmp[200]; + char wiitdbpath[200]; + char wiitdbpathtmp[200]; struct block file = downloadfile(XMLurl); if (file.data != NULL) { - snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); - snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); - rename(wiitdbpath,wiitdbpathtmp); - pfile = fopen(wiitdbpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - CloseXMLDatabase(); - if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory - remove(wiitdbpathtmp); - } else { - remove(wiitdbpath); - rename(wiitdbpathtmp,wiitdbpath); - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory - } - } + snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); + snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); + rename(wiitdbpath,wiitdbpathtmp); + pfile = fopen(wiitdbpath, "wb"); + fwrite(file.data,1,file.size,pfile); + fclose(pfile); + free(file.data); + CloseXMLDatabase(); + if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory + remove(wiitdbpathtmp); + } else { + remove(wiitdbpath); + rename(wiitdbpathtmp,wiitdbpath); + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory + } + } msgTxt.SetTextf("%s", tr("Updating Language Files:")); updateLanguageFiles(); @@ -2741,15 +2760,15 @@ int ProgressUpdateWindow() { promptWindow.Append(&prTxt); msgTxt.SetTextf("%s Rev%i wad.", tr("Downloading"), newrev); s32 filesize; - if (Settings.beta_upgrades) { - char url[255]; - memset(&url, 0, 255); - sprintf((char *) &url, "http://usbloader-gui.googlecode.com/files/r%d.wad", newrev); - filesize = download_request((char *) &url); - } else { - filesize = download_request("http://www.techjawa.com/usbloadergx/ULNR.file");//for some reason it didn't download completely when saved as a wad. - } - + if (Settings.beta_upgrades) { + char url[255]; + memset(&url, 0, 255); + sprintf((char *) &url, "http://usbloader-gui.googlecode.com/files/r%d.wad", newrev); + filesize = download_request((char *) &url); + } else { + filesize = download_request("http://www.techjawa.com/usbloadergx/ULNR.file");//for some reason it didn't download completely when saved as a wad. + } + if (filesize > 0) { pfile = fopen(dolpath, "wb");//here we save the txt as a wad @@ -2829,7 +2848,7 @@ int ProgressUpdateWindow() { //sprintf(nipple, tr("The update wad has been saved as %s. Now let's try to install it."),dolpath); //WindowPrompt(0,nipple, tr("OK")); gprintf("\n\tinstall wad"); - error = Wad_Install(wadFile); + error = Wad_Install(wadFile); fclose(wadFile); if (error==0) { diarhea = remove(dolpath); @@ -2837,7 +2856,7 @@ int ProgressUpdateWindow() { WindowPrompt(tr("Success"),tr("The wad file was installed. But It could not be deleted from the SD card."),tr("OK")); } else { gprintf(" -> failed"); - sprintf(nipple, tr("The wad installation failed with error %ld"),error); + sprintf(nipple, tr("The wad installation failed with error %ld"),error); WindowPrompt(tr("Error"),nipple,tr("OK")); } } @@ -2851,7 +2870,7 @@ int ProgressUpdateWindow() { ShutdownAudio(); StopGX(); gprintf("\nRebooting"); - WII_Initialize(); + WII_Initialize(); WII_LaunchTitle(TITLE_ID(0x00010001,0x554c4e52)); } @@ -2868,7 +2887,7 @@ int ProgressUpdateWindow() { return 1; } -#else +#else int ProgressUpdateWindow() { gprintf("\nProgressUpdateWindow(not full channel)"); @@ -2879,9 +2898,9 @@ int ProgressUpdateWindow() { promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -3003,173 +3022,173 @@ int ProgressUpdateWindow() { } } - //make the URL to get XML based on our games - char XMLurl[3540]; - build_XML_URL(XMLurl,sizeof(XMLurl)); + //make the URL to get XML based on our games + char XMLurl[3540]; + build_XML_URL(XMLurl,sizeof(XMLurl)); - if (IsNetworkInit() && ret >= 0) { + if (IsNetworkInit() && ret >= 0) { - updatemode = WindowPrompt(tr("What do you want to update?"), 0, "USB Loader GX", tr("WiiTDB Files"), tr("Language File"), tr("Cancel")); - mainWindow->SetState(STATE_DISABLED); - promptWindow.SetState(STATE_DEFAULT); - mainWindow->ChangeFocus(&promptWindow); + updatemode = WindowPrompt(tr("What do you want to update?"), 0, "USB Loader GX", tr("WiiTDB Files"), tr("Language File"), tr("Cancel")); + mainWindow->SetState(STATE_DISABLED); + promptWindow.SetState(STATE_DEFAULT); + mainWindow->ChangeFocus(&promptWindow); - if (updatemode == 1) { + if(updatemode == 1) { - int newrev = CheckUpdate(); - if (newrev > 0) { + int newrev = CheckUpdate(); + if (newrev > 0) { - sprintf(msg, "Rev%i %s.", newrev, tr("available")); - int choice = WindowPrompt(msg, tr("How do you want to update?"), tr("Update DOL"), tr("Update All"), tr("Cancel")); - mainWindow->SetState(STATE_DISABLED); - promptWindow.SetState(STATE_DEFAULT); - mainWindow->ChangeFocus(&promptWindow); - if (choice == 1 || choice == 2) { - titleTxt.SetTextf("%s USB Loader GX", tr("Updating")); - msgTxt.SetPosition(0,100); - promptWindow.Append(&progressbarEmptyImg); - promptWindow.Append(&progressbarImg); - promptWindow.Append(&progressbarOutlineImg); - promptWindow.Append(&prTxt); - msgTxt.SetTextf("%s Rev%i", tr("Update to"), newrev); + sprintf(msg, "Rev%i %s.", newrev, tr("available")); + int choice = WindowPrompt(msg, tr("How do you want to update?"), tr("Update DOL"), tr("Update All"), tr("Cancel")); + mainWindow->SetState(STATE_DISABLED); + promptWindow.SetState(STATE_DEFAULT); + mainWindow->ChangeFocus(&promptWindow); + if (choice == 1 || choice == 2) { + titleTxt.SetTextf("%s USB Loader GX", tr("Updating")); + msgTxt.SetPosition(0,100); + promptWindow.Append(&progressbarEmptyImg); + promptWindow.Append(&progressbarImg); + promptWindow.Append(&progressbarOutlineImg); + promptWindow.Append(&prTxt); + msgTxt.SetTextf("%s Rev%i", tr("Update to"), newrev); + + s32 filesize; + if (Settings.beta_upgrades) { + char url[255]; + memset(&url, 0, 255); + sprintf((char *) &url, "http://usbloader-gui.googlecode.com/files/r%d.dol", newrev); + filesize = download_request((char *) &url); + } else { + filesize = download_request("http://www.techjawa.com/usbloadergx/boot.dol"); + } + if (filesize > 0) { + FILE * pfile; + pfile = fopen(dolpath, "wb"); + u8 * blockbuffer = new unsigned char[BLOCKSIZE]; + for (s32 i = 0; i < filesize; i += BLOCKSIZE) { + usleep(100); + prTxt.SetTextf("%i%%", (100*i/filesize)+1); + if ((Settings.wsprompt == yes) && (CFG.widescreen)) { + progressbarImg.SetTile(80*i/filesize); + } else { + progressbarImg.SetTile(100*i/filesize); + } + msg2Txt.SetTextf("%iKB/%iKB", i/1024, filesize/1024); - s32 filesize; - if (Settings.beta_upgrades) { - char url[255]; - memset(&url, 0, 255); - sprintf((char *) &url, "http://usbloader-gui.googlecode.com/files/r%d.dol", newrev); - filesize = download_request((char *) &url); - } else { - filesize = download_request("http://www.techjawa.com/usbloadergx/boot.dol"); + if (btn1.GetState() == STATE_CLICKED) { + fclose(pfile); + remove(dolpath); + failed = -1; + btn1.ResetState(); + break; + } + + u32 blksize; + blksize = (u32)(filesize - i); + if (blksize > BLOCKSIZE) + blksize = BLOCKSIZE; + + ret = network_read(blockbuffer, blksize); + if (ret != (s32) blksize) { + failed = -1; + ret = -1; + fclose(pfile); + remove(dolpath); + break; + } + fwrite(blockbuffer,1,blksize, pfile); } - if (filesize > 0) { - FILE * pfile; - pfile = fopen(dolpath, "wb"); - u8 * blockbuffer = new unsigned char[BLOCKSIZE]; - for (s32 i = 0; i < filesize; i += BLOCKSIZE) { - usleep(100); - prTxt.SetTextf("%i%%", (100*i/filesize)+1); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) { - progressbarImg.SetTile(80*i/filesize); - } else { - progressbarImg.SetTile(100*i/filesize); - } - msg2Txt.SetTextf("%iKB/%iKB", i/1024, filesize/1024); - - if (btn1.GetState() == STATE_CLICKED) { - fclose(pfile); - remove(dolpath); - failed = -1; - btn1.ResetState(); - break; - } - - u32 blksize; - blksize = (u32)(filesize - i); - if (blksize > BLOCKSIZE) - blksize = BLOCKSIZE; - - ret = network_read(blockbuffer, blksize); - if (ret != (s32) blksize) { - failed = -1; - ret = -1; - fclose(pfile); - remove(dolpath); - break; - } - fwrite(blockbuffer,1,blksize, pfile); + fclose(pfile); + delete blockbuffer; + if (!failed) { + //remove old + if (checkfile(dolpathsuccess)) { + remove(dolpathsuccess); } - fclose(pfile); - delete blockbuffer; - if (!failed) { - //remove old - if (checkfile(dolpathsuccess)) { - remove(dolpathsuccess); - } - //rename new to old - rename(dolpath, dolpathsuccess); + //rename new to old + rename(dolpath, dolpathsuccess); - if (choice == 2) { - //get the icon.png and the meta.xml - char xmliconpath[150]; - struct block file = downloadfile("http://www.techjawa.com/usbloadergx/meta.file"); - if (file.data != NULL) { - sprintf(xmliconpath, "%smeta.xml", Settings.update_path); - pfile = fopen(xmliconpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - } - file = downloadfile("http://www.techjawa.com/usbloadergx/icon.png"); - if (file.data != NULL) { - sprintf(xmliconpath, "%sicon.png", Settings.update_path); - pfile = fopen(xmliconpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - } - msgTxt.SetTextf("%s", tr("Updating WiiTDB.zip")); - char wiitdbpath[200]; - char wiitdbpathtmp[200]; - file = downloadfile(XMLurl); - if (file.data != NULL) { - subfoldercreate(Settings.titlestxt_path); - snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); - snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); - rename(wiitdbpath,wiitdbpathtmp); - pfile = fopen(wiitdbpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - CloseXMLDatabase(); - if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory - remove(wiitdbpathtmp); - } else { - remove(wiitdbpath); - rename(wiitdbpathtmp,wiitdbpath); - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory - } - } - msgTxt.SetTextf("%s", tr("Updating Language Files:")); - updateLanguageFiles(); + if (choice == 2) { + //get the icon.png and the meta.xml + char xmliconpath[150]; + struct block file = downloadfile("http://www.techjawa.com/usbloadergx/meta.file"); + if (file.data != NULL) { + sprintf(xmliconpath, "%smeta.xml", Settings.update_path); + pfile = fopen(xmliconpath, "wb"); + fwrite(file.data,1,file.size,pfile); + fclose(pfile); + free(file.data); } + file = downloadfile("http://www.techjawa.com/usbloadergx/icon.png"); + if (file.data != NULL) { + sprintf(xmliconpath, "%sicon.png", Settings.update_path); + pfile = fopen(xmliconpath, "wb"); + fwrite(file.data,1,file.size,pfile); + fclose(pfile); + free(file.data); + } + msgTxt.SetTextf("%s", tr("Updating WiiTDB.zip")); + char wiitdbpath[200]; + char wiitdbpathtmp[200]; + file = downloadfile(XMLurl); + if (file.data != NULL) { + subfoldercreate(Settings.titlestxt_path); + snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); + snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); + rename(wiitdbpath,wiitdbpathtmp); + pfile = fopen(wiitdbpath, "wb"); + fwrite(file.data,1,file.size,pfile); + fclose(pfile); + free(file.data); + CloseXMLDatabase(); + if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory + remove(wiitdbpathtmp); + } else { + remove(wiitdbpath); + rename(wiitdbpathtmp,wiitdbpath); + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory + } + } + msgTxt.SetTextf("%s", tr("Updating Language Files:")); + updateLanguageFiles(); } - } else { - failed = -1; } } else { - ret = -1; + failed = -1; } } else { - WindowPrompt(tr("No new updates."), 0, tr("OK")); ret = -1; } + } else { + WindowPrompt(tr("No new updates."), 0, tr("OK")); + ret = -1; + } - } else if (updatemode == 2) { + } else if(updatemode == 2) { msgTxt.SetTextf("%s", tr("Updating WiiTDB.zip")); char wiitdbpath[200]; char wiitdbpathtmp[200]; struct block file = downloadfile(XMLurl); if (file.data != NULL) { - subfoldercreate(Settings.titlestxt_path); - snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); - snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); - rename(wiitdbpath,wiitdbpathtmp); - FILE *pfile = fopen(wiitdbpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - CloseXMLDatabase(); - if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory - remove(wiitdbpathtmp); - } else { - remove(wiitdbpath); - rename(wiitdbpathtmp,wiitdbpath); - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory - } + subfoldercreate(Settings.titlestxt_path); + snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); + snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); + rename(wiitdbpath,wiitdbpathtmp); + FILE *pfile = fopen(wiitdbpath, "wb"); + fwrite(file.data,1,file.size,pfile); + fclose(pfile); + free(file.data); + CloseXMLDatabase(); + if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory + remove(wiitdbpathtmp); + } else { + remove(wiitdbpath); + rename(wiitdbpathtmp,wiitdbpath); + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory + } } ret = 1; - } else if (updatemode == 3) { + } else if(updatemode == 3) { msgTxt.SetTextf("%s", tr("Updating Language Files...")); updateLanguageFiles(); @@ -3184,10 +3203,10 @@ int ProgressUpdateWindow() { if (!failed && ret >= 0 && updatemode == 1) { WindowPrompt(tr("Successfully Updated") , tr("Restarting..."), tr("OK")); - loadStub(); - Set_Stub_Split(0x00010001,"UNEO"); + loadStub(); + Set_Stub_Split(0x00010001,"UNEO"); Sys_BackToLoader(); - } else if (updatemode > 0 && ret > 0) { + } else if(updatemode > 0 && ret > 0) { WindowPrompt(tr("Successfully Updated") , 0, tr("OK")); } @@ -3215,9 +3234,9 @@ int CodeDownload(const char *id) { promptWindow.SetPosition(0, -10); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -3392,9 +3411,9 @@ HBCWindowPrompt(const char *name, const char *coder, const char *version, trigD.SetButtonOnlyTrigger(-1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN, PAD_BUTTON_DOWN); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); GuiImageData btnOutline(imgPath, button_dialogue_box_png); @@ -3594,12 +3613,14 @@ HBCWindowPrompt(const char *name, const char *coder, const char *version, choice = 1; } else if (btn2.GetState() == STATE_CLICKED) { choice = 0; - } else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); - } else if ((arrowUpBtn.GetState()==STATE_CLICKED||arrowUpBtn.GetState()==STATE_HELD) ) { + } + else if (screenShotBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tscreenShotBtn clicked"); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf("...It's easy, mmmmmmKay"); + } + else if ((arrowUpBtn.GetState()==STATE_CLICKED||arrowUpBtn.GetState()==STATE_HELD) ) { if (long_descriptionTxt.GetFirstLine()>1) long_descriptionTxt.SetFirstLine(long_descriptionTxt.GetFirstLine()-1); usleep(60000); diff --git a/source/prompts/TitleBrowser.cpp b/source/prompts/TitleBrowser.cpp index e30c61b7..ba08b19a 100644 --- a/source/prompts/TitleBrowser.cpp +++ b/source/prompts/TitleBrowser.cpp @@ -62,113 +62,114 @@ extern wchar_t *gameFilter; *********************************************************************************/ int TitleBrowser(u32 type) { - u32 num_titles; - u32 titles[100] ATTRIBUTE_ALIGN(32); - u32 num_sys_titles; - u32 sys_titles[10] ATTRIBUTE_ALIGN(32); - s32 ret = -1; - int numtitle;//to get rid of a stupid compile wrning - //open the database file - FILE *f; - char path[100]; + u32 num_titles; + u32 titles[100] ATTRIBUTE_ALIGN(32); + u32 num_sys_titles; + u32 sys_titles[10] ATTRIBUTE_ALIGN(32); + s32 ret = -1; + int numtitle;//to get rid of a stupid compile wrning + //open the database file + FILE *f; + char path[100]; - ISFS_Initialize(); + ISFS_Initialize(); - sprintf(path,"%s/config/database.txt",bootDevice); - f = fopen(path, "r"); + sprintf(path,"%s/config/database.txt",bootDevice); + f = fopen(path, "r"); - // Get count of titles of our requested type - ret = getTitles_TypeCount(type, &num_titles); - if (ret < 0) { - //printf("\tError! Can't get count of titles! (ret = %d)\n", ret); - //exit(1); - } + // Get count of titles of our requested type + ret = getTitles_TypeCount(type, &num_titles); + if (ret < 0) { + //printf("\tError! Can't get count of titles! (ret = %d)\n", ret); + //exit(1); + } - // Get titles of our requested type - ret = getTitles_Type(type, titles, num_titles); - if (ret < 0) { - //printf("\tError! Can't get list of titles! (ret = %d)\n", ret); - //exit(1); - } + // Get titles of our requested type + ret = getTitles_Type(type, titles, num_titles); + if (ret < 0) { + //printf("\tError! Can't get list of titles! (ret = %d)\n", ret); + //exit(1); + } - // Get count of system titles - ret = getTitles_TypeCount(0x00010002, &num_sys_titles); - if (ret < 0) { - //printf("\tError! Can't get count of titles! (ret = %d)\n", ret); - //exit(1); - } + // Get count of system titles + ret = getTitles_TypeCount(0x00010002, &num_sys_titles); + if (ret < 0) { + //printf("\tError! Can't get count of titles! (ret = %d)\n", ret); + //exit(1); + } - // Get system titles - ret = getTitles_Type(0x00010002, sys_titles, num_sys_titles); - if (ret < 0) { - //printf("\tError! Can't get list of titles! (ret = %d)\n", ret); - //exit(1); - } + // Get system titles + ret = getTitles_Type(0x00010002, sys_titles, num_sys_titles); + if (ret < 0) { + //printf("\tError! Can't get list of titles! (ret = %d)\n", ret); + //exit(1); + } - //this array will hold all the names for the titles so we only have to get them one time - char name[num_titles+num_sys_titles][50]; + //this array will hold all the names for the titles so we only have to get them one time + char name[num_titles+num_sys_titles][50]; - customOptionList options3(num_titles+num_sys_titles+1); - //write the titles on the option browser - u32 i = 0; + customOptionList options3(num_titles+num_sys_titles+1); + //write the titles on the option browser + u32 i = 0; - //first add the good stuff - while (i < num_titles) { - //start from the beginning of the file each loop - if (f)rewind(f); - //char name[50]; - char text[15]; - strcpy(name[i],"");//make sure name is empty - u8 found=0; - //set the title's name, number, ID to text - sprintf(text, "%s", titleText(type, titles[i])); + //first add the good stuff + while (i < num_titles) { + //start from the beginning of the file each loop + if (f)rewind(f); + //char name[50]; + char text[15]; + strcpy(name[i],"");//make sure name is empty + u8 found=0; + //set the title's name, number, ID to text + sprintf(text, "%s", titleText(type, titles[i])); - //get name from database cause i dont like the ADT function - char line[200]; - char tmp[50]; - snprintf(tmp,50," "); + //get name from database cause i dont like the ADT function + char line[200]; + char tmp[50]; + snprintf(tmp,50," "); + + //check if the content.bin is on the SD card for that game + //if there is content.bin,then the game is on the SDmenu and not the wii + sprintf(line,"SD:/private/wii/title/%s/content.bin",text); + if (!checkfile(line)) + { + if (f) { + while (fgets(line, sizeof(line), f)) { + if (line[0]== text[0]&& + line[1]== text[1]&& + line[2]== text[2]) { + int j=0; + found=1; + for (j=0;(line[j+4]!='\0' || j<51);j++) - //check if the content.bin is on the SD card for that game - //if there is content.bin,then the game is on the SDmenu and not the wii - sprintf(line,"SD:/private/wii/title/%s/content.bin",text); - if (!checkfile(line)) { - if (f) { - while (fgets(line, sizeof(line), f)) { - if (line[0]== text[0]&& - line[1]== text[1]&& - line[2]== text[2]) { - int j=0; - found=1; - for (j=0;(line[j+4]!='\0' || j<51);j++) + tmp[j]=line[j+4]; + snprintf(name[i],sizeof(name[i]),"%s",tmp); + //break; + } + } + } + if (!found) { + if (getName00(name[i], TITLE_ID(type, titles[i]),CONF_GetLanguage()*2)>=0) + found=2; - tmp[j]=line[j+4]; - snprintf(name[i],sizeof(name[i]),"%s",tmp); - //break; - } - } - } - if (!found) { - if (getName00(name[i], TITLE_ID(type, titles[i]),CONF_GetLanguage()*2)>=0) - found=2; + if (!found) { + if (getNameBN(name[i], TITLE_ID(type, titles[i]))>=0) + found=3; - if (!found) { - if (getNameBN(name[i], TITLE_ID(type, titles[i]))>=0) - found=3; + if (!found) + snprintf(name[i],sizeof(name[i]),"Unknown Title (%08x)",titles[i]); + } + } - if (!found) - snprintf(name[i],sizeof(name[i]),"Unknown Title (%08x)",titles[i]); - } - } - - //set the text to the option browser - options3.SetName(i, "%s",text); - options3.SetValue(i, "%s",name[i]); - //options3.SetValue(i, " (%08x) %s",titles[i],name[i]);//use this line to show the number to call to launch the channel - //move on to the next title - } + //set the text to the option browser + options3.SetName(i, "%s",text); + options3.SetValue(i, "%s",name[i]); + //options3.SetValue(i, " (%08x) %s",titles[i],name[i]);//use this line to show the number to call to launch the channel + //move on to the next title + } i++; } @@ -239,9 +240,9 @@ int TitleBrowser(u32 type) { ResumeNetworkWait(); GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; @@ -333,12 +334,12 @@ int TitleBrowser(u32 type) { else if (wifiBtn.GetState() == STATE_CLICKED) { - ResumeNetworkWait(); - wifiBtn.ResetState(); + ResumeNetworkWait(); + wifiBtn.ResetState(); } if (IsNetworkInit()) { - wifiBtn.SetAlpha(255); + wifiBtn.SetAlpha(255); } ret = optionBrowser3.GetClickedOption(); @@ -393,7 +394,7 @@ int TitleBrowser(u32 type) { char temp[112]; //prompt to boot selected title - snprintf(temp, sizeof(temp), tr("%s : %s May not boot correctly if your System Menu is not up to date."),text,name[ret]); + snprintf(temp, sizeof(temp), tr("%s : %s May not boot correctly if your System Menu is not up to date."),text,name[ret]); int choice = WindowPrompt(tr("Boot?"), temp, tr("OK"), tr("Cancel")); if (choice) {//if they say yes @@ -418,181 +419,185 @@ int TitleBrowser(u32 type) { } } - if (infilesize > 0) { + if(infilesize > 0) { - char filesizetxt[50]; - char temp[50]; - char filepath[100]; + char filesizetxt[50]; + char temp[50]; + char filepath[100]; // u32 read = 0; + + //make sure there is a folder for this to be saved in + struct stat st; + snprintf(filepath, sizeof(filepath), "%s/wad/", bootDevice); + if (stat(filepath, &st) != 0) { + if (subfoldercreate(filepath) != 1) { + WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + } + } + snprintf(filepath, sizeof(filepath), "%s/wad/tmp.tmp", bootDevice); + - //make sure there is a folder for this to be saved in - struct stat st; - snprintf(filepath, sizeof(filepath), "%s/wad/", bootDevice); - if (stat(filepath, &st) != 0) { - if (subfoldercreate(filepath) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); - } - } - snprintf(filepath, sizeof(filepath), "%s/wad/tmp.tmp", bootDevice); + if (infilesize < MB_SIZE) + snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fKB"), infilesize/KB_SIZE); + else + snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fMB"), infilesize/MB_SIZE); + snprintf(temp, sizeof(temp), tr("Load file from: %s ?"), GetIncommingIP()); - if (infilesize < MB_SIZE) - snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fKB"), infilesize/KB_SIZE); - else - snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fMB"), infilesize/MB_SIZE); + int choice = WindowPrompt(filesizetxt, temp, tr("OK"), tr("Cancel")); + gprintf("\nchoice:%d",choice); - snprintf(temp, sizeof(temp), tr("Load file from: %s ?"), GetIncommingIP()); + if (choice == 1) { - int choice = WindowPrompt(filesizetxt, temp, tr("OK"), tr("Cancel")); - gprintf("\nchoice:%d",choice); + u32 read = 0; + u8 *temp = NULL; + int len = NETWORKBLOCKSIZE; + temp = (u8 *) malloc(infilesize); - if (choice == 1) { + bool error = false; + u8 *ptr = temp; + gprintf("\nrecieving shit"); + while (read < infilesize) { - u32 read = 0; - u8 *temp = NULL; - int len = NETWORKBLOCKSIZE; - temp = (u8 *) malloc(infilesize); + ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true); - bool error = false; - u8 *ptr = temp; - gprintf("\nrecieving shit"); - while (read < infilesize) { + if (infilesize - read < (u32) len) + len = infilesize-read; + else + len = NETWORKBLOCKSIZE; - ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true); + int result = network_read(ptr, len); - if (infilesize - read < (u32) len) - len = infilesize-read; - else - len = NETWORKBLOCKSIZE; + if (result < 0) { + WindowPrompt(tr("Error while transfering data."), 0, tr("OK")); + error = true; + break; + } + if (!result) { + gprintf("\n!RESULT"); + break; + } + ptr += result; + read += result; + } + ProgressStop(); - int result = network_read(ptr, len); - - if (result < 0) { - WindowPrompt(tr("Error while transfering data."), 0, tr("OK")); - error = true; - break; - } - if (!result) { - gprintf("\n!RESULT"); - break; - } - ptr += result; - read += result; - } - ProgressStop(); - - char filename[101]; - char tmptxt[200]; + char filename[101]; + char tmptxt[200]; - //bool installWad=0; - if (!error) { - gprintf("\nno error yet"); + //bool installWad=0; + if (!error) { + gprintf("\nno error yet"); - network_read((u8*) &filename, 100); - gprintf("\nfilename: %s",filename); + network_read((u8*) &filename, 100); + gprintf("\nfilename: %s",filename); - // Do we need to unzip this thing? - if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) { - gprintf("\nusing newer wiiload version"); + // Do we need to unzip this thing? + if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) { + gprintf("\nusing newer wiiload version"); - if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed - gprintf("\ntrying to uncompress"); - // It's compressed, uncompress - u8 *unc = (u8 *) malloc(uncfilesize); - uLongf f = uncfilesize; - error = uncompress(unc, &f, temp, infilesize) != Z_OK; - uncfilesize = f; + if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed + gprintf("\ntrying to uncompress"); + // It's compressed, uncompress + u8 *unc = (u8 *) malloc(uncfilesize); + uLongf f = uncfilesize; + error = uncompress(unc, &f, temp, infilesize) != Z_OK; + uncfilesize = f; - free(temp); - temp = unc; - } - } + free(temp); + temp = unc; + } + } - if (!error) { - sprintf(tmptxt,"%s",filename); - //if we got a wad - if (strcasestr(tmptxt,".wad")) { - FILE *file = fopen(filepath, "wb"); - fwrite(temp, 1, (uncfilesize>0?uncfilesize:infilesize), file); - fclose(file); + if (!error) { + sprintf(tmptxt,"%s",filename); + //if we got a wad + if (strcasestr(tmptxt,".wad")) { + FILE *file = fopen(filepath, "wb"); + fwrite(temp, 1, (uncfilesize>0?uncfilesize:infilesize), file); + fclose(file); - sprintf(tmptxt,"%s/wad/%s",bootDevice,filename); - if (checkfile(tmptxt))remove(tmptxt); - rename(filepath, tmptxt); + sprintf(tmptxt,"%s/wad/%s",bootDevice,filename); + if (checkfile(tmptxt))remove(tmptxt); + rename(filepath, tmptxt); - //check and make sure the wad we just saved is the correct size - u32 lSize; - file = fopen(tmptxt, "rb"); + //check and make sure the wad we just saved is the correct size + u32 lSize; + file = fopen(tmptxt, "rb"); - // obtain file size: - fseek (file , 0 , SEEK_END); - lSize = ftell (file); + // obtain file size: + fseek (file , 0 , SEEK_END); + lSize = ftell (file); - rewind (file); - if (lSize==(uncfilesize>0?uncfilesize:infilesize)) { - gprintf("\nsize is ok"); - int pick = WindowPrompt(tr(" Wad Saved as:"), tmptxt, tr("Install"),tr("Uninstall"),tr("Cancel")); - //install or uninstall it - if (pick==1) { - HaltGui(); - w.Remove(&titleTxt); - w.Remove(&cancelBtn); - w.Remove(&wifiBtn); - w.Remove(&optionBrowser3); - ResumeGui(); + rewind (file); + if (lSize==(uncfilesize>0?uncfilesize:infilesize)) { + gprintf("\nsize is ok"); + int pick = WindowPrompt(tr(" Wad Saved as:"), tmptxt, tr("Install"),tr("Uninstall"),tr("Cancel")); + //install or uninstall it + if (pick==1) + { + HaltGui(); + w.Remove(&titleTxt); + w.Remove(&cancelBtn); + w.Remove(&wifiBtn); + w.Remove(&optionBrowser3); + ResumeGui(); - Wad_Install(file); + Wad_Install(file); - HaltGui(); - w.Append(&titleTxt); - w.Append(&cancelBtn); - w.Append(&wifiBtn); - w.Append(&optionBrowser3); - ResumeGui(); + HaltGui(); + w.Append(&titleTxt); + w.Append(&cancelBtn); + w.Append(&wifiBtn); + w.Append(&optionBrowser3); + ResumeGui(); - } - if (pick==2)Wad_Uninstall(file); - } else gprintf("\nBad size"); - //close that beast, we're done with it - fclose (file); + } + if (pick==2)Wad_Uninstall(file); + } + else gprintf("\nBad size"); + //close that beast, we're done with it + fclose (file); - //do we want to keep the file in the wad folder - if (WindowPrompt(tr("Delete ?"), tmptxt, tr("Delete"),tr("Keep"))!=0) - remove(tmptxt); - } else { - WindowPrompt(tr("ERROR:"), tr("Not a WAD file."), tr("OK")); - } - } - } + //do we want to keep the file in the wad folder + if (WindowPrompt(tr("Delete ?"), tmptxt, tr("Delete"),tr("Keep"))!=0) + remove(tmptxt); + } + else { + WindowPrompt(tr("ERROR:"), tr("Not a WAD file."), tr("OK")); + } + } + } - if (error || read != infilesize) { - WindowPrompt(tr("Error:"), tr("No data could be read."), tr("OK")); + if (error || read != infilesize) { + WindowPrompt(tr("Error:"), tr("No data could be read."), tr("OK")); - } - if (temp)free(temp); - } + } + if(temp)free(temp); + } - CloseConnection(); - ResumeNetworkWait(); + CloseConnection(); + ResumeNetworkWait(); } if (cancelBtn.GetState() == STATE_CLICKED) { //break the loop and end the function exit = true; ret = -10; - } else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); } + else if (screenShotBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tscreenShotBtn clicked"); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf("...It's easy, mmmmmmKay"); + } } CloseConnection(); diff --git a/source/prompts/filebrowser.cpp b/source/prompts/filebrowser.cpp index 3db06c7a..07db483b 100644 --- a/source/prompts/filebrowser.cpp +++ b/source/prompts/filebrowser.cpp @@ -47,18 +47,22 @@ BROWSERINFO *browser = NULL; * FileFilterCallbacks * return: 1-visible 0-hidden ***************************************************************************/ -int noDIRS(BROWSERENTRY *Entry, void* Args) { - return !Entry->isdir; +int noDIRS(BROWSERENTRY *Entry, void* Args) +{ + return !Entry->isdir; } -int noFILES(BROWSERENTRY *Entry, void* Args) { - return Entry->isdir; +int noFILES(BROWSERENTRY *Entry, void* Args) +{ + return Entry->isdir; } -int noEXT(BROWSERENTRY *Entry, void* Args) { - if (!Entry->isdir) { - char *cptr = strrchr(Entry->displayname, '.'); - if (cptr && cptr!= Entry->displayname) *cptr = 0; - } - return 1; +int noEXT(BROWSERENTRY *Entry, void* Args) +{ + if(!Entry->isdir) + { + char *cptr = strrchr(Entry->displayname, '.'); + if(cptr && cptr!= Entry->displayname) *cptr = 0; + } + return 1; } void ResetBrowser(BROWSERINFO *browser); @@ -67,46 +71,49 @@ void ResetBrowser(BROWSERINFO *browser); * Clears the file browser memory, and allocates one initial entry ***************************************************************************/ int InitBrowsers() { - curDevice = -1; - browsers.clear(); - browser = NULL; - char rootdir[ROOTDIRLEN]; - for (int i=3; iname, "stdnull") && devoptab_list[i]->write_r != NULL) { - snprintf(rootdir, sizeof(rootdir) , "%s:/", devoptab_list[i]->name); - if (DIR_ITER *dir = diropen(rootdir)) { - dirclose(dir); - BROWSERINFO browser; - browser.dir[0] = '\0'; - strcpy(browser.rootdir, rootdir); - ResetBrowser(&browser); - browsers.push_back(browser); - } - } - } - if (!browsers.size()) return -1; - curDevice = 0; - browser = &browsers[curDevice]; - return 0; + curDevice = -1; + browsers.clear(); + browser = NULL; + char rootdir[ROOTDIRLEN]; + for(int i=3; iname, "stdnull") && devoptab_list[i]->write_r != NULL) + { + snprintf(rootdir, sizeof(rootdir) , "%s:/", devoptab_list[i]->name); + if(DIR_ITER *dir = diropen(rootdir)) + { + dirclose(dir); + BROWSERINFO browser; + browser.dir[0] = '\0'; + strcpy(browser.rootdir, rootdir); + ResetBrowser(&browser); + browsers.push_back(browser); + } + } + } + if(!browsers.size()) return -1; + curDevice = 0; + browser = &browsers[curDevice]; + return 0; } /**************************************************************************** * ResetBrowser() * Clears the file browser memory, and allocates one initial entry ***************************************************************************/ void ResetBrowser(BROWSERINFO *browser) { - browser->pageIndex = 0; - browser->browserList.clear(); - /* - // Clear any existing values - if (browser->browserList != NULL) { - free(browser->browserList); - browser->browserList = NULL; - } - // set aside space for 1 entry - browser->browserList = (BROWSERENTRY *)malloc(sizeof(BROWSERENTRY)); - if(browser->browserList) - memset(browser->browserList, 0, sizeof(BROWSERENTRY)); - */ + browser->pageIndex = 0; + browser->browserList.clear(); +/* + // Clear any existing values + if (browser->browserList != NULL) { + free(browser->browserList); + browser->browserList = NULL; + } + // set aside space for 1 entry + browser->browserList = (BROWSERENTRY *)malloc(sizeof(BROWSERENTRY)); + if(browser->browserList) + memset(browser->browserList, 0, sizeof(BROWSERENTRY)); +*/ } /**************************************************************************** @@ -120,133 +127,154 @@ void ResetBrowser(BROWSERINFO *browser) { ***************************************************************************/ //int FileSortCallback(const void *f1, const void *f2) { bool operator< (const BROWSERENTRY &f1, const BROWSERENTRY &f2) { - /* Special case for implicit directories */ - if (f1.filename[0] == '.' || f2.filename[0] == '.') { - if (strcmp(f1.filename, ".") == 0) { - return true; - } - if (strcmp(f2.filename, ".") == 0) { - return false; - } - if (strcmp(f1.filename, "..") == 0) { - return true; - } - if (strcmp(f2.filename, "..") == 0) { - return false; - } - } + /* Special case for implicit directories */ + if (f1.filename[0] == '.' || f2.filename[0] == '.') { + if (strcmp(f1.filename, ".") == 0) { + return true; + } + if (strcmp(f2.filename, ".") == 0) { + return false; + } + if (strcmp(f1.filename, "..") == 0) { + return true; + } + if (strcmp(f2.filename, "..") == 0) { + return false; + } + } - /* If one is a file and one is a directory the directory is first. */ - if (f1.isdir && !(f2.isdir)) return true; - if (!(f1.isdir) && f2.isdir) return false; + /* If one is a file and one is a directory the directory is first. */ + if (f1.isdir && !(f2.isdir)) return true; + if (!(f1.isdir) && f2.isdir) return false; - return stricmp(f1.filename, f2.filename)<0; + return stricmp(f1.filename, f2.filename)<0; } -int ParseFilter(FILTERCASCADE *Filter, BROWSERENTRY* Entry) { - while (Filter) { - if (Filter->filter && Filter->filter(Entry, Filter->filter_args) == 0) - return 0; - Filter = Filter->next; - } - return 1; +int ParseFilter(FILTERCASCADE *Filter, BROWSERENTRY* Entry) +{ + while(Filter) + { + if(Filter->filter && Filter->filter(Entry, Filter->filter_args) == 0) + return 0; + Filter = Filter->next; + } + return 1; } /*************************************************************************** * Browse subdirectories **************************************************************************/ int ParseDirectory(const char* Path, int Flags, FILTERCASCADE *Filter) { - DIR_ITER *dir = NULL; - char fulldir[MAXPATHLEN]; - char filename[MAXPATHLEN]; - struct stat filestat; - unsigned int i; + DIR_ITER *dir = NULL; + char fulldir[MAXPATHLEN]; + char filename[MAXPATHLEN]; + struct stat filestat; + unsigned int i; - if (curDevice == -1) - if (InitBrowsers()) return -1; // InitBrowser fails + if(curDevice == -1) + if(InitBrowsers()) return -1; // InitBrowser fails - if (Path) { // note in this codeblock use filename temporary - strlcpy(fulldir, Path, sizeof(fulldir)); - if (*fulldir && fulldir[strlen(fulldir)-1] != '/') { // a file - char * chrp = strrchr(fulldir, '/'); - if (chrp) chrp[1] = 0; - } - if (strchr(fulldir, ':') == NULL) { // Path has no device device - getcwd(filename, sizeof(filename)); // save the current working dir - if (*fulldir==0) // if path is empty - strlcpy(fulldir, filename, sizeof(fulldir)); // we use the current working dir - else { // path is not empty - if (chdir(fulldir)); { // sets the path to concatenate and validate - if (Flags & (FB_TRYROOTDIR | FB_TRYSTDDEV)) - if (chdir("/") && !(Flags & FB_TRYSTDDEV))// try to set root if is needed - return -1; - } - if (getcwd(fulldir, sizeof(fulldir))) return -1; // gets the concatenated current working dir - chdir(filename); // restore the saved cwd - } - } - for (i=0; idir, &fulldir[strlen(browser->rootdir)]); - } else if (Flags & FB_TRYSTDDEV) { - curDevice = 0; - browser = &browsers[curDevice]; // when no browser was found and - browser->dir[0] = 0; // we alowed try StdDevice and try RootDir - strlcpy(fulldir, browser->rootdir, sizeof(fulldir)); // set the first browser with root-dir - } else - return -1; - } else - snprintf(fulldir, sizeof(fulldir), "%s%s", browser->rootdir, browser->dir); + if(Path) // note in this codeblock use filename temporary + { + strlcpy(fulldir, Path, sizeof(fulldir)); + if(*fulldir && fulldir[strlen(fulldir)-1] != '/') // a file + { + char * chrp = strrchr(fulldir, '/'); + if(chrp) chrp[1] = 0; + } + if(strchr(fulldir, ':') == NULL) // Path has no device device + { + getcwd(filename, sizeof(filename)); // save the current working dir + if(*fulldir==0) // if path is empty + strlcpy(fulldir, filename, sizeof(fulldir)); // we use the current working dir + else + { // path is not empty + if(chdir(fulldir)); // sets the path to concatenate and validate + { + if(Flags & (FB_TRYROOTDIR | FB_TRYSTDDEV)) + if(chdir("/") && !(Flags & FB_TRYSTDDEV))// try to set root if is needed + return -1; + } + if(getcwd(fulldir, sizeof(fulldir))) return -1; // gets the concatenated current working dir + chdir(filename); // restore the saved cwd + } + } + for(i=0; idir, &fulldir[strlen(browser->rootdir)]); + } + else if(Flags & FB_TRYSTDDEV) + { + curDevice = 0; + browser = &browsers[curDevice]; // when no browser was found and + browser->dir[0] = 0; // we alowed try StdDevice and try RootDir + strlcpy(fulldir, browser->rootdir, sizeof(fulldir)); // set the first browser with root-dir + } + else + return -1; + } + else + snprintf(fulldir, sizeof(fulldir), "%s%s", browser->rootdir, browser->dir); - // reset browser - ResetBrowser(browser); + // reset browser + ResetBrowser(browser); - // open the directory - if ((dir = diropen(fulldir)) == NULL) { - if (Flags & FB_TRYROOTDIR) { - browser->dir[0] = 0; - if ((dir = diropen(browser->rootdir)) == NULL) - return -1; - } else - return -1; - } + // open the directory + if((dir = diropen(fulldir)) == NULL) + { + if(Flags & FB_TRYROOTDIR) + { + browser->dir[0] = 0; + if((dir = diropen(browser->rootdir)) == NULL) + return -1; + } + else + return -1; + } - while (dirnext(dir,filename,&filestat) == 0) { - if (strcmp(filename,".") != 0) { - BROWSERENTRY newEntry; - memset(&newEntry, 0, sizeof(BROWSERENTRY)); // clear the new entry - strlcpy(newEntry.filename, filename, sizeof(newEntry.filename)); - strlcpy(newEntry.displayname, filename, sizeof(newEntry.displayname)); - newEntry.length = filestat.st_size; - newEntry.isdir = (filestat.st_mode & S_IFDIR) == 0 ? 0 : 1; // flag this as a dir - if (ParseFilter(Filter, &newEntry)) - browser->browserList.push_back(newEntry); - } - } + while (dirnext(dir,filename,&filestat) == 0) + { + if (strcmp(filename,".") != 0) + { + BROWSERENTRY newEntry; + memset(&newEntry, 0, sizeof(BROWSERENTRY)); // clear the new entry + strlcpy(newEntry.filename, filename, sizeof(newEntry.filename)); + strlcpy(newEntry.displayname, filename, sizeof(newEntry.displayname)); + newEntry.length = filestat.st_size; + newEntry.isdir = (filestat.st_mode & S_IFDIR) == 0 ? 0 : 1; // flag this as a dir + if(ParseFilter(Filter, &newEntry)) + browser->browserList.push_back(newEntry); + } + } - // close directory - dirclose(dir); + // close directory + dirclose(dir); - // Sort the file list - std::sort(browser->browserList.begin(), browser->browserList.end()); - return 0; + // Sort the file list + std::sort(browser->browserList.begin(), browser->browserList.end()); + return 0; } -int ParseDirectory(int Device, int Flags, FILTERCASCADE *Filter) { - if (Device >=0 && Device < (int)browsers.size()) { - int old_curDevice = curDevice; - curDevice = Device; - browser = &browsers[curDevice]; - if (ParseDirectory((char*)NULL, Flags, Filter) == 0) return 0; - curDevice = old_curDevice; - browser = &browsers[old_curDevice]; - } - return -1; +int ParseDirectory(int Device, int Flags, FILTERCASCADE *Filter) +{ + if(Device >=0 && Device < (int)browsers.size()) + { + int old_curDevice = curDevice; + curDevice = Device; + browser = &browsers[curDevice]; + if(ParseDirectory((char*)NULL, Flags, Filter) == 0) return 0; + curDevice = old_curDevice; + browser = &browsers[old_curDevice]; + } + return -1; } /**************************************************************************** @@ -254,238 +282,255 @@ int ParseDirectory(int Device, int Flags, FILTERCASCADE *Filter) { * Displays a list of files on the selected path ***************************************************************************/ -int BrowseDevice(char * Path, int Path_size, int Flags, FILTERCASCADE *Filter/*=NULL*/) { - int result=-1; - int i; +int BrowseDevice(char * Path, int Path_size, int Flags, FILTERCASCADE *Filter/*=NULL*/) +{ + int result=-1; + int i; - if (InitBrowsers() || ParseDirectory(Path, Flags, Filter)) { - WindowPrompt(tr("Error"),0,tr("OK")); - return -1; - } - int menu = MENU_NONE; + if(InitBrowsers() || ParseDirectory(Path, Flags, Filter)) + { + WindowPrompt(tr("Error"),0,tr("OK")); + return -1; + } + int menu = MENU_NONE; - /* - GuiText titleTxt("Browse Files", 28, (GXColor){0, 0, 0, 230}); - titleTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - titleTxt.SetPosition(70,20); - */ - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + /* + GuiText titleTxt("Browse Files", 28, (GXColor){0, 0, 0, 230}); + titleTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + titleTxt.SetPosition(70,20); + */ + GuiTrigger trigA; + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiImageData folderImgData(icon_folder_png); - GuiImage folderImg(&folderImgData); - GuiButton folderBtn(folderImg.GetWidth(), folderImg.GetHeight()); - folderBtn.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - folderBtn.SetPosition(-210, -145); - folderBtn.SetImage(&folderImg); - folderBtn.SetTrigger(&trigA); - folderBtn.SetEffectGrow(); + GuiImageData folderImgData(icon_folder_png); + GuiImage folderImg(&folderImgData); + GuiButton folderBtn(folderImg.GetWidth(), folderImg.GetHeight()); + folderBtn.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + folderBtn.SetPosition(-210, -145); + folderBtn.SetImage(&folderImg); + folderBtn.SetTrigger(&trigA); + folderBtn.SetEffectGrow(); + + char imgPath[100]; + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + GuiText ExitBtnTxt(tr("Cancel"), 24, (GXColor) {0, 0, 0, 255}); + GuiImage ExitBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { + ExitBtnTxt.SetWidescreen(CFG.widescreen); + ExitBtnImg.SetWidescreen(CFG.widescreen); + } + GuiButton ExitBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); + ExitBtn.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + ExitBtn.SetPosition(-40, -35); + ExitBtn.SetLabel(&ExitBtnTxt); + ExitBtn.SetImage(&ExitBtnImg); + ExitBtn.SetTrigger(&trigA); + ExitBtn.SetTrigger(&trigB); + ExitBtn.SetEffectGrow(); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - GuiText ExitBtnTxt(tr("Cancel"), 24, (GXColor) {0, 0, 0, 255}); - GuiImage ExitBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - ExitBtnTxt.SetWidescreen(CFG.widescreen); - ExitBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton ExitBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); - ExitBtn.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); - ExitBtn.SetPosition(-40, -35); - ExitBtn.SetLabel(&ExitBtnTxt); - ExitBtn.SetImage(&ExitBtnImg); - ExitBtn.SetTrigger(&trigA); - ExitBtn.SetTrigger(&trigB); - ExitBtn.SetEffectGrow(); + GuiText usbBtnTxt(browsers[(curDevice+1)%browsers.size()].rootdir, 24, (GXColor) {0, 0, 0, 255}); + GuiImage usbBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { + usbBtnTxt.SetWidescreen(CFG.widescreen); + usbBtnImg.SetWidescreen(CFG.widescreen); + } + GuiButton usbBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); + usbBtn.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + usbBtn.SetPosition(0, -35); + usbBtn.SetLabel(&usbBtnTxt); + usbBtn.SetImage(&usbBtnImg); + usbBtn.SetTrigger(&trigA); + usbBtn.SetEffectGrow(); - GuiText usbBtnTxt(browsers[(curDevice+1)%browsers.size()].rootdir, 24, (GXColor) {0, 0, 0, 255}); - GuiImage usbBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - usbBtnTxt.SetWidescreen(CFG.widescreen); - usbBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton usbBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); - usbBtn.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - usbBtn.SetPosition(0, -35); - usbBtn.SetLabel(&usbBtnTxt); - usbBtn.SetImage(&usbBtnImg); - usbBtn.SetTrigger(&trigA); - usbBtn.SetEffectGrow(); + GuiText okBtnTxt(tr("OK"), 22, THEME.prompttext); + GuiImage okBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { + okBtnTxt.SetWidescreen(CFG.widescreen); + okBtnImg.SetWidescreen(CFG.widescreen); + } + GuiButton okBtn(&okBtnImg,&okBtnImg, 0, 4, 40, -35, &trigA, &btnSoundOver, btnClick2,1); + okBtn.SetLabel(&okBtnTxt); - GuiText okBtnTxt(tr("OK"), 22, THEME.prompttext); - GuiImage okBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - okBtnTxt.SetWidescreen(CFG.widescreen); - okBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton okBtn(&okBtnImg,&okBtnImg, 0, 4, 40, -35, &trigA, &btnSoundOver, btnClick2,1); - okBtn.SetLabel(&okBtnTxt); + GuiFileBrowser fileBrowser(396, 248); + fileBrowser.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + fileBrowser.SetPosition(0, 120); - GuiFileBrowser fileBrowser(396, 248); - fileBrowser.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - fileBrowser.SetPosition(0, 120); + GuiImageData Address(addressbar_textbox_png); + GuiText AdressText(NULL, 20, (GXColor) { 0, 0, 0, 255}); + AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); + AdressText.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + AdressText.SetPosition(20, 0); + AdressText.SetMaxWidth(Address.GetWidth()-40, GuiText::SCROLL); + GuiImage AdressbarImg(&Address); + GuiButton Adressbar(Address.GetWidth(), Address.GetHeight()); + Adressbar.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + Adressbar.SetPosition(0, fileBrowser.GetTop()-45); + Adressbar.SetImage(&AdressbarImg); + Adressbar.SetLabel(&AdressText); - GuiImageData Address(addressbar_textbox_png); - GuiText AdressText(NULL, 20, (GXColor) {0, 0, 0, 255}); - AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); - AdressText.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - AdressText.SetPosition(20, 0); - AdressText.SetMaxWidth(Address.GetWidth()-40, GuiText::SCROLL); - GuiImage AdressbarImg(&Address); - GuiButton Adressbar(Address.GetWidth(), Address.GetHeight()); - Adressbar.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - Adressbar.SetPosition(0, fileBrowser.GetTop()-45); - Adressbar.SetImage(&AdressbarImg); - Adressbar.SetLabel(&AdressText); - - HaltGui(); - GuiWindow w(screenwidth, screenheight); - w.Append(&ExitBtn); + HaltGui(); + GuiWindow w(screenwidth, screenheight); + w.Append(&ExitBtn); // w.Append(&titleTxt); - w.Append(&fileBrowser); - w.Append(&Adressbar); - w.Append(&okBtn); - if (!(Flags & FB_NOFOLDER_BTN)) - w.Append(&folderBtn); - if (browsers.size()>1 && !(Flags & FB_NODEVICE_BTN)) - w.Append(&usbBtn); - mainWindow->Append(&w); - ResumeGui(); - int clickedIndex = -1; - while (menu == MENU_NONE) { - VIDEO_WaitVSync(); + w.Append(&fileBrowser); + w.Append(&Adressbar); + w.Append(&okBtn); + if(!(Flags & FB_NOFOLDER_BTN)) + w.Append(&folderBtn); + if(browsers.size()>1 && !(Flags & FB_NODEVICE_BTN)) + w.Append(&usbBtn); + mainWindow->Append(&w); + ResumeGui(); + int clickedIndex = -1; + while (menu == MENU_NONE) { + VIDEO_WaitVSync(); - if (shutdown == 1) - Sys_Shutdown(); + if (shutdown == 1) + Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); + if (reset == 1) + Sys_Reboot(); - for (i=0; iGetState() == STATE_CLICKED) { - fileBrowser.fileList[i]->ResetState(); + for (i=0; iGetState() == STATE_CLICKED) { + fileBrowser.fileList[i]->ResetState(); - clickedIndex = browser->pageIndex + i; - bool pathCanged = false; - // check corresponding browser entry - if (browser->browserList[clickedIndex].isdir) { - /* go up to parent directory */ - if (strcmp(browser->browserList[clickedIndex].filename,"..") == 0) { - /* remove last subdirectory name */ - int len = strlen(browser->dir); - while (browser->dir[0] && browser->dir[len-1] == '/') - browser->dir[--len] = '\0'; // remove all trailing '/' - char *cptr = strrchr(browser->dir, '/'); - if (cptr) *++cptr = 0; - else browser->dir[0] = '\0'; // remove trailing dir - pathCanged = true; - } - /* Open a directory */ - /* current directory doesn't change */ - else if (strcmp(browser->browserList[clickedIndex].filename,".")) { - /* test new directory namelength */ - if ((strlen(browser->dir) + strlen(browser->browserList[clickedIndex].filename) - + 1/*'/'*/) < MAXPATHLEN) { - /* update current directory name */ - sprintf(browser->dir, "%s%s/",browser->dir, - browser->browserList[clickedIndex].filename); - pathCanged = true; - } - } - if (pathCanged) { - LOCK(&fileBrowser); - ParseDirectory((char*)NULL, Flags, Filter); - fileBrowser.ResetState(); - fileBrowser.TriggerUpdate(); - AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); - } - clickedIndex = -1; - } else { /* isFile */ - AdressText.SetTextf("%s%s%s", browser->rootdir, browser->dir, browser->browserList[clickedIndex].filename); - } - } - } + clickedIndex = browser->pageIndex + i; + bool pathCanged = false; + // check corresponding browser entry + if (browser->browserList[clickedIndex].isdir) + { + /* go up to parent directory */ + if (strcmp(browser->browserList[clickedIndex].filename,"..") == 0) + { + /* remove last subdirectory name */ + int len = strlen(browser->dir); + while(browser->dir[0] && browser->dir[len-1] == '/') + browser->dir[--len] = '\0'; // remove all trailing '/' + char *cptr = strrchr(browser->dir, '/'); + if(cptr) *++cptr = 0; else browser->dir[0] = '\0'; // remove trailing dir + pathCanged = true; + } + /* Open a directory */ + /* current directory doesn't change */ + else if (strcmp(browser->browserList[clickedIndex].filename,".")) + { + /* test new directory namelength */ + if ((strlen(browser->dir) + strlen(browser->browserList[clickedIndex].filename) + + 1/*'/'*/) < MAXPATHLEN) + { + /* update current directory name */ + sprintf(browser->dir, "%s%s/",browser->dir, + browser->browserList[clickedIndex].filename); + pathCanged = true; + } + } + if (pathCanged) + { + LOCK(&fileBrowser); + ParseDirectory((char*)NULL, Flags, Filter); + fileBrowser.ResetState(); + fileBrowser.TriggerUpdate(); + AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); + } + clickedIndex = -1; + } + else /* isFile */ + { + AdressText.SetTextf("%s%s%s", browser->rootdir, browser->dir, browser->browserList[clickedIndex].filename); + } + } + } - if (ExitBtn.GetState() == STATE_CLICKED) { - break; - } else if (okBtn.GetState() == STATE_CLICKED) { - if (clickedIndex>=0) - snprintf(Path, Path_size, "%s%s%s", browser->rootdir, browser->dir,browser->browserList[clickedIndex].filename); - else - snprintf(Path, Path_size, "%s%s", browser->rootdir, browser->dir); - result = 1; - break; - } else if (usbBtn.GetState() == STATE_CLICKED) { - usbBtn.ResetState(); - for (u32 i=1; irootdir, browser->dir); - usbBtnTxt.SetText(browsers[(curDevice+1)%browsers.size()].rootdir); - break; - } - } - } else if (folderBtn.GetState() == STATE_CLICKED) { - folderBtn.ResetState(); + if (ExitBtn.GetState() == STATE_CLICKED) { + break; + } + else if (okBtn.GetState() == STATE_CLICKED) { + if(clickedIndex>=0) + snprintf(Path, Path_size, "%s%s%s", browser->rootdir, browser->dir,browser->browserList[clickedIndex].filename); + else + snprintf(Path, Path_size, "%s%s", browser->rootdir, browser->dir); + result = 1; + break; + } + else if (usbBtn.GetState() == STATE_CLICKED) { + usbBtn.ResetState(); + for(u32 i=1; irootdir, browser->dir); + usbBtnTxt.SetText(browsers[(curDevice+1)%browsers.size()].rootdir); + break; + } + } + } + else if (folderBtn.GetState() == STATE_CLICKED) { + folderBtn.ResetState(); - HaltGui(); - mainWindow->Remove(&w); - ResumeGui(); - char newfolder[100]; - char oldfolder[100]; - snprintf(newfolder, sizeof(newfolder), "%s%s", browser->rootdir, browser->dir); - strcpy(oldfolder,newfolder); + HaltGui(); + mainWindow->Remove(&w); + ResumeGui(); + char newfolder[100]; + char oldfolder[100]; + snprintf(newfolder, sizeof(newfolder), "%s%s", browser->rootdir, browser->dir); + strcpy(oldfolder,newfolder); + + int result = OnScreenKeyboard(newfolder, sizeof(newfolder), strlen(browser->rootdir)); + if ( result == 1 ) { + unsigned int len = strlen(newfolder); + if (len>0 && len+1 < sizeof(newfolder) && newfolder[len-1] !='/') + { + newfolder[len] = '/'; + newfolder[len+1] = '\0'; + } - int result = OnScreenKeyboard(newfolder, sizeof(newfolder), strlen(browser->rootdir)); - if ( result == 1 ) { - unsigned int len = strlen(newfolder); - if (len>0 && len+1 < sizeof(newfolder) && newfolder[len-1] !='/') { - newfolder[len] = '/'; - newfolder[len+1] = '\0'; - } + struct stat st; + if (stat(newfolder, &st) != 0) { + if(WindowPrompt(tr("Directory does not exist!"),tr("The entered directory does not exist. Would you like to create it?") ,tr("OK"), tr("Cancel")) == 1) + if (subfoldercreate(newfolder) == false) + WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + } + if(ParseDirectory(newfolder, Flags, Filter)==0) + { + fileBrowser.ResetState(); + fileBrowser.TriggerUpdate(); + AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); + usbBtnTxt.SetText(browsers[(curDevice+1)%browsers.size()].rootdir); + } + } + HaltGui(); + mainWindow->Append(&w); + ResumeGui(); + } - struct stat st; - if (stat(newfolder, &st) != 0) { - if (WindowPrompt(tr("Directory does not exist!"),tr("The entered directory does not exist. Would you like to create it?") ,tr("OK"), tr("Cancel")) == 1) - if (subfoldercreate(newfolder) == false) - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); - } - if (ParseDirectory(newfolder, Flags, Filter)==0) { - fileBrowser.ResetState(); - fileBrowser.TriggerUpdate(); - AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); - usbBtnTxt.SetText(browsers[(curDevice+1)%browsers.size()].rootdir); - } - } - HaltGui(); - mainWindow->Append(&w); - ResumeGui(); - } + } + HaltGui(); + mainWindow->Remove(&w); + ResumeGui(); - } - HaltGui(); - mainWindow->Remove(&w); - ResumeGui(); + //} - //} - - return result; + return result; } -int BrowseDevice(char * Path, int Path_size, int Flags, FILEFILTERCALLBACK Filter, void *FilterArgs) { - if (Filter) { - FILTERCASCADE filter = {Filter, FilterArgs, NULL}; - return BrowseDevice(Path, Path_size, Flags, &filter); - } - return BrowseDevice(Path, Path_size, Flags); +int BrowseDevice(char * Path, int Path_size, int Flags, FILEFILTERCALLBACK Filter, void *FilterArgs) +{ + if(Filter) + { + FILTERCASCADE filter = {Filter, FilterArgs, NULL}; + return BrowseDevice(Path, Path_size, Flags, &filter); + } + return BrowseDevice(Path, Path_size, Flags); } diff --git a/source/prompts/filebrowser.h b/source/prompts/filebrowser.h index d37caea4..5d05b079 100644 --- a/source/prompts/filebrowser.h +++ b/source/prompts/filebrowser.h @@ -32,7 +32,7 @@ typedef struct { char dir[MAXPATHLEN]; // directory path of browserList char rootdir[ROOTDIRLEN];// directory path of browserList int pageIndex; // starting index of browserList page display - std::vector browserList; + std::vector browserList; } BROWSERINFO; extern BROWSERINFO *browser; @@ -48,10 +48,10 @@ int noDIRS(BROWSERENTRY *Entry, void* Args); int noFILES(BROWSERENTRY *Entry, void* Args); int noEXT(BROWSERENTRY *Entry, void* Args); -typedef struct _FILTERCASCADE { - FILEFILTERCALLBACK filter; - void *filter_args; - _FILTERCASCADE *next; +typedef struct _FILTERCASCADE{ + FILEFILTERCALLBACK filter; + void *filter_args; + _FILTERCASCADE *next; } FILTERCASCADE; diff --git a/source/prompts/gameinfo.cpp b/source/prompts/gameinfo.cpp index 3a3918ce..7e8325c2 100644 --- a/source/prompts/gameinfo.cpp +++ b/source/prompts/gameinfo.cpp @@ -58,19 +58,19 @@ int showGameInfo(char *ID) { int wifiY=0; int intputX=200, inputY=-30, txtXOffset=90; u8 nunchuk=0, - classiccontroller=0, - balanceboard=0, - dancepad=0, - guitar=0, - gamecube=0, - wheel=0, - motionplus=0, - drums=0, - microphone=0, - zapper=0, - nintendods=0, - //vitalitysensor=0, - wiispeak=0; + classiccontroller=0, + balanceboard=0, + dancepad=0, + guitar=0, + gamecube=0, + wheel=0, + motionplus=0, + drums=0, + microphone=0, + zapper=0, + nintendods=0, + //vitalitysensor=0, + wiispeak=0; int newline=1; u8 page=1; @@ -225,15 +225,15 @@ int showGameInfo(char *ID) { wheel=1; if (strcmp(gameinfo.accessoriesReq[i],"balanceboard")==0) balanceboard=1; - if (strcmp(gameinfo.accessoriesReq[i],"microphone")==0) + if (strcmp(gameinfo.accessoriesReq[i],"microphone")==0) microphone=1; - if (strcmp(gameinfo.accessoriesReq[i],"zapper")==0) + if (strcmp(gameinfo.accessoriesReq[i],"zapper")==0) zapper=1; - if (strcmp(gameinfo.accessoriesReq[i],"nintendods")==0) + if (strcmp(gameinfo.accessoriesReq[i],"nintendods")==0) nintendods=1; - if (strcmp(gameinfo.accessoriesReq[i],"wiispeak")==0) + if (strcmp(gameinfo.accessoriesReq[i],"wiispeak")==0) wiispeak=1; - //if (strcmp(gameinfo.accessoriesReq[i],"vitalitysensor")==0) + //if (strcmp(gameinfo.accessoriesReq[i],"vitalitysensor")==0) // vitalitysensor=1; if (strcmp(gameinfo.accessoriesReq[i],"gamecube")==0) gamecube=1; @@ -267,13 +267,13 @@ int showGameInfo(char *ID) { if (zapper) zapperImgData = new GuiImageData(zapperR_png); else zapperImgData = new GuiImageData(zapper_png); - if (wiispeak) wiispeakImgData = new GuiImageData(wiispeakR_png); + if (wiispeak) wiispeakImgData = new GuiImageData(wiispeakR_png); else wiispeakImgData = new GuiImageData(wiispeak_png); - if (nintendods) nintendodsImgData = new GuiImageData(nintendodsR_png); + if (nintendods) nintendodsImgData = new GuiImageData(nintendodsR_png); else nintendodsImgData = new GuiImageData(nintendods_png); - //if (vitalitysensor) vitalitysensorImgData = new GuiImageData(vitalitysensorR_png); + //if (vitalitysensor) vitalitysensorImgData = new GuiImageData(vitalitysensorR_png); //else vitalitysensorImgData = new GuiImageData(vitalitysensor_png); if (balanceboard) balanceboardImgData = new GuiImageData(balanceboardR_png); @@ -302,13 +302,13 @@ int showGameInfo(char *ID) { balanceboard=1; if (strcmp(gameinfo.accessories[i],"microphone")==0) microphone=1; - if (strcmp(gameinfo.accessories[i],"zapper")==0) + if (strcmp(gameinfo.accessories[i],"zapper")==0) zapper=1; - if (strcmp(gameinfo.accessories[i],"nintendods")==0) + if (strcmp(gameinfo.accessories[i],"nintendods")==0) nintendods=1; - if (strcmp(gameinfo.accessories[i],"wiispeak")==0) + if (strcmp(gameinfo.accessories[i],"wiispeak")==0) wiispeak=1; - //if (strcmp(gameinfo.accessories[i],"vitalitysensor")==0) + //if (strcmp(gameinfo.accessories[i],"vitalitysensor")==0) // vitalitysensor=1; if (strcmp(gameinfo.accessories[i],"gamecube")==0) gamecube=1; @@ -433,7 +433,7 @@ int showGameInfo(char *ID) { gameinfoWindow.Append(microphoneImg); intputX += (CFG.widescreen ? microphoneImg->GetWidth() * .8 : microphoneImg->GetWidth())+5; } - if (zapper==1) { + if (zapper==1) { zapperImg = new GuiImage( zapperImgData); zapperImg->SetWidescreen(CFG.widescreen); zapperImg->SetPosition(intputX , inputY); @@ -441,7 +441,7 @@ int showGameInfo(char *ID) { gameinfoWindow.Append(zapperImg); intputX += (CFG.widescreen ? zapperImg->GetWidth() * .8 : zapperImg->GetWidth())+5; } - if (wiispeak==1) { + if (wiispeak==1) { wiispeakImg = new GuiImage(wiispeakImgData); wiispeakImg->SetWidescreen(CFG.widescreen); wiispeakImg->SetPosition(intputX , inputY); @@ -449,7 +449,7 @@ int showGameInfo(char *ID) { gameinfoWindow.Append(wiispeakImg); intputX += (CFG.widescreen ? wiispeakImg->GetWidth() * .8 : wiispeakImg->GetWidth())+5; } - if (nintendods==1) { + if (nintendods==1) { nintendodsImg = new GuiImage(nintendodsImgData); nintendodsImg->SetWidescreen(CFG.widescreen); nintendodsImg->SetPosition(intputX , inputY); @@ -457,8 +457,8 @@ int showGameInfo(char *ID) { gameinfoWindow.Append(nintendodsImg); intputX += (CFG.widescreen ? nintendodsImg->GetWidth() * .8 : nintendodsImg->GetWidth())+5; } - /* - if (vitalitysensor==1) { + /* + if (vitalitysensor==1) { vitalitysensorImg = new GuiImage(vitalitysensorImgData); vitalitysensorImg->SetWidescreen(CFG.widescreen); vitalitysensorImg->SetPosition(intputX , inputY); @@ -466,7 +466,7 @@ int showGameInfo(char *ID) { gameinfoWindow.Append(vitalitysensorImg); intputX += (CFG.widescreen ? vitalitysensorImg->GetWidth() * .8 : vitalitysensorImg->GetWidth())+5; } - */ + */ if (dancepad==1) { dancepadImg = new GuiImage(dancepadImgData); dancepadImg->SetWidescreen(CFG.widescreen); @@ -497,20 +497,20 @@ int showGameInfo(char *ID) { //wifiplayersImgData= new GuiImageData(wifi6_png); wifiplayersImgData= new GuiImageData(wifi8_png); } - /* - if (atoi(gameinfo.wifiplayers)>6) { + /* + if (atoi(gameinfo.wifiplayers)>6) { wifiplayersImgData= new GuiImageData(wifi8_png); } - */ + */ if (atoi(gameinfo.wifiplayers)>8) { - wifiplayersImgData= new GuiImageData(wifi12_png); - } + wifiplayersImgData= new GuiImageData(wifi12_png); + } if (atoi(gameinfo.wifiplayers)>12) { - wifiplayersImgData= new GuiImageData(wifi16_png); - } + wifiplayersImgData= new GuiImageData(wifi16_png); + } if (atoi(gameinfo.wifiplayers)>16) { - wifiplayersImgData= new GuiImageData(wifi32_png); - } + wifiplayersImgData= new GuiImageData(wifi32_png); + } wifiplayersImg = new GuiImage(wifiplayersImgData); wifiplayersImg->SetWidescreen(CFG.widescreen); wifiplayersImg->SetPosition(intputX , inputY); @@ -584,7 +584,7 @@ int showGameInfo(char *ID) { char meminfotxt[200]; strlcpy(meminfotxt,MemInfo(),sizeof(meminfotxt)); snprintf(linebuf, sizeof(linebuf), "%s",meminfotxt); - memTxt = new GuiText(linebuf, 18, (GXColor) {0,0,0, 255}); + memTxt = new GuiText(linebuf, 18, (GXColor) {0,0,0, 255}); memTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); memTxt->SetPosition(0,0); gameinfoWindow.Append(memTxt); @@ -594,7 +594,7 @@ int showGameInfo(char *ID) { int titlefontsize=25; if (strcmp(gameinfo.title,"") != 0) { snprintf(linebuf, sizeof(linebuf), "%s",gameinfo.title); - titleTxt = new GuiText(linebuf, titlefontsize, (GXColor) {0,0,0, 255}); + titleTxt = new GuiText(linebuf, titlefontsize, (GXColor) {0,0,0, 255}); titleTxt->SetMaxWidth(350, GuiText::SCROLL); //while (titleTxt->GetWidth()>250) { titleTxt->SetFontSize(titlefontsize-=2); } titleTxt->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); @@ -649,7 +649,7 @@ int showGameInfo(char *ID) { } if (strcmp(gameinfo.year,"") != 0) { snprintf(linebuf, sizeof(linebuf), "%s : %s%s", tr("Released"), linebuf2, gameinfo.year); - releasedTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + releasedTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); if (releasedTxt->GetWidth()>300) newline=2; releasedTxt->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); releasedTxt->SetPosition(-17,12+indexy); @@ -661,7 +661,7 @@ int showGameInfo(char *ID) { //publisher if (strcmp(gameinfo.publisher,"") != 0) { snprintf(linebuf, sizeof(linebuf), "%s %s", tr("Published by"), gameinfo.publisher); - publisherTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + publisherTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); if (publisherTxt->GetWidth()>250) newline=2; publisherTxt->SetMaxWidth(250,GuiText::WRAP); publisherTxt->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); @@ -674,7 +674,7 @@ int showGameInfo(char *ID) { //developer if (strcmp(gameinfo.developer,"") != 0 && strcasecmp(gameinfo.developer,gameinfo.publisher) != 0) { snprintf(linebuf, sizeof(linebuf), "%s %s", tr("Developed by"), gameinfo.developer); - developerTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + developerTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); if (developerTxt->GetWidth()>250) newline=2; developerTxt->SetMaxWidth(250,GuiText::WRAP); developerTxt->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); @@ -689,7 +689,7 @@ int showGameInfo(char *ID) { genreTxt = new GuiText * [gameinfo.genreCnt + 1]; for (int i=1;i<=gameinfo.genreCnt;i++) { snprintf(linebuf, sizeof(linebuf), "%s", gameinfo.genresplit[i]); - genreTxt[i] = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + genreTxt[i] = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); genreTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); genreTxt[i]->SetPosition(205,12+genreY); genreY+=20; @@ -704,7 +704,7 @@ int showGameInfo(char *ID) { } else { snprintf(linebuf, sizeof(linebuf), "%s",gameinfo.wififeatures[i]); } - wifiTxt[i] = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + wifiTxt[i] = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); wifiTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); wifiTxt[i]->SetPosition(215,200+wifiY); wifiY-=20; @@ -712,10 +712,10 @@ int showGameInfo(char *ID) { } if (strcmp(gameinfo.wififeatures[1],"") !=0) { snprintf(linebuf, sizeof(linebuf), "%s:",tr("WiFi Features")); - } else { + } else { strcpy(linebuf,""); - } - wifiTxt[0] = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + } + wifiTxt[0] = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); wifiTxt[0]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); wifiTxt[0]->SetPosition(205,200+wifiY); gameinfoWindow.Append(wifiTxt[0]); @@ -724,7 +724,7 @@ int showGameInfo(char *ID) { int pagesize=12; if (strcmp(gameinfo.synopsis,"") !=0) { snprintf(linebuf, sizeof(linebuf), "%s", gameinfo.synopsis); - synopsisTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + synopsisTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); synopsisTxt->SetMaxWidth(350,GuiText::WRAP); synopsisTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); synopsisTxt->SetPosition(0,0); @@ -764,37 +764,37 @@ int showGameInfo(char *ID) { snprintf(linebuf, sizeof(linebuf), "http://wiitdb.com"); //snprintf(linebuf, sizeof(linebuf), tr("Don't bother the USB Loader GX Team about errors in this file.")); - wiitdb1Txt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); + wiitdb1Txt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); wiitdb1Txt->SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); wiitdb1Txt->SetPosition(40,-15); gameinfoWindow.Append(wiitdb1Txt); snprintf(linebuf, sizeof(linebuf), tr("If you don't have WiFi, press 1 to get an URL to get your WiiTDB.zip")); - wiitdb2Txt = new GuiText(linebuf, 14, (GXColor) {0,0,0, 255}); + wiitdb2Txt = new GuiText(linebuf, 14, (GXColor) {0,0,0, 255}); wiitdb2Txt->SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); wiitdb2Txt->SetPosition(202,-15); gameinfoWindow.Append(wiitdb2Txt); - snprintf(linebuf, sizeof(linebuf), " "); - wiitdb3Txt = new GuiText(linebuf, 14, (GXColor) {0,0,0, 255}); + snprintf(linebuf, sizeof(linebuf), " "); + wiitdb3Txt = new GuiText(linebuf, 14, (GXColor) {0,0,0, 255}); wiitdb3Txt->SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); wiitdb3Txt->SetPosition(202,-4); gameinfoWindow.Append(wiitdb3Txt); gameinfoWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 100); - GuiTrigger trigZ; - trigZ.SetButtonOnlyTrigger(-1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z); + GuiTrigger trigZ; + trigZ.SetButtonOnlyTrigger(-1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z); - GuiButton screenShotBtn(0,0); - screenShotBtn.SetPosition(0,0); - screenShotBtn.SetTrigger(&trigZ); - gameinfoWindow.Append(&screenShotBtn); + GuiButton screenShotBtn(0,0); + screenShotBtn.SetPosition(0,0); + screenShotBtn.SetTrigger(&trigZ); + gameinfoWindow.Append(&screenShotBtn); HaltGui(); //mainWindow->SetState(STATE_DISABLED); mainWindow->Append(&gameinfoWindow); mainWindow->ChangeFocus(&gameinfoWindow); ResumeGui(); - bool savedURL = false; + bool savedURL = false; while (choice == -1) { @@ -806,24 +806,24 @@ int showGameInfo(char *ID) { Sys_Reboot(); else if ((backBtn.GetState()==STATE_CLICKED)||(backBtn.GetState()==STATE_HELD)) { - backBtn.ResetState(); + backBtn.ResetState(); if (page==1) { choice=1; synopsisTxt = NULL; break; } else if (page==2) { HaltGui(); - gameinfoWindow2.Remove(&nextBtn); + gameinfoWindow2.Remove(&nextBtn); gameinfoWindow2.Remove(&backBtn); - gameinfoWindow2.Remove(&homeBtn); - gameinfoWindow2.Remove(&screenShotBtn); - gameinfoWindow2.SetVisible(false); + gameinfoWindow2.Remove(&homeBtn); + gameinfoWindow2.Remove(&screenShotBtn); + gameinfoWindow2.SetVisible(false); gameinfoWindow.SetVisible(true); - gameinfoWindow.Append(&backBtn); + gameinfoWindow.Append(&backBtn); gameinfoWindow.Append(&nextBtn); - gameinfoWindow.Append(&homeBtn); - gameinfoWindow.Append(&screenShotBtn); - mainWindow->Remove(&gameinfoWindow2); + gameinfoWindow.Append(&homeBtn); + gameinfoWindow.Append(&screenShotBtn); + mainWindow->Remove(&gameinfoWindow2); ResumeGui(); page=1; } @@ -832,33 +832,33 @@ int showGameInfo(char *ID) { nextBtn.ResetState(); if (page==1) { HaltGui(); - gameinfoWindow.Remove(&nextBtn); + gameinfoWindow.Remove(&nextBtn); gameinfoWindow.Remove(&backBtn); - gameinfoWindow.Remove(&homeBtn); - gameinfoWindow.Remove(&screenShotBtn); - gameinfoWindow.SetVisible(false); + gameinfoWindow.Remove(&homeBtn); + gameinfoWindow.Remove(&screenShotBtn); + gameinfoWindow.SetVisible(false); gameinfoWindow2.SetVisible(true); coverImg->SetPosition(15,30); gameinfoWindow2.Append(&nextBtn); gameinfoWindow2.Append(&backBtn); - gameinfoWindow2.Append(&homeBtn); - gameinfoWindow2.Append(&screenShotBtn); - mainWindow->Append(&gameinfoWindow2); + gameinfoWindow2.Append(&homeBtn); + gameinfoWindow2.Append(&screenShotBtn); + mainWindow->Append(&gameinfoWindow2); ResumeGui(); page=2; } else { HaltGui(); - gameinfoWindow2.Remove(&nextBtn); + gameinfoWindow2.Remove(&nextBtn); gameinfoWindow2.Remove(&backBtn); - gameinfoWindow2.Remove(&homeBtn); - gameinfoWindow2.Remove(&screenShotBtn); - gameinfoWindow2.SetVisible(false); + gameinfoWindow2.Remove(&homeBtn); + gameinfoWindow2.Remove(&screenShotBtn); + gameinfoWindow2.SetVisible(false); gameinfoWindow.SetVisible(true); gameinfoWindow.Append(&backBtn); gameinfoWindow.Append(&nextBtn); - gameinfoWindow.Append(&homeBtn); - gameinfoWindow.Append(&screenShotBtn); - mainWindow->Remove(&gameinfoWindow2); + gameinfoWindow.Append(&homeBtn); + gameinfoWindow.Append(&screenShotBtn); + mainWindow->Remove(&gameinfoWindow2); ResumeGui(); page=1; } @@ -898,8 +898,8 @@ int showGameInfo(char *ID) { page=1; } } else if (urlBtn.GetState()==STATE_CLICKED && !savedURL) { - snprintf(linebuf, sizeof(linebuf), tr("Please wait...")); - wiitdb2Txt->SetText(linebuf); + snprintf(linebuf, sizeof(linebuf), tr("Please wait...")); + wiitdb2Txt->SetText(linebuf); gameinfoWindow.Append(wiitdb2Txt); if (save_XML_URL()) { snprintf(linebuf, sizeof(linebuf), tr("Your URL has been saved in %sWiiTDB_URL.txt."), Settings.update_path); @@ -908,19 +908,20 @@ int showGameInfo(char *ID) { snprintf(linebuf, sizeof(linebuf), tr("Paste it into your browser to get your WiiTDB.zip.")); wiitdb3Txt->SetText(linebuf); gameinfoWindow.Append(wiitdb3Txt); - savedURL = true; + savedURL = true; } else { - snprintf(linebuf, sizeof(linebuf), tr("Could not save.")); - wiitdb2Txt->SetText(linebuf); - gameinfoWindow.Append(wiitdb2Txt); - } - urlBtn.ResetState(); - } else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); + snprintf(linebuf, sizeof(linebuf), tr("Could not save.")); + wiitdb2Txt->SetText(linebuf); + gameinfoWindow.Append(wiitdb2Txt); + } + urlBtn.ResetState(); } + else if (screenShotBtn.GetState() == STATE_CLICKED) { + gprintf("\n\tscreenShotBtn clicked"); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf("...It's easy, mmmmmmKay"); + } } if (page==1) { gameinfoWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 100); @@ -1006,17 +1007,17 @@ int showGameInfo(char *ID) { ResumeGui(); } - if (savedURL) return 3; + if (savedURL) return 3; return choice; - /* File not found */ + /* File not found */ } else { return -1; } } bool save_gamelist(int txt) { // save gamelist - mainWindow->SetState(STATE_DISABLED); + mainWindow->SetState(STATE_DISABLED); char tmp[200]; sprintf(tmp, "%s", Settings.update_path); struct stat st; @@ -1025,65 +1026,65 @@ bool save_gamelist(int txt) { // save gamelist } FILE *f; sprintf(tmp, "%sGameList.txt", Settings.update_path); - if (txt==1) - sprintf(tmp, "%sGameList.csv", Settings.update_path); + if (txt==1) + sprintf(tmp, "%sGameList.csv", Settings.update_path); f = fopen(tmp, "w"); if (!f) { sleep(1); - mainWindow->SetState(STATE_DEFAULT); + mainWindow->SetState(STATE_DEFAULT); return false; } //make sure that all games are added to the gamelist __Menu_GetEntries(1); f32 size = 0.0; - f32 freespace, used; - unsigned int i; + f32 freespace, used; + unsigned int i; - WBFS_DiskSpace(&used, &freespace); + WBFS_DiskSpace(&used, &freespace); - fprintf(f, "# USB Loader Has Saved this file\n"); + fprintf(f, "# USB Loader Has Saved this file\n"); fprintf(f, "# This file was created based on your list of games and language settings.\n"); fclose(f); /* Closing and reopening because of a write issue we are having right now */ f = fopen(tmp, "w"); - if (txt==0) { - fprintf(f, "# USB Loader Has Saved this file\n"); - fprintf(f, "# This file was created based on your list of games and language settings.\n\n"); + if (txt==0) { + fprintf(f, "# USB Loader Has Saved this file\n"); + fprintf(f, "# This file was created based on your list of games and language settings.\n\n"); - fprintf(f, "%.2fGB %s %.2fGB %s\n\n",freespace,tr("of"),(freespace+used),tr("free")); - fprintf(f, "ID Size(GB) Name\n"); + fprintf(f, "%.2fGB %s %.2fGB %s\n\n",freespace,tr("of"),(freespace+used),tr("free")); + fprintf(f, "ID Size(GB) Name\n"); - for (i = 0; i < gameCnt ; i++) { - struct discHdr* header = &gameList[i]; - WBFS_GameSize(header->id, &size); - if (i<500) { - fprintf(f, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5]); - fprintf(f, " [%.2f] ", size); - fprintf(f, " %s",get_title(header)); - } - fprintf(f, "\n"); - } - } else { + for (i = 0; i < gameCnt ; i++) { + struct discHdr* header = &gameList[i]; + WBFS_GameSize(header->id, &size); + if (i<500) { + fprintf(f, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5]); + fprintf(f, " [%.2f] ", size); + fprintf(f, " %s",get_title(header)); + } + fprintf(f, "\n"); + } + } else { - fprintf(f, "\"ID\",\"Size(GB)\",\"Name\"\n"); + fprintf(f, "\"ID\",\"Size(GB)\",\"Name\"\n"); - for (i = 0; i < gameCnt ; i++) { - struct discHdr* header = &gameList[i]; - WBFS_GameSize(header->id, &size); - if (i<500) { - fprintf(f, "\"%c%c%c%c%c%c\",\"%.2f\",\"%s\"\n", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5], size,get_title(header)); - //fprintf(f, "\"%.2f\",", size); - //fprintf(f, "\"%s\"",get_title(header)); - } - //fprintf(f, "\n"); - } - } + for (i = 0; i < gameCnt ; i++) { + struct discHdr* header = &gameList[i]; + WBFS_GameSize(header->id, &size); + if (i<500) { + fprintf(f, "\"%c%c%c%c%c%c\",\"%.2f\",\"%s\"\n", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5], size,get_title(header)); + //fprintf(f, "\"%.2f\",", size); + //fprintf(f, "\"%s\"",get_title(header)); + } + //fprintf(f, "\n"); + } + } fclose(f); __Menu_GetEntries(); - mainWindow->SetState(STATE_DEFAULT); + mainWindow->SetState(STATE_DEFAULT); return true; } @@ -1102,10 +1103,10 @@ bool save_XML_URL() { // save xml url as as txt file for people without wifi sleep(1); return false; } - - char XMLurl[3540]; - build_XML_URL(XMLurl,sizeof(XMLurl)); - + + char XMLurl[3540]; + build_XML_URL(XMLurl,sizeof(XMLurl)); + fprintf(f, "# USB Loader Has Saved this file\n"); fprintf(f, "# This URL was created based on your list of games and language settings.\n"); fclose(f); @@ -1122,16 +1123,17 @@ bool save_XML_URL() { // save xml url as as txt file for people without wifi } -void MemInfoPrompt() { - char meminfotxt[200]; +void MemInfoPrompt() +{ + char meminfotxt[200]; strlcpy(meminfotxt,MemInfo(),sizeof(meminfotxt)); - WindowPrompt(0,meminfotxt, tr("OK")); + WindowPrompt(0,meminfotxt, tr("OK")); } void build_XML_URL(char *XMLurl, int XMLurlsize) { __Menu_GetEntries(1); - // NET_BUFFER_SIZE in http.c needs to be set to size of XMLurl + headerformat + // NET_BUFFER_SIZE in http.c needs to be set to size of XMLurl + headerformat char url[3540]; char filename[10]; snprintf(url,sizeof(url),"http://wiitdb.com/wiitdb.zip?LANG=%s&ID=", Settings.db_language); @@ -1139,12 +1141,12 @@ void build_XML_URL(char *XMLurl, int XMLurlsize) { for (i = 0; i < gameCnt ; i++) { struct discHdr* header = &gameList[i]; if (i<500) { - snprintf(filename,sizeof(filename),"%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); + snprintf(filename,sizeof(filename),"%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); strncat(url,filename,6); if ((i!=gameCnt-1)&&(i<500)) strncat(url, ",",1); } } - strlcpy(XMLurl,url,XMLurlsize); - __Menu_GetEntries(); + strlcpy(XMLurl,url,XMLurlsize); + __Menu_GetEntries(); } diff --git a/source/ramdisk/ramdisk.cpp b/source/ramdisk/ramdisk.cpp index 7529d374..77478636 100644 --- a/source/ramdisk/ramdisk.cpp +++ b/source/ramdisk/ramdisk.cpp @@ -18,393 +18,455 @@ class RAMDISK_PARTITION; class RAMDISK_LINK_ENTRY; class RAMDISK_DIR_ENTRY; class RAMDISK_FILE_ENTRY; -class RAMDISK_BASE_ENTRY { +class RAMDISK_BASE_ENTRY +{ public: - RAMDISK_BASE_ENTRY(const char *Name, RAMDISK_DIR_ENTRY *Parent); - virtual ~RAMDISK_BASE_ENTRY(); - void Rename(const char *Name); - RAMDISK_LINK_ENTRY *IsLink(); - RAMDISK_DIR_ENTRY *IsDir(); - RAMDISK_FILE_ENTRY *IsFile(); - RAMDISK_PARTITION *GetPartition(); - char *name; - RAMDISK_DIR_ENTRY *parent; - RAMDISK_BASE_ENTRY *next; + RAMDISK_BASE_ENTRY(const char *Name, RAMDISK_DIR_ENTRY *Parent); + virtual ~RAMDISK_BASE_ENTRY(); + void Rename(const char *Name); + RAMDISK_LINK_ENTRY *IsLink(); + RAMDISK_DIR_ENTRY *IsDir(); + RAMDISK_FILE_ENTRY *IsFile(); + RAMDISK_PARTITION *GetPartition(); + char *name; + RAMDISK_DIR_ENTRY *parent; + RAMDISK_BASE_ENTRY *next; }; -class RAMDISK_LINK_ENTRY : public RAMDISK_BASE_ENTRY { +class RAMDISK_LINK_ENTRY : public RAMDISK_BASE_ENTRY +{ public: - RAMDISK_LINK_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent, RAMDISK_BASE_ENTRY *Link); - RAMDISK_BASE_ENTRY *link; + RAMDISK_LINK_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent, RAMDISK_BASE_ENTRY *Link); + RAMDISK_BASE_ENTRY *link; }; -class RAMDISK_DIR_ENTRY : public RAMDISK_BASE_ENTRY { +class RAMDISK_DIR_ENTRY : public RAMDISK_BASE_ENTRY +{ public: - RAMDISK_DIR_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent); - ~RAMDISK_DIR_ENTRY(); - RAMDISK_BASE_ENTRY *FindEntry(const char* Path); - RAMDISK_FILE_ENTRY *CreateFile(const char *Filename); - RAMDISK_DIR_ENTRY *CreateDir(const char *Filename); - void RemoveEntry(RAMDISK_BASE_ENTRY *Entry); - RAMDISK_BASE_ENTRY *first; - RAMDISK_BASE_ENTRY *last; + RAMDISK_DIR_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent); + ~RAMDISK_DIR_ENTRY(); + RAMDISK_BASE_ENTRY *FindEntry(const char* Path); + RAMDISK_FILE_ENTRY *CreateFile(const char *Filename); + RAMDISK_DIR_ENTRY *CreateDir(const char *Filename); + void RemoveEntry(RAMDISK_BASE_ENTRY *Entry); + RAMDISK_BASE_ENTRY *first; + RAMDISK_BASE_ENTRY *last; }; -typedef struct { - RAMDISK_DIR_ENTRY *dir; - RAMDISK_BASE_ENTRY *current_entry; +typedef struct +{ + RAMDISK_DIR_ENTRY *dir; + RAMDISK_BASE_ENTRY *current_entry; } DIR_STRUCT; -class RAMDISK_PARTITION : public RAMDISK_DIR_ENTRY { +class RAMDISK_PARTITION : public RAMDISK_DIR_ENTRY +{ public: - RAMDISK_PARTITION(const char *Mountpoint, bool AutoMount); - RAMDISK_BASE_ENTRY *FindEntry(const char* Path); - RAMDISK_DIR_ENTRY *FindPath(const char* Path, const char **Basename=NULL); - RAMDISK_DIR_ENTRY *cwd; - bool automount; + RAMDISK_PARTITION(const char *Mountpoint, bool AutoMount); + RAMDISK_BASE_ENTRY *FindEntry(const char* Path); + RAMDISK_DIR_ENTRY *FindPath(const char* Path, const char **Basename=NULL); + RAMDISK_DIR_ENTRY *cwd; + bool automount; }; -class FILE_DATA { +class FILE_DATA +{ public: - FILE_DATA(size_t Len); - ~FILE_DATA(); - u8 *data; - size_t len; - FILE_DATA *next; + FILE_DATA(size_t Len); + ~FILE_DATA(); + u8 *data; + size_t len; + FILE_DATA *next; }; -typedef struct { - RAMDISK_FILE_ENTRY *file; - bool isLink; - u32 current_pos; - bool read; - bool write; +typedef struct +{ + RAMDISK_FILE_ENTRY *file; + bool isLink; + u32 current_pos; + bool read; + bool write; } FILE_STRUCT; -class RAMDISK_FILE_ENTRY : public RAMDISK_BASE_ENTRY { +class RAMDISK_FILE_ENTRY : public RAMDISK_BASE_ENTRY +{ public: - RAMDISK_FILE_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent); - ~RAMDISK_FILE_ENTRY(); - bool Truncate(size_t newLen); - bool AddCluster(size_t size); - size_t Read(struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len); - size_t Write(struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len); - size_t file_len; - size_t cluster_len; - FILE_DATA *first_cluster; - FILE_DATA *last_cluster; + RAMDISK_FILE_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent); + ~RAMDISK_FILE_ENTRY(); + bool Truncate(size_t newLen); + bool AddCluster(size_t size); + size_t Read(struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len); + size_t Write(struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len); + size_t file_len; + size_t cluster_len; + FILE_DATA *first_cluster; + FILE_DATA *last_cluster; }; RAMDISK_LINK_ENTRY::RAMDISK_LINK_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent, RAMDISK_BASE_ENTRY *Link) - : - RAMDISK_BASE_ENTRY(Name, Parent), - link(Link) { +: +RAMDISK_BASE_ENTRY(Name, Parent), +link(Link) +{ } RAMDISK_BASE_ENTRY::RAMDISK_BASE_ENTRY(const char *Name, RAMDISK_DIR_ENTRY *Parent) - : - name(strdup(Name)), - parent(Parent), - next(NULL) {} -RAMDISK_BASE_ENTRY::~RAMDISK_BASE_ENTRY() { - free(name); - if (parent) parent->RemoveEntry(this); +: +name(strdup(Name)), +parent(Parent), +next(NULL) +{} +RAMDISK_BASE_ENTRY::~RAMDISK_BASE_ENTRY() +{ + free(name); + if(parent) parent->RemoveEntry(this); } -void RAMDISK_BASE_ENTRY::Rename(const char *Name) { - free(name); - name = strdup(Name); +void RAMDISK_BASE_ENTRY::Rename(const char *Name) +{ + free(name); + name = strdup(Name); } -inline RAMDISK_LINK_ENTRY *RAMDISK_BASE_ENTRY::IsLink() { - return dynamic_cast(this); +inline RAMDISK_LINK_ENTRY *RAMDISK_BASE_ENTRY::IsLink() +{ + return dynamic_cast(this); } -inline RAMDISK_DIR_ENTRY *RAMDISK_BASE_ENTRY::IsDir() { - RAMDISK_LINK_ENTRY *lentry = dynamic_cast(this); - return dynamic_cast(lentry ? lentry->link : this); +inline RAMDISK_DIR_ENTRY *RAMDISK_BASE_ENTRY::IsDir() +{ + RAMDISK_LINK_ENTRY *lentry = dynamic_cast(this); + return dynamic_cast(lentry ? lentry->link : this); } -inline RAMDISK_FILE_ENTRY *RAMDISK_BASE_ENTRY::IsFile() { - RAMDISK_LINK_ENTRY *lentry = dynamic_cast(this); - return dynamic_cast(lentry ? lentry->link : this); +inline RAMDISK_FILE_ENTRY *RAMDISK_BASE_ENTRY::IsFile() +{ + RAMDISK_LINK_ENTRY *lentry = dynamic_cast(this); + return dynamic_cast(lentry ? lentry->link : this); } -RAMDISK_PARTITION *RAMDISK_BASE_ENTRY::GetPartition() { - for (RAMDISK_BASE_ENTRY *entry = this; entry; entry = entry->parent) - if (entry->parent == NULL) - return dynamic_cast(entry); - return NULL; +RAMDISK_PARTITION *RAMDISK_BASE_ENTRY::GetPartition() +{ + for(RAMDISK_BASE_ENTRY *entry = this; entry; entry = entry->parent) + if(entry->parent == NULL) + return dynamic_cast(entry); + return NULL; } RAMDISK_DIR_ENTRY::RAMDISK_DIR_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent) - : - RAMDISK_BASE_ENTRY(Name, Parent) { - RAMDISK_BASE_ENTRY* entry = new RAMDISK_LINK_ENTRY(".", this, this); - first = entry; - last = entry; - if (parent) { - entry = new RAMDISK_LINK_ENTRY("..", this, parent); - first->next = entry; - last = entry; - } +: +RAMDISK_BASE_ENTRY(Name, Parent) +{ + RAMDISK_BASE_ENTRY* entry = new RAMDISK_LINK_ENTRY(".", this, this); + first = entry; + last = entry; + if(parent) + { + entry = new RAMDISK_LINK_ENTRY("..", this, parent); + first->next = entry; + last = entry; + } } -RAMDISK_DIR_ENTRY::~RAMDISK_DIR_ENTRY() { - while (first) { - first->parent = NULL; // ~RAMDISK_BASE_ENTRY() no calls RemoveEntry() - RAMDISK_BASE_ENTRY* next = first->next; - delete first; - first = next; - } +RAMDISK_DIR_ENTRY::~RAMDISK_DIR_ENTRY() +{ + while(first) + { + first->parent = NULL; // ~RAMDISK_BASE_ENTRY() no calls RemoveEntry() + RAMDISK_BASE_ENTRY* next = first->next; + delete first; + first = next; + } } -RAMDISK_BASE_ENTRY *RAMDISK_DIR_ENTRY::FindEntry(const char* Path) { - const char* dirpath = Path; - const char* cptr; - while ( dirpath[0] == '/') dirpath++; // move past leading '/' +RAMDISK_BASE_ENTRY *RAMDISK_DIR_ENTRY::FindEntry(const char* Path) +{ + const char* dirpath = Path; + const char* cptr; + while( dirpath[0] == '/') dirpath++; // move past leading '/' - if (dirpath[0] == '\0') // this path is found - return this; + if(dirpath[0] == '\0') // this path is found + return this; - cptr = strchr(dirpath,'/'); // find next '/' - if (cptr == NULL) - cptr = strchr(dirpath,'\0'); // cptr at end - for (RAMDISK_BASE_ENTRY *curr = first; curr; curr=curr->next) { - if ( strncmp(curr->name, dirpath, cptr-dirpath) == 0) { - if (RAMDISK_DIR_ENTRY *dir = curr->IsDir()) - return dir->FindEntry(cptr); - else - return curr; - } - } - - return NULL; + cptr = strchr(dirpath,'/'); // find next '/' + if(cptr == NULL) + cptr = strchr(dirpath,'\0'); // cptr at end + for(RAMDISK_BASE_ENTRY *curr = first; curr; curr=curr->next) + { + if( strncmp(curr->name, dirpath, cptr-dirpath) == 0) + { + if(RAMDISK_DIR_ENTRY *dir = curr->IsDir()) + return dir->FindEntry(cptr); + else + return curr; + } + } + + return NULL; } -RAMDISK_FILE_ENTRY *RAMDISK_DIR_ENTRY::CreateFile(const char *Filename) { - try { - RAMDISK_FILE_ENTRY* file = new RAMDISK_FILE_ENTRY(Filename, this); - if (!first) first = file; - last->next = file; - last = file; - return file; - } catch (...) { - return NULL; - } +RAMDISK_FILE_ENTRY *RAMDISK_DIR_ENTRY::CreateFile(const char *Filename) +{ + try + { + RAMDISK_FILE_ENTRY* file = new RAMDISK_FILE_ENTRY(Filename, this); + if(!first) first = file; + last->next = file; + last = file; + return file; } -RAMDISK_DIR_ENTRY *RAMDISK_DIR_ENTRY::CreateDir(const char *Filename) { - try { - RAMDISK_DIR_ENTRY* dir = new RAMDISK_DIR_ENTRY(Filename, this); - if (!first) first = dir; - last->next = dir; - last = dir; - return dir; - } catch (...) { - return NULL; - } +catch(...) { return NULL; } } -void RAMDISK_DIR_ENTRY::RemoveEntry(RAMDISK_BASE_ENTRY *Entry) { - RAMDISK_BASE_ENTRY **p_last = NULL; - for (RAMDISK_BASE_ENTRY **curr = &first; *curr; curr=&((*curr)->next) ) { - if ( *curr == Entry ) { - *curr = Entry->next; - if (Entry->next == NULL) // entry is last - last = *p_last; - break; - } - p_last = curr; - } +RAMDISK_DIR_ENTRY *RAMDISK_DIR_ENTRY::CreateDir(const char *Filename) +{ + try + { + RAMDISK_DIR_ENTRY* dir = new RAMDISK_DIR_ENTRY(Filename, this); + if(!first) first = dir; + last->next = dir; + last = dir; + return dir; +} +catch(...) { return NULL; } +} +void RAMDISK_DIR_ENTRY::RemoveEntry(RAMDISK_BASE_ENTRY *Entry) +{ + RAMDISK_BASE_ENTRY **p_last = NULL; + for(RAMDISK_BASE_ENTRY **curr = &first; *curr; curr=&((*curr)->next) ) + { + if( *curr == Entry ) + { + *curr = Entry->next; + if(Entry->next == NULL) // entry is last + last = *p_last; + break; + } + p_last = curr; + } } RAMDISK_PARTITION::RAMDISK_PARTITION(const char *Mountpoint, bool AutoMount) : - RAMDISK_DIR_ENTRY(Mountpoint, NULL), - cwd(this), - automount(AutoMount) { +RAMDISK_DIR_ENTRY(Mountpoint, NULL), +cwd(this), +automount(AutoMount) +{ } -RAMDISK_BASE_ENTRY * RAMDISK_PARTITION::FindEntry(const char* path) { - char *cptr; - if ( (cptr=strchr(path,':')) ) - path=cptr+1; //move path past any device names - if ( strchr(path, ':') != NULL ) { +RAMDISK_BASE_ENTRY * RAMDISK_PARTITION::FindEntry(const char* path) +{ + char *cptr; + if ( (cptr=strchr(path,':')) ) + path=cptr+1; //move path past any device names + if ( strchr(path, ':') != NULL ) + { // r->_errno = EINVAL; - return NULL; - } - if (*path=='/') // if first character is '/' use absolute root path - return RAMDISK_DIR_ENTRY::FindEntry(path); - else // else use current working dir - return cwd->FindEntry(path); + return NULL; + } + if(*path=='/') // if first character is '/' use absolute root path + return RAMDISK_DIR_ENTRY::FindEntry(path); + else // else use current working dir + return cwd->FindEntry(path); } -RAMDISK_DIR_ENTRY * RAMDISK_PARTITION::FindPath(const char* path, const char **basename) { - int pathLen = strlen(path); - char dirfilename[pathLen+1]; // to hold a full path - const char *cptr = path+pathLen; // find the end... - const char *filename = NULL; // to hold filename - while (cptr-->path) { //search till start - if ((*cptr=='/') || (*cptr==':')) { // split at either / or : (whichever comes first form the end!) - cptr++; - strlcpy(dirfilename, path, 1+cptr-path); //copy string up till and including / or : - filename = cptr; //filename = now remainder of string - break; - } - } - - if (!filename) { - filename = path; //filename = complete path - dirfilename[0] = 0; //make directory path "" - } - RAMDISK_BASE_ENTRY *entry = FindEntry(dirfilename); - if (entry) { - if (basename) *basename = filename; - return entry->IsDir(); - } - return NULL; +RAMDISK_DIR_ENTRY * RAMDISK_PARTITION::FindPath(const char* path, const char **basename) +{ + int pathLen = strlen(path); + char dirfilename[pathLen+1]; // to hold a full path + const char *cptr = path+pathLen; // find the end... + const char *filename = NULL; // to hold filename + while(cptr-->path) //search till start + { + if((*cptr=='/') || (*cptr==':')) // split at either / or : (whichever comes first form the end!) + { + cptr++; + strlcpy(dirfilename, path, 1+cptr-path); //copy string up till and including / or : + filename = cptr; //filename = now remainder of string + break; + } + } + + if(!filename) + { + filename = path; //filename = complete path + dirfilename[0] = 0; //make directory path "" + } + RAMDISK_BASE_ENTRY *entry = FindEntry(dirfilename); + if(entry) + { + if(basename) *basename = filename; + return entry->IsDir(); + } + return NULL; } FILE_DATA::FILE_DATA(size_t Len) : - next(NULL) { - data = new u8[Len]; - len = Len; - memset(data, 0, len); -} -FILE_DATA::~FILE_DATA() { - delete [] data; - delete next; +next(NULL) +{ + data = new u8[Len]; + len = Len; + memset(data, 0, len); +} +FILE_DATA::~FILE_DATA() +{ + delete [] data; + delete next; } RAMDISK_FILE_ENTRY::RAMDISK_FILE_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent) - : - RAMDISK_BASE_ENTRY(Name, Parent), - file_len(0), - cluster_len(0), - first_cluster(NULL), - last_cluster(NULL) {} -RAMDISK_FILE_ENTRY::~RAMDISK_FILE_ENTRY() { - Truncate(0); +: +RAMDISK_BASE_ENTRY(Name, Parent), +file_len(0), +cluster_len(0), +first_cluster(NULL), +last_cluster(NULL) +{} +RAMDISK_FILE_ENTRY::~RAMDISK_FILE_ENTRY() +{ + Truncate(0); } #define CLUSTER_SIZE 4*1024 -bool RAMDISK_FILE_ENTRY::Truncate(size_t newSize) { - if (newSize > cluster_len) { - // Expanding the file over cluster_len - return AddCluster(newSize - cluster_len); - } else if (newSize < file_len) { - // Shrinking the file - FILE_DATA *prev_cluster = NULL; - size_t len = 0; - for (FILE_DATA **p_cluster = &first_cluster; *p_cluster; p_cluster = &(*p_cluster)->next) { - if (len >= newSize) { - last_cluster = prev_cluster; - delete *p_cluster; - (*p_cluster) = NULL; - break; - } - len += (*p_cluster)->len; - prev_cluster = *p_cluster; - } - } - file_len = newSize; - return true; +bool RAMDISK_FILE_ENTRY::Truncate(size_t newSize) +{ + if (newSize > cluster_len) + { + // Expanding the file over cluster_len + return AddCluster(newSize - cluster_len); + } + else if (newSize < file_len) + { + // Shrinking the file + FILE_DATA *prev_cluster = NULL; + size_t len = 0; + for(FILE_DATA **p_cluster = &first_cluster; *p_cluster; p_cluster = &(*p_cluster)->next) + { + if(len >= newSize) + { + last_cluster = prev_cluster; + delete *p_cluster; + (*p_cluster) = NULL; + break; + } + len += (*p_cluster)->len; + prev_cluster = *p_cluster; + } + } + file_len = newSize; + return true; } -bool RAMDISK_FILE_ENTRY::AddCluster(size_t len) { - if (len < CLUSTER_SIZE) - len = CLUSTER_SIZE; - try { - *(last_cluster ? &last_cluster->next : &first_cluster) = last_cluster = new FILE_DATA(len); - cluster_len += len; - return true; - } catch (...) { - return false; - } +bool RAMDISK_FILE_ENTRY::AddCluster(size_t len) +{ + if(len < CLUSTER_SIZE) + len = CLUSTER_SIZE; + try + { + *(last_cluster ? &last_cluster->next : &first_cluster) = last_cluster = new FILE_DATA(len); + cluster_len += len; + return true; + } + catch(...) { return false; } } -size_t RAMDISK_FILE_ENTRY::Read(struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len) { - if (!fileStruct->read) { - r->_errno = EBADF; - return 0; - } - // Short circuit cases where len is 0 (or less) - if (len <= 0) - return 0; - // Don't try to read if the read pointer is past the end of file - if (fileStruct->current_pos >= file_len) { - r->_errno = EOVERFLOW; - return 0; - } +size_t RAMDISK_FILE_ENTRY::Read(struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len) +{ + if (!fileStruct->read) + { + r->_errno = EBADF; + return 0; + } + // Short circuit cases where len is 0 (or less) + if (len <= 0) + return 0; + // Don't try to read if the read pointer is past the end of file + if (fileStruct->current_pos >= file_len) + { + r->_errno = EOVERFLOW; + return 0; + } - // Don't read past end of file - if (len + fileStruct->current_pos > file_len) { - r->_errno = EOVERFLOW; - len = fileStruct->current_pos - file_len; - } + // Don't read past end of file + if (len + fileStruct->current_pos > file_len) + { + r->_errno = EOVERFLOW; + len = fileStruct->current_pos - file_len; + } - off_t pos = fileStruct->current_pos; - size_t readed = 0; - size_t max_len = file_len; - for (FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) { - if (pos > cluster->len) { - pos -= cluster->len; - max_len -= cluster->len; - } else { - size_t read = max_len; - if (read > cluster->len) - read = cluster->len; - read -= pos; - if (read > len) - read = len; - memcpy(ptr, &(cluster->data[pos]), read); - readed += read; - ptr += read; - len -= read; - if (len == 0) - break; - pos -= cluster->len; - max_len -= cluster->len; - - } - } - fileStruct->current_pos += readed; - return readed; + off_t pos = fileStruct->current_pos; + size_t readed = 0; + size_t max_len = file_len; + for(FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) + { + if(pos > cluster->len) + { + pos -= cluster->len; + max_len -= cluster->len; + } + else + { + size_t read = max_len; + if(read > cluster->len) + read = cluster->len; + read -= pos; + if(read > len) + read = len; + memcpy(ptr, &(cluster->data[pos]), read); + readed += read; + ptr += read; + len -= read; + if(len == 0) + break; + pos -= cluster->len; + max_len -= cluster->len; + + } + } + fileStruct->current_pos += readed; + return readed; } -size_t RAMDISK_FILE_ENTRY::Write(struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len) { +size_t RAMDISK_FILE_ENTRY::Write(struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len) +{ - if (!fileStruct->write) { - r->_errno = EBADF; - return 0; - } - // Short circuit cases where len is 0 (or less) - if (len <= 0) - return 0; + if (!fileStruct->write) + { + r->_errno = EBADF; + return 0; + } + // Short circuit cases where len is 0 (or less) + if (len <= 0) + return 0; - off_t pos = fileStruct->current_pos; - if (cluster_len < (pos+len) && !AddCluster((pos+len) - cluster_len)) { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - return 0; - } - if (file_len < (pos+len)) - file_len = (pos+len); - - size_t written = 0; - size_t max_len = cluster_len; - for (FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) { - if (pos > cluster->len) { - pos -= cluster->len; - max_len -= cluster->len; - } else { - size_t write = cluster->len - pos; - if (write > len) write = len; - memcpy(&(cluster->data[pos]), ptr, write); - written += write; - ptr += write; - len -= write; - if (len == 0) - break; - pos -= cluster->len; - max_len -= cluster->len; - } - } - fileStruct->current_pos += written; - return written; + off_t pos = fileStruct->current_pos; + if(cluster_len < (pos+len) && !AddCluster((pos+len) - cluster_len)) + { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + return 0; + } + if(file_len < (pos+len)) + file_len = (pos+len); + + size_t written = 0; + size_t max_len = cluster_len; + for(FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) + { + if(pos > cluster->len) + { + pos -= cluster->len; + max_len -= cluster->len; + } + else + { + size_t write = cluster->len - pos; + if(write > len) write = len; + memcpy(&(cluster->data[pos]), ptr, write); + written += write; + ptr += write; + len -= write; + if(len == 0) + break; + pos -= cluster->len; + max_len -= cluster->len; + } + } + fileStruct->current_pos += written; + return written; } @@ -428,41 +490,41 @@ static int ramdiskFS_ftruncate_r(struct _reent *r, int fd, off_t len); static devoptab_t ramdiskFS_devoptab={ - "ramdisk", - sizeof(FILE_STRUCT), // int structSize; - &ramdiskFS_open_r, // int (*open_r)(struct _reent *r, void *fileStruct, const char *path,int - // flags,int mode); - &ramdiskFS_close_r, // int (*close_r)(struct _reent *r, int fd); - &ramdiskFS_write_r, // int (*write_r)(struct _reent *r, int fd, const char *ptr, int len); - &ramdiskFS_read_r, // int (*read_r)(struct _reent *r, int fd, char *ptr, int len); - &ramdiskFS_seek_r, // off_t (*seek_r)(struct _reent *r, off_t fd, int pos, int dir); - &ramdiskFS_fstat_r, // int (*fstat_r)(struct _reent *r, int fd, struct stat *st); - &ramdiskFS_stat_r, // int (*stat_r)(struct _reent *r, const char *file, struct stat *st); - NULL, // int (*link_r)(struct _reent *r, const char *existing, const char *newLink); - &ramdiskFS_unlink_r, // int (*unlink_r)(struct _reent *r, const char *name); - &ramdiskFS_chdir_r, // int (*chdir_r)(struct _reent *r, const char *name); - NULL, // int (*rename_r) (struct _reent *r, const char *oldName, const char *newName); - ramdiskFS_mkdir_r, // int (*mkdir_r) (struct _reent *r, const char *path, int mode); - sizeof(DIR_STRUCT), // int dirStateSize; - &ramdiskFS_diropen_r, // DIR_ITER* (*diropen_r)(struct _reent *r, DIR_ITER *dirState, const char *path); - &ramdiskFS_dirreset_r, // int (*dirreset_r)(struct _reent *r, DIR_ITER *dirState); - &ramdiskFS_dirnext_r, // int (*dirnext_r)(struct _reent *r, DIR_ITER *dirState, char *filename, - // struct stat *filestat); - &ramdiskFS_dirclose_r, // int (*dirclose_r)(struct _reent *r, DIR_ITER *dirState); - NULL, // statvfs_r - &ramdiskFS_ftruncate_r, // int (*ftruncate_r)(struct _reent *r, int fd, off_t len); + "ramdisk", + sizeof(FILE_STRUCT), // int structSize; + &ramdiskFS_open_r, // int (*open_r)(struct _reent *r, void *fileStruct, const char *path,int + // flags,int mode); + &ramdiskFS_close_r, // int (*close_r)(struct _reent *r, int fd); + &ramdiskFS_write_r, // int (*write_r)(struct _reent *r, int fd, const char *ptr, int len); + &ramdiskFS_read_r, // int (*read_r)(struct _reent *r, int fd, char *ptr, int len); + &ramdiskFS_seek_r, // off_t (*seek_r)(struct _reent *r, off_t fd, int pos, int dir); + &ramdiskFS_fstat_r, // int (*fstat_r)(struct _reent *r, int fd, struct stat *st); + &ramdiskFS_stat_r, // int (*stat_r)(struct _reent *r, const char *file, struct stat *st); + NULL, // int (*link_r)(struct _reent *r, const char *existing, const char *newLink); + &ramdiskFS_unlink_r, // int (*unlink_r)(struct _reent *r, const char *name); + &ramdiskFS_chdir_r, // int (*chdir_r)(struct _reent *r, const char *name); + NULL, // int (*rename_r) (struct _reent *r, const char *oldName, const char *newName); + ramdiskFS_mkdir_r, // int (*mkdir_r) (struct _reent *r, const char *path, int mode); + sizeof(DIR_STRUCT), // int dirStateSize; + &ramdiskFS_diropen_r, // DIR_ITER* (*diropen_r)(struct _reent *r, DIR_ITER *dirState, const char *path); + &ramdiskFS_dirreset_r, // int (*dirreset_r)(struct _reent *r, DIR_ITER *dirState); + &ramdiskFS_dirnext_r, // int (*dirnext_r)(struct _reent *r, DIR_ITER *dirState, char *filename, + // struct stat *filestat); + &ramdiskFS_dirclose_r, // int (*dirclose_r)(struct _reent *r, DIR_ITER *dirState); + NULL, // statvfs_r + &ramdiskFS_ftruncate_r, // int (*ftruncate_r)(struct _reent *r, int fd, off_t len); - NULL, // fsync_r, - NULL // Device data + NULL, // fsync_r, + NULL // Device data }; //--------------------------------------------------------------------------------- static inline RAMDISK_PARTITION* ramdiskFS_getPartitionFromPath(const char* path) { //--------------------------------------------------------------------------------- - const devoptab_t *devops = GetDeviceOpTab(path); - if (!devops) - return NULL; - return *((RAMDISK_PARTITION**)devops->deviceData); + const devoptab_t *devops = GetDeviceOpTab(path); + if (!devops) + return NULL; + return *((RAMDISK_PARTITION**)devops->deviceData); } //--------------------------------------------------------------------------------- @@ -470,229 +532,254 @@ static inline RAMDISK_PARTITION* ramdiskFS_getPartitionFromPath(const char* path //--------------------------------------------------------------------------------- static int ramdiskFS_open_r(struct _reent *r, void *file_Struct, const char *path, int flags, int mode) { //--------------------------------------------------------------------------------- - FILE_STRUCT *fileStruct = (FILE_STRUCT*)file_Struct; + FILE_STRUCT *fileStruct = (FILE_STRUCT*)file_Struct; - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); - if ( partition == NULL ) { - r->_errno = ENODEV; - return -1; - } + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } - if ((flags & 0x03) == O_RDONLY) { - // Open the file for read-only access - fileStruct->read = true; - fileStruct->write = false; - } else if ((flags & 0x03) == O_WRONLY) { - // Open file for write only access - fileStruct->read = false; - fileStruct->write = true; - } else if ((flags & 0x03) == O_RDWR) { - // Open file for read/write access - fileStruct->read = true; - fileStruct->write = true; - } else { - r->_errno = EACCES; - return -1; - } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry(path); + if ((flags & 0x03) == O_RDONLY) { + // Open the file for read-only access + fileStruct->read = true; + fileStruct->write = false; + } else if ((flags & 0x03) == O_WRONLY) { + // Open file for write only access + fileStruct->read = false; + fileStruct->write = true; + } else if ((flags & 0x03) == O_RDWR) { + // Open file for read/write access + fileStruct->read = true; + fileStruct->write = true; + } else { + r->_errno = EACCES; + return -1; + } + RAMDISK_BASE_ENTRY *entry = partition->FindEntry(path); + + // The file shouldn't exist if we are trying to create it + if (entry && (flags & O_CREAT) && (flags & O_EXCL)) + { + r->_errno = EEXIST; + return -1; + } + // It should not be a directory if we're openning a file, + if (entry && entry->IsDir()) + { + r->_errno = EISDIR; + return -1; + } - // The file shouldn't exist if we are trying to create it - if (entry && (flags & O_CREAT) && (flags & O_EXCL)) { - r->_errno = EEXIST; - return -1; - } - // It should not be a directory if we're openning a file, - if (entry && entry->IsDir()) { - r->_errno = EISDIR; - return -1; - } - - fileStruct->isLink = entry ? entry->IsLink() : false; - fileStruct->file = entry ? entry->IsFile() : NULL; - if (!fileStruct->file) { // entry not exists - if (flags & O_CREAT) { - const char *filename; - RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); - if (!dir) { - r->_errno = ENOTDIR; - return -1; - } - fileStruct->file = dir->CreateFile(filename); - } else { - // file doesn't exist, and we aren't creating it - r->_errno = ENOENT; - return -1; - } - } - if (fileStruct->file) { - fileStruct->current_pos = 0; - // Truncate the file if requested - if ((flags & O_TRUNC) && fileStruct->write) - fileStruct->file->Truncate(0); - if (flags & O_APPEND) - fileStruct->current_pos = fileStruct->file->file_len; - return 0; - } - r->_errno = ENOENT; - return(-1); + fileStruct->isLink = entry ? entry->IsLink() : false; + fileStruct->file = entry ? entry->IsFile() : NULL; + if(!fileStruct->file) // entry not exists + { + if (flags & O_CREAT) + { + const char *filename; + RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); + if(!dir) + { + r->_errno = ENOTDIR; + return -1; + } + fileStruct->file = dir->CreateFile(filename); + } + else + { + // file doesn't exist, and we aren't creating it + r->_errno = ENOENT; + return -1; + } + } + if(fileStruct->file) + { + fileStruct->current_pos = 0; + // Truncate the file if requested + if ((flags & O_TRUNC) && fileStruct->write) + fileStruct->file->Truncate(0); + if (flags & O_APPEND) + fileStruct->current_pos = fileStruct->file->file_len; + return 0; + } + r->_errno = ENOENT; + return(-1); } //--------------------------------------------------------------------------------- static int ramdiskFS_close_r(struct _reent *r, int fd) { //--------------------------------------------------------------------------------- - return(0); + return(0); } //--------------------------------------------------------------------------------- static int ramdiskFS_read_r(struct _reent *r, int fd, char *ptr, size_t len) { //--------------------------------------------------------------------------------- - FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; - return fileStruct->file->Read(r, fileStruct, ptr, len); + FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; + return fileStruct->file->Read(r, fileStruct, ptr, len); } //--------------------------------------------------------------------------------- static int ramdiskFS_write_r(struct _reent *r, int fd, const char *ptr, size_t len) { //--------------------------------------------------------------------------------- - FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; - return fileStruct->file->Write(r, fileStruct, ptr, len); + FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; + return fileStruct->file->Write(r, fileStruct, ptr, len); } //--------------------------------------------------------------------------------- static off_t ramdiskFS_seek_r(struct _reent *r, int fd, off_t pos, int dir) { //--------------------------------------------------------------------------------- - //need check for eof here... - FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; - - switch (dir) { - case SEEK_SET: - break; - case SEEK_CUR: - pos += fileStruct->current_pos; - break; - case SEEK_END: - pos += fileStruct->file->file_len; // set start to end of file - break; - default: - r->_errno = EINVAL; - return -1; - } - return fileStruct->current_pos = pos; + //need check for eof here... + FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; + + switch(dir) + { + case SEEK_SET: + break; + case SEEK_CUR: + pos += fileStruct->current_pos; + break; + case SEEK_END: + pos += fileStruct->file->file_len; // set start to end of file + break; + default: + r->_errno = EINVAL; + return -1; + } + return fileStruct->current_pos = pos; } //--------------------------------------------------------------------------------- static int ramdiskFS_fstat_r(struct _reent *r, int fd, struct stat *st) { //--------------------------------------------------------------------------------- - FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; + FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; - st->st_mode = fileStruct->isLink ? S_IFLNK : S_IFREG; - st->st_size = fileStruct->file->file_len; - return(0); + st->st_mode = fileStruct->isLink ? S_IFLNK : S_IFREG; + st->st_size = fileStruct->file->file_len; + return(0); } //--------------------------------------------------------------------------------- static int ramdiskFS_stat_r(struct _reent *r, const char *file, struct stat *st) { //--------------------------------------------------------------------------------- - FILE_STRUCT fileStruct; - DIR_STRUCT dirStruct; - DIR_ITER dirState; - dirState.dirStruct=&dirStruct; //create a temp dirstruct - int ret; + FILE_STRUCT fileStruct; + DIR_STRUCT dirStruct; + DIR_ITER dirState; + dirState.dirStruct=&dirStruct; //create a temp dirstruct + int ret; - if ( ramdiskFS_open_r(r, &fileStruct, file, 0, 0) ==0 ) { - ret = ramdiskFS_fstat_r(r, (int)&fileStruct, st); - ramdiskFS_close_r(r, (int)&fileStruct); - return(ret); - } else if ( (ramdiskFS_diropen_r(r, &dirState, file)!=NULL) ) { - st->st_mode = S_IFDIR; - ramdiskFS_dirclose_r(r, &dirState); - return(0); - } - r->_errno = ENOENT; - return(-1); + if( ramdiskFS_open_r(r, &fileStruct, file, 0, 0) ==0 ) + { + ret = ramdiskFS_fstat_r(r, (int)&fileStruct, st); + ramdiskFS_close_r(r, (int)&fileStruct); + return(ret); + } + else if( (ramdiskFS_diropen_r(r, &dirState, file)!=NULL) ) + { + st->st_mode = S_IFDIR; + ramdiskFS_dirclose_r(r, &dirState); + return(0); + } + r->_errno = ENOENT; + return(-1); } //--------------------------------------------------------------------------------- static int ramdiskFS_unlink_r(struct _reent *r, const char *name) { //--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(name); - if ( partition == NULL ) { - r->_errno = ENODEV; - return -1; - } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry(name); - if (!entry) { - r->_errno = ENOENT; - return -1; - } + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(name); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + RAMDISK_BASE_ENTRY *entry = partition->FindEntry(name); + if(!entry) + { + r->_errno = ENOENT; + return -1; + } + + if (entry->IsLink()) + { + if(entry->name[0] == '.' && (entry->name[1] == '\0' || (entry->name[1] == '.' && entry->name[2] == '\0'))) + { + r->_errno = EPERM; + return -1; + } + delete entry; + return 0; + } - if (entry->IsLink()) { - if (entry->name[0] == '.' && (entry->name[1] == '\0' || (entry->name[1] == '.' && entry->name[2] == '\0'))) { - r->_errno = EPERM; - return -1; - } - delete entry; - return 0; - } - - if (RAMDISK_DIR_ENTRY *dir = entry->IsDir()) { - for (RAMDISK_BASE_ENTRY *entry = dir->first; entry; entry = entry->next) { - if (!(entry->name[0] == '.' && (entry->name[1] == '\0' - || (entry->name[1] == '.' && entry->name[2] == '\0')))) { - r->_errno = EPERM; - return -1; - } - } - } - delete entry; - return 0; + if (RAMDISK_DIR_ENTRY *dir = entry->IsDir()) + { + for(RAMDISK_BASE_ENTRY *entry = dir->first; entry; entry = entry->next) + { + if(!(entry->name[0] == '.' && (entry->name[1] == '\0' + || (entry->name[1] == '.' && entry->name[2] == '\0')))) + { + r->_errno = EPERM; + return -1; + } + } + } + delete entry; + return 0; } //--------------------------------------------------------------------------------- static int ramdiskFS_chdir_r(struct _reent *r, const char *name) { //--------------------------------------------------------------------------------- - DIR_STRUCT dirStruct; - DIR_ITER dirState; - dirState.dirStruct=&dirStruct; - if ( (name == NULL) ) { - r->_errno = ENODEV; - return -1; - } + DIR_STRUCT dirStruct; + DIR_ITER dirState; + dirState.dirStruct=&dirStruct; + if( (name == NULL) ) + { + r->_errno = ENODEV; + return -1; + } + + if( (ramdiskFS_diropen_r(r, &dirState, name) == NULL) ) + return -1; - if ( (ramdiskFS_diropen_r(r, &dirState, name) == NULL) ) - return -1; - - RAMDISK_PARTITION *partition = dirStruct.dir->GetPartition(); - if ( partition == NULL ) { - r->_errno = ENODEV; - return -1; - } - partition->cwd = dirStruct.dir; - ramdiskFS_dirclose_r(r, &dirState); - return 0; + RAMDISK_PARTITION *partition = dirStruct.dir->GetPartition(); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + partition->cwd = dirStruct.dir; + ramdiskFS_dirclose_r(r, &dirState); + return 0; } //--------------------------------------------------------------------------------- static int ramdiskFS_mkdir_r(struct _reent *r, const char *path, int mode) { //--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); - if ( partition == NULL ) { - r->_errno = ENODEV; - return -1; - } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry(path); - if (entry) { - r->_errno = EEXIST; - return -1; - } - const char *filename; - RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); - if (!dir) { - r->_errno = ENOTDIR; - return -1; - } - dir->CreateDir(filename); - return 0; + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + RAMDISK_BASE_ENTRY *entry = partition->FindEntry(path); + if (entry) + { + r->_errno = EEXIST; + return -1; + } + const char *filename; + RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); + if(!dir) + { + r->_errno = ENOTDIR; + return -1; + } + dir->CreateDir(filename); + return 0; } //--------------------------------------------------------------------------------- @@ -701,39 +788,43 @@ static int ramdiskFS_mkdir_r(struct _reent *r, const char *path, int mode) { static DIR_ITER* ramdiskFS_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path) { //--------------------------------------------------------------------------------- - DIR_STRUCT *dirStruct = (DIR_STRUCT*)dirState->dirStruct; - char *cptr; + DIR_STRUCT *dirStruct = (DIR_STRUCT*)dirState->dirStruct; + char *cptr; - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); - if ( partition == NULL ) { - r->_errno = ENODEV; - return NULL; - } + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return NULL; + } - if ( (cptr=strchr(path,':')) ) - path=cptr+1; //move path past any device names - if ( strchr(path, ':') != NULL ) { - r->_errno = EINVAL; - return NULL; - } + if ( (cptr=strchr(path,':')) ) + path=cptr+1; //move path past any device names + if ( strchr(path, ':') != NULL ) + { + r->_errno = EINVAL; + return NULL; + } - if (*path=='/') //if first character is '/' use absolute root path - dirStruct->dir = partition; //first root dir - else - dirStruct->dir = partition->cwd; //else use current working dir + if(*path=='/') //if first character is '/' use absolute root path + dirStruct->dir = partition; //first root dir + else + dirStruct->dir = partition->cwd; //else use current working dir - RAMDISK_BASE_ENTRY *entry = dirStruct->dir->FindEntry(path); - if (entry==NULL) { - r->_errno = ENOENT; - return NULL; - } - dirStruct->dir = entry->IsDir(); - if (dirStruct->dir==NULL) { - r->_errno = ENOTDIR; - return NULL; - } - dirStruct->current_entry = dirStruct->dir->first; - return dirState; + RAMDISK_BASE_ENTRY *entry = dirStruct->dir->FindEntry(path); + if(entry==NULL) + { + r->_errno = ENOENT; + return NULL; + } + dirStruct->dir = entry->IsDir(); + if(dirStruct->dir==NULL) + { + r->_errno = ENOTDIR; + return NULL; + } + dirStruct->current_entry = dirStruct->dir->first; + return dirState; } /*Consts containing relative system path strings*/ @@ -741,153 +832,164 @@ static DIR_ITER* ramdiskFS_diropen_r(struct _reent *r, DIR_ITER *dirState, const //--------------------------------------------------------------------------------- static int ramdiskFS_dirreset_r(struct _reent *r, DIR_ITER *dirState) { //--------------------------------------------------------------------------------- - DIR_STRUCT *dirStruct = (DIR_STRUCT*)dirState->dirStruct; - dirStruct->current_entry = dirStruct->dir->first; - return(0); + DIR_STRUCT *dirStruct = (DIR_STRUCT*)dirState->dirStruct; + dirStruct->current_entry = dirStruct->dir->first; + return(0); } //--------------------------------------------------------------------------------- static int ramdiskFS_dirnext_r(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st) { //--------------------------------------------------------------------------------- - DIR_STRUCT *dirStruct = (DIR_STRUCT*)dirState->dirStruct; + DIR_STRUCT *dirStruct = (DIR_STRUCT*)dirState->dirStruct; // RAMDISK_BASE_ENTRY **dirStruct = (RAMDISK_BASE_ENTRY**)dirState->dirStruct; - if (dirStruct->current_entry) { - strcpy(filename, dirStruct->current_entry->name); - if (dirStruct->current_entry->IsDir()) { - if (st) st->st_mode=S_IFDIR; - } else { - if (st) st->st_mode=0; - } - dirStruct->current_entry = dirStruct->current_entry->next; - return(0); - } - r->_errno = ENOENT; - return(-1); + if(dirStruct->current_entry) + { + strcpy(filename, dirStruct->current_entry->name); + if(dirStruct->current_entry->IsDir()) + { + if(st) st->st_mode=S_IFDIR; + } + else + { + if(st) st->st_mode=0; + } + dirStruct->current_entry = dirStruct->current_entry->next; + return(0); + } + r->_errno = ENOENT; + return(-1); } //--------------------------------------------------------------------------------- static int ramdiskFS_dirclose_r(struct _reent *r, DIR_ITER *dirState) { //--------------------------------------------------------------------------------- - return(0); + return(0); } //--------------------------------------------------------------------------------- static int ramdiskFS_ftruncate_r(struct _reent *r, int fd, off_t len) { //--------------------------------------------------------------------------------- - FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; + FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; - if (len < 0) { - // Trying to truncate to a negative size - r->_errno = EINVAL; - return -1; - } - /* - if ((sizeof(len) > 4) && len > (off_t)FILE_MAX_SIZE) - { - // Trying to extend the file beyond what supports - r->_errno = EFBIG; - return -1; - } - */ - if (!fileStruct->write) { - // Read-only file - r->_errno = EINVAL; - return -1; - } - if (fileStruct->file->Truncate(len)) - return 0; - r->_errno = ENOSPC; - return -1; + if (len < 0) + { + // Trying to truncate to a negative size + r->_errno = EINVAL; + return -1; + } +/* + if ((sizeof(len) > 4) && len > (off_t)FILE_MAX_SIZE) + { + // Trying to extend the file beyond what supports + r->_errno = EFBIG; + return -1; + } +*/ + if (!fileStruct->write) + { + // Read-only file + r->_errno = EINVAL; + return -1; + } + if(fileStruct->file->Truncate(len)) + return 0; + r->_errno = ENOSPC; + return -1; } //--------------------------------------------------------------------------------- void ramdiskFS_Unmount(const char* mountpoint) { //--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition; - devoptab_t *devops = (devoptab_t*)GetDeviceOpTab(mountpoint); + RAMDISK_PARTITION *partition; + devoptab_t *devops = (devoptab_t*)GetDeviceOpTab(mountpoint); + + if (!devops) + return; - if (!devops) - return; + // Perform a quick check to make sure we're dealing with a ramdiskFS_ controlled device + if (devops->open_r != ramdiskFS_devoptab.open_r) + return; + + if (RemoveDevice (mountpoint) == -1) + return; - // Perform a quick check to make sure we're dealing with a ramdiskFS_ controlled device - if (devops->open_r != ramdiskFS_devoptab.open_r) - return; - - if (RemoveDevice (mountpoint) == -1) - return; - - partition = *((RAMDISK_PARTITION **)devops->deviceData); - if (partition->automount) - delete partition; - free (devops); + partition = *((RAMDISK_PARTITION **)devops->deviceData); + if(partition->automount) + delete partition; + free (devops); } extern "C" void ramdiskUnmount(const char *mountpoint) { - ramdiskFS_Unmount(mountpoint); + ramdiskFS_Unmount(mountpoint); } //--------------------------------------------------------------------------------- int ramdiskFS_Mount(const char *mountpoint, void *handle) { //--------------------------------------------------------------------------------- - devoptab_t* devops; - char* nameCopy; - RAMDISK_PARTITION** partition; - char Mountpoint[100]; - char *cptr; + devoptab_t* devops; + char* nameCopy; + RAMDISK_PARTITION** partition; + char Mountpoint[100]; + char *cptr; - strlcpy(Mountpoint, mountpoint, sizeof(Mountpoint)); - int len = strlen(Mountpoint); - cptr = strchr(Mountpoint, ':'); - if (cptr) { - len = cptr-Mountpoint; - *++cptr = 0; - } else - strlcat(Mountpoint, ":", sizeof(Mountpoint)); - ramdiskFS_Unmount(Mountpoint); - if (handle) ramdiskFS_Unmount(((RAMDISK_PARTITION*)handle)->name); + strlcpy(Mountpoint, mountpoint, sizeof(Mountpoint)); + int len = strlen(Mountpoint); + cptr = strchr(Mountpoint, ':'); + if(cptr) + { + len = cptr-Mountpoint; + *++cptr = 0; + } + else + strlcat(Mountpoint, ":", sizeof(Mountpoint)); + ramdiskFS_Unmount(Mountpoint); + if(handle) ramdiskFS_Unmount(((RAMDISK_PARTITION*)handle)->name); + + devops = (devoptab_t*)malloc(sizeof(devoptab_t) + sizeof(RAMDISK_PARTITION*) + len + 1); + if (!devops) + return false; - devops = (devoptab_t*)malloc(sizeof(devoptab_t) + sizeof(RAMDISK_PARTITION*) + len + 1); - if (!devops) - return false; + partition = (RAMDISK_PARTITION**)(devops+1); // Use the space allocated at the end of the devoptab struct + // for storing the partition + nameCopy = (char*)( partition+1); // Use the space allocated at the end of the partition struct + // for storing the name + + memcpy (devops, &ramdiskFS_devoptab, sizeof(ramdiskFS_devoptab)); // Add an entry for this device to the devoptab table - partition = (RAMDISK_PARTITION**)(devops+1); // Use the space allocated at the end of the devoptab struct - // for storing the partition - nameCopy = (char*)( partition+1); // Use the space allocated at the end of the partition struct - // for storing the name + strlcpy (nameCopy, Mountpoint, len + 1); + devops->name = nameCopy; + + if(handle) + { + *partition = (RAMDISK_PARTITION*)handle; + (*partition)->Rename(Mountpoint); + } + else + *partition = new RAMDISK_PARTITION(Mountpoint, true); + devops->deviceData = partition; - memcpy (devops, &ramdiskFS_devoptab, sizeof(ramdiskFS_devoptab)); // Add an entry for this device to the devoptab table + if(AddDevice(devops)<0) + { + free(devops); + return false; + } - strlcpy (nameCopy, Mountpoint, len + 1); - devops->name = nameCopy; - - if (handle) { - *partition = (RAMDISK_PARTITION*)handle; - (*partition)->Rename(Mountpoint); - } else - *partition = new RAMDISK_PARTITION(Mountpoint, true); - devops->deviceData = partition; - - if (AddDevice(devops)<0) { - free(devops); - return false; - } - - return true; + return true; } extern "C" int ramdiskMount(const char *mountpoint, void *handle) { - return ramdiskFS_Mount(mountpoint, handle); + return ramdiskFS_Mount(mountpoint, handle); } //--------------------------------------------------------------------------------- extern "C" void* ramdiskCreate() { //--------------------------------------------------------------------------------- - return new RAMDISK_PARTITION("", false); + return new RAMDISK_PARTITION("", false); } //--------------------------------------------------------------------------------- extern "C" void ramdiskDelete(void* Handle) { //--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition = (RAMDISK_PARTITION*)Handle; - if (partition->automount==false) - ramdiskFS_Unmount(partition->name); - delete partition; + RAMDISK_PARTITION *partition = (RAMDISK_PARTITION*)Handle; + if(partition->automount==false) + ramdiskFS_Unmount(partition->name); + delete partition; } diff --git a/source/ramdisk/ramdisk.h b/source/ramdisk/ramdisk.h index 9f40c656..60e64fcd 100644 --- a/source/ramdisk/ramdisk.h +++ b/source/ramdisk/ramdisk.h @@ -2,81 +2,82 @@ #define __RAMDISK_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - /* - ramdiskCreate initialize a dynamic RAM-disk. - return: Handle for ramdiskMount - */ - void* ramdiskCreate(); +/* +ramdiskCreate initialize a dynamic RAM-disk. +return: Handle for ramdiskMount +*/ +void* ramdiskCreate(); - /************************************************** - * ramdiskDelete - * - * destroy all datas - * if the ramdisk is allready mounted forces ramdiskUnmount - * IN: a Handle was created witch ramdiskCreate(); - **************************************************/ - void ramdiskDelete(void* Handle); +/************************************************** + * ramdiskDelete + * + * destroy all datas + * if the ramdisk is allready mounted forces ramdiskUnmount + * IN: a Handle was created witch ramdiskCreate(); + **************************************************/ +void ramdiskDelete(void* Handle); - /************************************************** - * ramdiskMount - * - * mounts a ramdisk - * IN: mountpoint e.g. "RAM" or "MEM:" - * handle is a Handle was created ramdiskCreate() - * or NULL for auto-create - * OUT: 0 = Error / !0 = OK - **************************************************/ - int ramdiskMount(const char *mountpoint, void *handle); +/************************************************** + * ramdiskMount + * + * mounts a ramdisk + * IN: mountpoint e.g. "RAM" or "MEM:" + * handle is a Handle was created ramdiskCreate() + * or NULL for auto-create + * OUT: 0 = Error / !0 = OK + **************************************************/ +int ramdiskMount(const char *mountpoint, void *handle); - /************************************************** - * ramdiskUnmount - * - * unmounts a ramdisk - * IN: mountpoint e.g "RAM" or "MEM:" - **************************************************/ - void ramdiskUnmount(const char *mountpoint); +/************************************************** + * ramdiskUnmount + * + * unmounts a ramdisk + * IN: mountpoint e.g "RAM" or "MEM:" + **************************************************/ +void ramdiskUnmount(const char *mountpoint); - /* - NOTE: - if the ramdisk not explizit created with ramdiskCreate (e.g ramdiskMount("RAMDISK:", NULL)) - the ramdisk is implizit created. When unmount this "auto-created" ramdisk the ramdisk automitic deleted +/* +NOTE: +if the ramdisk not explizit created with ramdiskCreate (e.g ramdiskMount("RAMDISK:", NULL)) +the ramdisk is implizit created. When unmount this "auto-created" ramdisk the ramdisk automitic deleted - but if the ramdisk explizit created (with ramdiskCreate), - then we can remount the filesystem without lost all datas. +but if the ramdisk explizit created (with ramdiskCreate), +then we can remount the filesystem without lost all datas. - Example1: - ========= - void *ram = ramdiskCreate(); // create ramdisk - ramdiskMount("RAM", ram); // mount the ramdisk - ... - fopen("RAM:/file", ...); - ... - ramdiskMount("MEM", ram); // remount as MEM: (without lost of data) - ... - fopen("RAM:/file", ...); - ... - ramdiskUnmount("MEM"); // unmount - ... - ramdiskMount("RAM", ram); // remount as RAM: (without lost of data) - ... - ramdiskDelete(ram); // unmount and delete +Example1: +========= +void *ram = ramdiskCreate(); // create ramdisk +ramdiskMount("RAM", ram); // mount the ramdisk +... +fopen("RAM:/file", ...); +... +ramdiskMount("MEM", ram); // remount as MEM: (without lost of data) +... +fopen("RAM:/file", ...); +... +ramdiskUnmount("MEM"); // unmount +... +ramdiskMount("RAM", ram); // remount as RAM: (without lost of data) +... +ramdiskDelete(ram); // unmount and delete - Example2: - ========= - ramdiskMount("RAM", NULL); // create and mount the ramdisk - ... - fopen("RAM:/file", ...); - ... - ramdiskUnmount("RAM"); // unmount and delete - */ +Example2: +========= +ramdiskMount("RAM", NULL); // create and mount the ramdisk +... +fopen("RAM:/file", ...); +... +ramdiskUnmount("RAM"); // unmount and delete +*/ #ifdef __cplusplus } diff --git a/source/settings/Settings.cpp b/source/settings/Settings.cpp index 88ed7386..5bb98409 100644 --- a/source/settings/Settings.cpp +++ b/source/settings/Settings.cpp @@ -53,2673 +53,2958 @@ static const char *opts_partitions[settings_partitions_max] = {trNOOP("Game part static const char *opts_installdir[settings_installdir_max] = {trNOOP("None"), trNOOP("GAMEID_Gamename"), trNOOP("Gamename [GAMEID]")}; bool IsValidPartition(int fs_type, int cios) { - if (cios == 249 || cios == 250) { - return fs_type == FS_TYPE_WBFS; - } else { - return fs_type == FS_TYPE_WBFS || fs_type == FS_TYPE_FAT32 || fs_type == FS_TYPE_NTFS; - } + if (cios == 249 || cios == 250) { + return fs_type == FS_TYPE_WBFS; + } else { + return fs_type == FS_TYPE_WBFS || fs_type == FS_TYPE_FAT32 || fs_type == FS_TYPE_NTFS; + } } /**************************************************************************** * MenuSettings ***************************************************************************/ -int MenuSettings() { - int menu = MENU_NONE; - int ret; - int choice = 0; - bool exit = false; +int MenuSettings() +{ + int menu = MENU_NONE; + int ret; + int choice = 0; + bool exit = false; - // backup game language setting - char opt_lang[100]; - strcpy(opt_lang,Settings.language_path); - // backup title override setting - int opt_override = Settings.titlesOverride; - // backup partition index - u8 settingspartitionold = Settings.partition; + // backup game language setting + char opt_lang[100]; + strcpy(opt_lang,Settings.language_path); + // backup title override setting + int opt_override = Settings.titlesOverride; + // backup partition index + u8 settingspartitionold = Settings.partition; + + enum + { + FADE, + LEFT, + RIGHT + }; - enum { - FADE, - LEFT, - RIGHT - }; + int slidedirection = FADE; - int slidedirection = FADE; + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + char imgPath[100]; - char imgPath[100]; + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path); + GuiImageData MainButtonImgData(imgPath, settings_title_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path); - GuiImageData MainButtonImgData(imgPath, settings_title_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path); + GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path); - GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); + snprintf(imgPath, sizeof(imgPath), "%spageindicator.png", CFG.theme_path); + GuiImageData PageindicatorImgData(imgPath, pageindicator_png); - snprintf(imgPath, sizeof(imgPath), "%spageindicator.png", CFG.theme_path); - GuiImageData PageindicatorImgData(imgPath, pageindicator_png); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); + GuiImageData arrow_left(imgPath, startgame_arrow_left_png); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); - GuiImageData arrow_left(imgPath, startgame_arrow_left_png); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); + GuiImageData arrow_right(imgPath, startgame_arrow_right_png); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); - GuiImageData arrow_right(imgPath, startgame_arrow_right_png); + snprintf(imgPath, sizeof(imgPath), "%scredits_button.png", CFG.theme_path); + GuiImageData creditsImgData(imgPath, credits_button_png); - snprintf(imgPath, sizeof(imgPath), "%scredits_button.png", CFG.theme_path); - GuiImageData creditsImgData(imgPath, credits_button_png); + snprintf(imgPath, sizeof(imgPath), "%scredits_button_over.png", CFG.theme_path); + GuiImageData creditsOver(imgPath, credits_button_over_png); - snprintf(imgPath, sizeof(imgPath), "%scredits_button_over.png", CFG.theme_path); - GuiImageData creditsOver(imgPath, credits_button_over_png); + GuiImage creditsImg(&creditsImgData); + GuiImage creditsImgOver(&creditsOver); - GuiImage creditsImg(&creditsImgData); - GuiImage creditsImgOver(&creditsOver); + GuiTrigger trigA; + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + GuiTrigger trigHome; + trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + GuiTrigger trigL; + trigL.SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); + GuiTrigger trigR; + trigR.SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); + GuiTrigger trigMinus; + trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); + GuiTrigger trigPlus; + trigPlus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigHome; - trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiTrigger trigL; - trigL.SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); - GuiTrigger trigR; - trigR.SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); - GuiTrigger trigMinus; - trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); - GuiTrigger trigPlus; - trigPlus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); + GuiText titleTxt(tr("Settings"), 28, (GXColor) {0, 0, 0, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0,40); - GuiText titleTxt(tr("Settings"), 28, (GXColor) {0, 0, 0, 255}); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetPosition(0,40); + GuiImage settingsbackground(&settingsbg); - GuiImage settingsbackground(&settingsbg); + GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); + GuiImage backBtnImg(&btnOutline); + if (Settings.wsprompt == yes) + { + backBtnTxt.SetWidescreen(CFG.widescreen); + backBtnImg.SetWidescreen(CFG.widescreen); + } + GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); + backBtn.SetLabel(&backBtnTxt); + backBtn.SetTrigger(&trigB); - GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); - backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage backBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); + GuiButton homo(1,1); + homo.SetTrigger(&trigHome); - GuiButton homo(1,1); - homo.SetTrigger(&trigHome); + GuiImage PageindicatorImg1(&PageindicatorImgData); + GuiText PageindicatorTxt1("1", 22, (GXColor) { 0, 0, 0, 255}); + GuiButton PageIndicatorBtn1(PageindicatorImg1.GetWidth(), PageindicatorImg1.GetHeight()); + PageIndicatorBtn1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + PageIndicatorBtn1.SetPosition(165, 400); + PageIndicatorBtn1.SetImage(&PageindicatorImg1); + PageIndicatorBtn1.SetLabel(&PageindicatorTxt1); + PageIndicatorBtn1.SetSoundOver(&btnSoundOver); + PageIndicatorBtn1.SetSoundClick(&btnClick1); + PageIndicatorBtn1.SetTrigger(&trigA); + PageIndicatorBtn1.SetEffectGrow(); - GuiImage PageindicatorImg1(&PageindicatorImgData); - GuiText PageindicatorTxt1("1", 22, (GXColor) {0, 0, 0, 255}); - GuiButton PageIndicatorBtn1(PageindicatorImg1.GetWidth(), PageindicatorImg1.GetHeight()); - PageIndicatorBtn1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - PageIndicatorBtn1.SetPosition(165, 400); - PageIndicatorBtn1.SetImage(&PageindicatorImg1); - PageIndicatorBtn1.SetLabel(&PageindicatorTxt1); - PageIndicatorBtn1.SetSoundOver(&btnSoundOver); - PageIndicatorBtn1.SetSoundClick(&btnClick1); - PageIndicatorBtn1.SetTrigger(&trigA); - PageIndicatorBtn1.SetEffectGrow(); + GuiImage PageindicatorImg2(&PageindicatorImgData); + GuiText PageindicatorTxt2("2", 22, (GXColor) {0, 0, 0, 255}); + GuiButton PageIndicatorBtn2(PageindicatorImg2.GetWidth(), PageindicatorImg2.GetHeight()); + PageIndicatorBtn2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + PageIndicatorBtn2.SetPosition(200, 400); + PageIndicatorBtn2.SetImage(&PageindicatorImg2); + PageIndicatorBtn2.SetLabel(&PageindicatorTxt2); + PageIndicatorBtn2.SetSoundOver(&btnSoundOver); + PageIndicatorBtn2.SetSoundClick(&btnClick1); + PageIndicatorBtn2.SetTrigger(&trigA); + PageIndicatorBtn2.SetEffectGrow(); - GuiImage PageindicatorImg2(&PageindicatorImgData); - GuiText PageindicatorTxt2("2", 22, (GXColor) {0, 0, 0, 255}); - GuiButton PageIndicatorBtn2(PageindicatorImg2.GetWidth(), PageindicatorImg2.GetHeight()); - PageIndicatorBtn2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - PageIndicatorBtn2.SetPosition(200, 400); - PageIndicatorBtn2.SetImage(&PageindicatorImg2); - PageIndicatorBtn2.SetLabel(&PageindicatorTxt2); - PageIndicatorBtn2.SetSoundOver(&btnSoundOver); - PageIndicatorBtn2.SetSoundClick(&btnClick1); - PageIndicatorBtn2.SetTrigger(&trigA); - PageIndicatorBtn2.SetEffectGrow(); + GuiImage PageindicatorImg3(&PageindicatorImgData); + GuiText PageindicatorTxt3("3", 22, (GXColor) {0, 0, 0, 255}); + GuiButton PageIndicatorBtn3(PageindicatorImg3.GetWidth(), PageindicatorImg3.GetHeight()); + PageIndicatorBtn3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + PageIndicatorBtn3.SetPosition(235, 400); + PageIndicatorBtn3.SetImage(&PageindicatorImg3); + PageIndicatorBtn3.SetLabel(&PageindicatorTxt3); + PageIndicatorBtn3.SetSoundOver(&btnSoundOver); + PageIndicatorBtn3.SetSoundClick(&btnClick1); + PageIndicatorBtn3.SetTrigger(&trigA); + PageIndicatorBtn3.SetEffectGrow(); - GuiImage PageindicatorImg3(&PageindicatorImgData); - GuiText PageindicatorTxt3("3", 22, (GXColor) {0, 0, 0, 255}); - GuiButton PageIndicatorBtn3(PageindicatorImg3.GetWidth(), PageindicatorImg3.GetHeight()); - PageIndicatorBtn3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - PageIndicatorBtn3.SetPosition(235, 400); - PageIndicatorBtn3.SetImage(&PageindicatorImg3); - PageIndicatorBtn3.SetLabel(&PageindicatorTxt3); - PageIndicatorBtn3.SetSoundOver(&btnSoundOver); - PageIndicatorBtn3.SetSoundClick(&btnClick1); - PageIndicatorBtn3.SetTrigger(&trigA); - PageIndicatorBtn3.SetEffectGrow(); + GuiImage GoLeftImg(&arrow_left); + GuiButton GoLeftBtn(GoLeftImg.GetWidth(), GoLeftImg.GetHeight()); + GoLeftBtn.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + GoLeftBtn.SetPosition(25, -25); + GoLeftBtn.SetImage(&GoLeftImg); + GoLeftBtn.SetSoundOver(&btnSoundOver); + GoLeftBtn.SetSoundClick(btnClick2); + GoLeftBtn.SetEffectGrow(); + GoLeftBtn.SetTrigger(&trigA); + GoLeftBtn.SetTrigger(&trigL); + GoLeftBtn.SetTrigger(&trigMinus); - GuiImage GoLeftImg(&arrow_left); - GuiButton GoLeftBtn(GoLeftImg.GetWidth(), GoLeftImg.GetHeight()); - GoLeftBtn.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - GoLeftBtn.SetPosition(25, -25); - GoLeftBtn.SetImage(&GoLeftImg); - GoLeftBtn.SetSoundOver(&btnSoundOver); - GoLeftBtn.SetSoundClick(btnClick2); - GoLeftBtn.SetEffectGrow(); - GoLeftBtn.SetTrigger(&trigA); - GoLeftBtn.SetTrigger(&trigL); - GoLeftBtn.SetTrigger(&trigMinus); + GuiImage GoRightImg(&arrow_right); + GuiButton GoRightBtn(GoRightImg.GetWidth(), GoRightImg.GetHeight()); + GoRightBtn.SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); + GoRightBtn.SetPosition(-25, -25); + GoRightBtn.SetImage(&GoRightImg); + GoRightBtn.SetSoundOver(&btnSoundOver); + GoRightBtn.SetSoundClick(btnClick2); + GoRightBtn.SetEffectGrow(); + GoRightBtn.SetTrigger(&trigA); + GoRightBtn.SetTrigger(&trigR); + GoRightBtn.SetTrigger(&trigPlus); - GuiImage GoRightImg(&arrow_right); - GuiButton GoRightBtn(GoRightImg.GetWidth(), GoRightImg.GetHeight()); - GoRightBtn.SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); - GoRightBtn.SetPosition(-25, -25); - GoRightBtn.SetImage(&GoRightImg); - GoRightBtn.SetSoundOver(&btnSoundOver); - GoRightBtn.SetSoundClick(btnClick2); - GoRightBtn.SetEffectGrow(); - GoRightBtn.SetTrigger(&trigA); - GoRightBtn.SetTrigger(&trigR); - GoRightBtn.SetTrigger(&trigPlus); + char MainButtonText[50]; + snprintf(MainButtonText, sizeof(MainButtonText), "%s", " "); - char MainButtonText[50]; - snprintf(MainButtonText, sizeof(MainButtonText), "%s", " "); + GuiImage MainButton1Img(&MainButtonImgData); + GuiImage MainButton1ImgOver(&MainButtonImgOverData); + GuiText MainButton1Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); + MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth()); + GuiButton MainButton1(MainButton1Img.GetWidth(), MainButton1Img.GetHeight()); + MainButton1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton1.SetPosition(0, 90); + MainButton1.SetImage(&MainButton1Img); + MainButton1.SetImageOver(&MainButton1ImgOver); + MainButton1.SetLabel(&MainButton1Txt); + MainButton1.SetSoundOver(&btnSoundOver); + MainButton1.SetSoundClick(&btnClick1); + MainButton1.SetEffectGrow(); + MainButton1.SetTrigger(&trigA); - GuiImage MainButton1Img(&MainButtonImgData); - GuiImage MainButton1ImgOver(&MainButtonImgOverData); - GuiText MainButton1Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth()); - GuiButton MainButton1(MainButton1Img.GetWidth(), MainButton1Img.GetHeight()); - MainButton1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton1.SetPosition(0, 90); - MainButton1.SetImage(&MainButton1Img); - MainButton1.SetImageOver(&MainButton1ImgOver); - MainButton1.SetLabel(&MainButton1Txt); - MainButton1.SetSoundOver(&btnSoundOver); - MainButton1.SetSoundClick(&btnClick1); - MainButton1.SetEffectGrow(); - MainButton1.SetTrigger(&trigA); + GuiImage MainButton2Img(&MainButtonImgData); + GuiImage MainButton2ImgOver(&MainButtonImgOverData); + GuiText MainButton2Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255 }); + MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()); + GuiButton MainButton2(MainButton2Img.GetWidth(), MainButton2Img.GetHeight()); + MainButton2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton2.SetPosition(0, 160); + MainButton2.SetImage(&MainButton2Img); + MainButton2.SetImageOver(&MainButton2ImgOver); + MainButton2.SetLabel(&MainButton2Txt); + MainButton2.SetSoundOver(&btnSoundOver); + MainButton2.SetSoundClick(&btnClick1); + MainButton2.SetEffectGrow(); + MainButton2.SetTrigger(&trigA); - GuiImage MainButton2Img(&MainButtonImgData); - GuiImage MainButton2ImgOver(&MainButtonImgOverData); - GuiText MainButton2Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()); - GuiButton MainButton2(MainButton2Img.GetWidth(), MainButton2Img.GetHeight()); - MainButton2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton2.SetPosition(0, 160); - MainButton2.SetImage(&MainButton2Img); - MainButton2.SetImageOver(&MainButton2ImgOver); - MainButton2.SetLabel(&MainButton2Txt); - MainButton2.SetSoundOver(&btnSoundOver); - MainButton2.SetSoundClick(&btnClick1); - MainButton2.SetEffectGrow(); - MainButton2.SetTrigger(&trigA); + GuiImage MainButton3Img(&MainButtonImgData); + GuiImage MainButton3ImgOver(&MainButtonImgOverData); + GuiText MainButton3Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); + MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()); + GuiButton MainButton3(MainButton3Img.GetWidth(), MainButton3Img.GetHeight()); + MainButton3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton3.SetPosition(0, 230); + MainButton3.SetImage(&MainButton3Img); + MainButton3.SetImageOver(&MainButton3ImgOver); + MainButton3.SetLabel(&MainButton3Txt); + MainButton3.SetSoundOver(&btnSoundOver); + MainButton3.SetSoundClick(&btnClick1); + MainButton3.SetEffectGrow(); + MainButton3.SetTrigger(&trigA); - GuiImage MainButton3Img(&MainButtonImgData); - GuiImage MainButton3ImgOver(&MainButtonImgOverData); - GuiText MainButton3Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()); - GuiButton MainButton3(MainButton3Img.GetWidth(), MainButton3Img.GetHeight()); - MainButton3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton3.SetPosition(0, 230); - MainButton3.SetImage(&MainButton3Img); - MainButton3.SetImageOver(&MainButton3ImgOver); - MainButton3.SetLabel(&MainButton3Txt); - MainButton3.SetSoundOver(&btnSoundOver); - MainButton3.SetSoundClick(&btnClick1); - MainButton3.SetEffectGrow(); - MainButton3.SetTrigger(&trigA); + GuiImage MainButton4Img(&MainButtonImgData); + GuiImage MainButton4ImgOver(&MainButtonImgOverData); + GuiText MainButton4Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); + MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()); + GuiButton MainButton4(MainButton4Img.GetWidth(), MainButton4Img.GetHeight()); + MainButton4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton4.SetPosition(0, 300); + MainButton4.SetImage(&MainButton4Img); + MainButton4.SetImageOver(&MainButton4ImgOver); + MainButton4.SetLabel(&MainButton4Txt); + MainButton4.SetSoundOver(&btnSoundOver); + MainButton4.SetSoundClick(&btnClick1); + MainButton4.SetEffectGrow(); + MainButton4.SetTrigger(&trigA); - GuiImage MainButton4Img(&MainButtonImgData); - GuiImage MainButton4ImgOver(&MainButtonImgOverData); - GuiText MainButton4Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()); - GuiButton MainButton4(MainButton4Img.GetWidth(), MainButton4Img.GetHeight()); - MainButton4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton4.SetPosition(0, 300); - MainButton4.SetImage(&MainButton4Img); - MainButton4.SetImageOver(&MainButton4ImgOver); - MainButton4.SetLabel(&MainButton4Txt); - MainButton4.SetSoundOver(&btnSoundOver); - MainButton4.SetSoundClick(&btnClick1); - MainButton4.SetEffectGrow(); - MainButton4.SetTrigger(&trigA); + customOptionList options2(MAXOPTIONS); + GuiCustomOptionBrowser optionBrowser2(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150); + optionBrowser2.SetPosition(0, 90); + optionBrowser2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - customOptionList options2(MAXOPTIONS); - GuiCustomOptionBrowser optionBrowser2(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150); - optionBrowser2.SetPosition(0, 90); - optionBrowser2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + GuiWindow w(screenwidth, screenheight); - GuiWindow w(screenwidth, screenheight); + int pageToDisplay = 1; + while ( pageToDisplay > 0) { //set pageToDisplay to 0 to quit + VIDEO_WaitVSync (); - int pageToDisplay = 1; - while ( pageToDisplay > 0) { //set pageToDisplay to 0 to quit - VIDEO_WaitVSync (); + menu = MENU_NONE; - menu = MENU_NONE; + if ( pageToDisplay == 1) + { + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - if ( pageToDisplay == 1) { - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + if (slidedirection == RIGHT) + { + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + while (MainButton1.GetEffect()>0) usleep(50); + } + else if (slidedirection == LEFT) + { + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + while (MainButton1.GetEffect()>0) usleep(50); + } - if (slidedirection == RIGHT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } else if (slidedirection == LEFT) { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } + HaltGui(); - HaltGui(); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("GUI Settings")); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Game Load")); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Parental Control")); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Sound")); + MainButton4Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("GUI Settings")); - MainButton1Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Game Load")); - MainButton2Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Parental Control")); - MainButton3Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Sound")); - MainButton4Txt.SetText(MainButtonText); + mainWindow->RemoveAll(); + mainWindow->Append(&w); + w.RemoveAll(); + w.Append(&settingsbackground); + w.Append(&PageIndicatorBtn1); + w.Append(&PageIndicatorBtn2); + w.Append(&PageIndicatorBtn3); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&homo); + w.Append(&GoRightBtn); + w.Append(&GoLeftBtn); + w.Append(&MainButton1); + w.Append(&MainButton2); + w.Append(&MainButton3); + w.Append(&MainButton4); - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&PageIndicatorBtn1); - w.Append(&PageIndicatorBtn2); - w.Append(&PageIndicatorBtn3); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&GoRightBtn); - w.Append(&GoLeftBtn); - w.Append(&MainButton1); - w.Append(&MainButton2); - w.Append(&MainButton3); - w.Append(&MainButton4); + PageIndicatorBtn1.SetAlpha(255); + PageIndicatorBtn2.SetAlpha(50); + PageIndicatorBtn3.SetAlpha(50); - PageIndicatorBtn1.SetAlpha(255); - PageIndicatorBtn2.SetAlpha(50); - PageIndicatorBtn3.SetAlpha(50); + /** Creditsbutton change **/ + MainButton4.SetImage(&MainButton4Img); + MainButton4.SetImageOver(&MainButton4ImgOver); - /** Creditsbutton change **/ - MainButton4.SetImage(&MainButton4Img); - MainButton4.SetImageOver(&MainButton4ImgOver); - - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable(false); + /** Default no scrollbar and reset position **/ // optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); + optionBrowser2.SetOffset(0); - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); - if (slidedirection == FADE) { - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - } else if (slidedirection == LEFT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - } else if (slidedirection == RIGHT) { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - } + if (slidedirection == FADE) + { + MainButton1.SetEffect(EFFECT_FADE, 20); + MainButton2.SetEffect(EFFECT_FADE, 20); + MainButton3.SetEffect(EFFECT_FADE, 20); + MainButton4.SetEffect(EFFECT_FADE, 20); + } + else if (slidedirection == LEFT) + { + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + } + else if (slidedirection == RIGHT) + { + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + } - mainWindow->Append(&w); + mainWindow->Append(&w); - ResumeGui(); + ResumeGui(); - while (MainButton1.GetEffect() > 0) usleep(50); + while (MainButton1.GetEffect() > 0) usleep(50); - } else if ( pageToDisplay == 2 ) { - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + } + else if ( pageToDisplay == 2 ) + { + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - if (slidedirection == RIGHT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } else if (slidedirection == LEFT) { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } + if (slidedirection == RIGHT) + { + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + while (MainButton1.GetEffect()>0) usleep(50); + } + else if (slidedirection == LEFT) + { + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + while (MainButton1.GetEffect()>0) usleep(50); + } - HaltGui(); + HaltGui(); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Custom Paths")); - MainButton1Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Update")); - MainButton2Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Default Settings")); - MainButton3Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Credits")); - MainButton4Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Custom Paths")); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Update")); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Default Settings")); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Credits")); + MainButton4Txt.SetText(MainButtonText); - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&PageIndicatorBtn1); - w.Append(&PageIndicatorBtn2); - w.Append(&PageIndicatorBtn3); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&GoRightBtn); - w.Append(&GoLeftBtn); - w.Append(&MainButton1); - w.Append(&MainButton2); - w.Append(&MainButton3); - w.Append(&MainButton4); + mainWindow->RemoveAll(); + mainWindow->Append(&w); + w.RemoveAll(); + w.Append(&settingsbackground); + w.Append(&PageIndicatorBtn1); + w.Append(&PageIndicatorBtn2); + w.Append(&PageIndicatorBtn3); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&homo); + w.Append(&GoRightBtn); + w.Append(&GoLeftBtn); + w.Append(&MainButton1); + w.Append(&MainButton2); + w.Append(&MainButton3); + w.Append(&MainButton4); - PageIndicatorBtn1.SetAlpha(50); - PageIndicatorBtn2.SetAlpha(255); - PageIndicatorBtn3.SetAlpha(50); + PageIndicatorBtn1.SetAlpha(50); + PageIndicatorBtn2.SetAlpha(255); + PageIndicatorBtn3.SetAlpha(50); - /** Creditsbutton change **/ - MainButton4.SetImage(&creditsImg); - MainButton4.SetImageOver(&creditsImgOver); + /** Creditsbutton change **/ + MainButton4.SetImage(&creditsImg); + MainButton4.SetImageOver(&creditsImgOver); - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable(false); + /** Default no scrollbar and reset position **/ // optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); + optionBrowser2.SetOffset(0); - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); - if (slidedirection == FADE) { - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - } else if (slidedirection == LEFT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - } else if (slidedirection == RIGHT) { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - } + if (slidedirection == FADE) + { + MainButton1.SetEffect(EFFECT_FADE, 20); + MainButton2.SetEffect(EFFECT_FADE, 20); + MainButton3.SetEffect(EFFECT_FADE, 20); + MainButton4.SetEffect(EFFECT_FADE, 20); + } + else if (slidedirection == LEFT) + { + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + } + else if (slidedirection == RIGHT) + { + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + } - mainWindow->Append(&w); + mainWindow->Append(&w); - ResumeGui(); + ResumeGui(); - while (MainButton1.GetEffect() > 0) usleep(50); + while (MainButton1.GetEffect() > 0) usleep(50); - } else if ( pageToDisplay == 3 ) { - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + } + else if ( pageToDisplay == 3 ) + { + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - if (slidedirection == RIGHT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } else if (slidedirection == LEFT) { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } + if (slidedirection == RIGHT) + { + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); + while (MainButton1.GetEffect()>0) usleep(50); + } + else if (slidedirection == LEFT) + { + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); + while (MainButton1.GetEffect()>0) usleep(50); + } - HaltGui(); + HaltGui(); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Theme Downloader")); - MainButton1Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr(" ")); - MainButton2Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr(" ")); - MainButton3Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr(" ")); - MainButton4Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Theme Downloader")); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr(" ")); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr(" ")); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr(" ")); + MainButton4Txt.SetText(MainButtonText); - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&PageIndicatorBtn1); - w.Append(&PageIndicatorBtn2); - w.Append(&PageIndicatorBtn3); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&GoRightBtn); - w.Append(&GoLeftBtn); - w.Append(&MainButton1); + mainWindow->RemoveAll(); + mainWindow->Append(&w); + w.RemoveAll(); + w.Append(&settingsbackground); + w.Append(&PageIndicatorBtn1); + w.Append(&PageIndicatorBtn2); + w.Append(&PageIndicatorBtn3); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&homo); + w.Append(&GoRightBtn); + w.Append(&GoLeftBtn); + w.Append(&MainButton1); - PageIndicatorBtn1.SetAlpha(50); - PageIndicatorBtn2.SetAlpha(50); - PageIndicatorBtn3.SetAlpha(255); + PageIndicatorBtn1.SetAlpha(50); + PageIndicatorBtn2.SetAlpha(50); + PageIndicatorBtn3.SetAlpha(255); - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable(false); + /** Default no scrollbar and reset position **/ // optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); + optionBrowser2.SetOffset(0); - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); - if (slidedirection == FADE) { - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - } else if (slidedirection == LEFT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - } else if (slidedirection == RIGHT) { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - } + if (slidedirection == FADE) + { + MainButton1.SetEffect(EFFECT_FADE, 20); + MainButton2.SetEffect(EFFECT_FADE, 20); + MainButton3.SetEffect(EFFECT_FADE, 20); + MainButton4.SetEffect(EFFECT_FADE, 20); + } + else if (slidedirection == LEFT) + { + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); + } + else if (slidedirection == RIGHT) + { + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); + } - mainWindow->Append(&w); + mainWindow->Append(&w); - ResumeGui(); + ResumeGui(); - while (MainButton1.GetEffect() > 0) usleep(50); - } + while (MainButton1.GetEffect() > 0) usleep(50); + } - while (menu == MENU_NONE) { - VIDEO_WaitVSync (); + while (menu == MENU_NONE) + { + VIDEO_WaitVSync (); - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); - if ( pageToDisplay == 1 ) { - if (MainButton1.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton1.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("GUI Settings")); - exit = false; - options2.SetLength(0); + if ( pageToDisplay == 1 ) + { + if (MainButton1.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton1.GetEffect() > 0) usleep(50); + HaltGui(); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + titleTxt.SetText(tr("GUI Settings")); + exit = false; + options2.SetLength(0); // optionBrowser2.SetScrollbar(1); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - VIDEO_WaitVSync (); - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - int returnhere = 1; - char * languagefile; - languagefile = strrchr(Settings.language_path, '/')+1; - - bool firstRun = true; - while (!exit) { - VIDEO_WaitVSync (); - - returnhere = 1; - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - else if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } - - else if (menu == MENU_DISCLIST) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - WindowCredits(); - w.Append(&optionBrowser2); - w.Append(&backBtn); - } - - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if (firstRun || ret >= 0) { - int Idx = -1; - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("App Language")); - if (ret == Idx) { - if (isInserted(bootDevice)) { - if ( Settings.godmode == 1) { - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); - mainWindow->Remove(&w); - while (returnhere == 1) - returnhere = MenuLanguageSelect(); - if (returnhere == 2) { - menu = MENU_SETTINGS; - pageToDisplay = 0; - exit = true; - mainWindow->Append(&w); - break; - } else { - HaltGui(); - mainWindow->Append(&w); - w.SetEffect(EFFECT_FADE, 20); - ResumeGui(); - while (w.GetEffect()>0) usleep(50); - } - } else { - WindowPrompt(tr("Language change:"),tr("Console should be unlocked to modify it."),tr("OK")); - } - } else { - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to use this option."),tr("OK")); - } - } - - if (!strcmp("notset", Settings.language_path)) - options2.SetValue(Idx, "%s", tr("Default")); - else - options2.SetValue(Idx, "%s", languagefile); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Display")); - if (ret == Idx && ++Settings.sinfo >= settings_sinfo_max) - Settings.sinfo = 0; - static const char *opts[settings_sinfo_max] = {trNOOP("Game ID"),trNOOP("Game Region"),trNOOP("Both"),trNOOP("Neither")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.sinfo])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Clock")); - if (ret == Idx && ++Settings.hddinfo >= settings_clock_max) - Settings.hddinfo = 0; //CLOCK - if (Settings.hddinfo == hr12) options2.SetValue(Idx,"12 %s",tr("Hour")); - else if (Settings.hddinfo == hr24) options2.SetValue(Idx,"24 %s",tr("Hour")); - else if (Settings.hddinfo == Off) options2.SetValue(Idx,"%s",tr("OFF")); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Tooltips")); - if (ret == Idx && ++Settings.tooltips >= settings_tooltips_max) - Settings.tooltips = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.tooltips])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Flip-X")); - if (ret == Idx && ++Settings.xflip >= settings_xflip_max) - Settings.xflip = 0; - static const char *opts[settings_xflip_max][3] = { {trNOOP("Right"),"/",trNOOP("Next")}, - {trNOOP("Left"),"/",trNOOP("Prev")}, - {trNOOP("Like SysMenu"),"",""}, - {trNOOP("Right"),"/",trNOOP("Prev")}, - {trNOOP("DiskFlip"),"",""} - }; - options2.SetValue(Idx,"%s%s%s",tr(opts[Settings.xflip][0]),opts[Settings.xflip][1],tr(opts[Settings.xflip][2])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Prompts Buttons")); - if (ret == Idx && ++Settings.wsprompt >= settings_off_on_max ) - Settings.wsprompt = 0; - static const char *opts[settings_off_on_max] = {trNOOP("Normal"),trNOOP("Widescreen Fix")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.wsprompt])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Keyboard")); - if (ret == Idx && ++Settings.keyset >= settings_keyset_max) - Settings.keyset = 0; - static const char *opts[settings_keyset_max] = {"QWERTY","QWERTY 2","DVORAK","QWERTZ","AZERTY"}; - options2.SetValue(Idx,"%s", opts[Settings.keyset]); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Disc Artwork Download")); - if (ret == Idx && ++Settings.discart >= 4) - Settings.discart = 0; - static const char *opts[4] = {trNOOP("Only Original"),trNOOP("Only Customs"),trNOOP("Original/Customs"),trNOOP("Customs/Original")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.discart])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Wiilight")); - if (ret == Idx && ++Settings.wiilight >= settings_wiilight_max ) - Settings.wiilight = 0; - static const char *opts[settings_wiilight_max] = {trNOOP("OFF"),trNOOP("ON"),trNOOP("Only for Install")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.wiilight])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Rumble")); - if (ret == Idx && ++Settings.rumble >= settings_rumble_max) - Settings.rumble = 0; //RUMBLE - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.rumble])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("AutoInit Network")); - if (ret == Idx && ++Settings.autonetwork >= settings_off_on_max) - Settings.autonetwork = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.autonetwork])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("BETA revisions")); - if (ret == Idx && ++Settings.beta_upgrades >= settings_off_on_max) - Settings.beta_upgrades = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.beta_upgrades])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Titles from WiiTDB")); - if (ret == Idx && ++Settings.titlesOverride >= settings_off_on_max) - Settings.titlesOverride = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.titlesOverride])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Screensaver")); - if (ret == Idx && ++Settings.screensaver >= settings_screensaver_max) - Settings.screensaver = 0; //RUMBLE - static const char *opts[settings_screensaver_max] = {trNOOP("OFF"),trNOOP("3 min"),trNOOP("5 min"),trNOOP("10 min"),trNOOP("20 min"),trNOOP("30 min"),trNOOP("1 hour")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.screensaver])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Mark new games")); - if (ret == Idx && ++Settings.marknewtitles >= settings_off_on_max) - Settings.marknewtitles = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.marknewtitles])); - } - - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - if (returnhere != 2) - pageToDisplay = 1; - MainButton1.ResetState(); - break; - } - - else if (MainButton2.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton2.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Game Load")); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - VIDEO_WaitVSync (); - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - bool firstRun = true; - while (!exit) { - VIDEO_WaitVSync (); - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - else if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } - - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if (firstRun || ret >= 0) { - int Idx = -1; - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Video Mode")); - if (ret == Idx && ++Settings.video >= settings_video_max) - Settings.video = 0; - options2.SetValue(Idx,"%s%s",opts_videomode[Settings.video][0], tr(opts_videomode[Settings.video][1])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("VIDTV Patch")); - if (ret == Idx && ++Settings.vpatch >= settings_off_on_max) - Settings.vpatch = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.vpatch])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Game Language")); - if (ret == Idx && ++Settings.language >= settings_language_max) - Settings.language = 0; - options2.SetValue(Idx,"%s",tr(opts_language[Settings.language])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Patch Country Strings")); - if (ret == Idx && ++Settings.patchcountrystrings >= settings_off_on_max) - Settings.patchcountrystrings = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.patchcountrystrings])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "Ocarina"); - if (ret == Idx && ++Settings.ocarina >= settings_off_on_max) - Settings.ocarina = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.ocarina])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx,"%s", tr("Boot/Standard")); - if (ret == Idx && Settings.godmode == 1) { - if (++Settings.cios >= settings_cios_max) { - Settings.cios = 0; - } - if ((Settings.cios == 1 && ios222rev!=4) || (Settings.cios == 2 && ios223rev != 4)) { - WindowPrompt(tr("Hermes CIOS"),tr("USB Loader GX will only run with Hermes CIOS rev 4! Please make sure you have revision 4 installed!"),tr("OK")); - } - } - if (Settings.godmode == 1) - options2.SetValue(Idx, "%s", opts_cios[Settings.cios]); - else - options2.SetValue(Idx, "********"); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Partition")); - if (ret == Idx) { - // Select the next valid partition, even if that's the same one - do { - Settings.partition = Settings.partition + 1 == partitions.num ? 0 : Settings.partition + 1; - } while (!IsValidPartition(partitions.pinfo[Settings.partition].fs_type, Settings.cios)); - } - - PartInfo pInfo = partitions.pinfo[Settings.partition]; - f32 partition_size = partitions.pentry[Settings.partition].size * (partitions.sector_size / GB_SIZE); - - // Get the partition name and it's size in GB's - options2.SetValue(Idx,"%s%d (%.2fGB)", pInfo.fs_type == FS_TYPE_FAT32 ? "FAT" : pInfo.fs_type == FS_TYPE_NTFS ? "NTFS" : "WBFS", - pInfo.index, - partition_size); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("FAT: Use directories")); - if (ret == Idx && ++Settings.FatInstallToDir >= settings_installdir_max) - Settings.FatInstallToDir = 0; - options2.SetValue(Idx, "%s", tr(opts_installdir[Settings.FatInstallToDir])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Quick Boot")); - if (ret == Idx && ++Settings.qboot >= settings_off_on_max) - Settings.qboot = 0; - options2.SetValue(Idx,"%s",tr(opts_no_yes[Settings.qboot])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Error 002 fix")); - if (ret == Idx && ++Settings.error002 >= settings_error002_max) - Settings.error002 = 0; - options2.SetValue(Idx,"%s",tr(opts_error002[Settings.error002])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Install partitions")); - if (ret == Idx && ++Settings.partitions_to_install >= settings_partitions_max) - Settings.partitions_to_install = 0; - options2.SetValue(Idx,"%s",tr(opts_partitions[Settings.partitions_to_install])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Install 1:1 Copy")); - if (ret == Idx) { - Settings.fullcopy = Settings.fullcopy == 0 ? 1 : 0; - } - options2.SetValue(Idx,"%s",tr(opts_no_yes[Settings.fullcopy])); - } - - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - pageToDisplay = 1; - MainButton2.ResetState(); - break; - } - - else if (MainButton3.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton3.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Parental Control")); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - VIDEO_WaitVSync (); - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - bool firstRun = true; - while (!exit) { - VIDEO_WaitVSync (); - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - else if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } - - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if (firstRun || ret >= 0) { - - int Idx = -1; - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Console")); - if (ret == Idx) { - if (!strcmp("", Settings.unlockCode) && Settings.parental.enabled == 0) { - Settings.godmode = !Settings.godmode; - } else if ( Settings.godmode == 0 ) { - char entered[20]; - memset(entered, 0, 20); - - //password check to unlock Install,Delete and Format - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - int result = Settings.parental.enabled == 0 ? OnScreenKeyboard(entered, 20,0) : OnScreenNumpad(entered, 5); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - if (!strcmp(entered, Settings.unlockCode) || !memcmp(entered, Settings.parental.pin, 4)) { //if password correct - if (Settings.godmode == 0) { - WindowPrompt(tr("Correct Password"),tr("All the features of USB Loader GX are unlocked."),tr("OK")); - Settings.godmode = 1; - menu = MENU_DISCLIST; - } - } else - WindowPrompt(tr("Wrong Password"),tr("USB Loader GX is protected"),tr("OK")); - } - } else { - int choice = WindowPrompt (tr("Lock Console"),tr("Are you sure?"),tr("Yes"),tr("No")); - if (choice == 1) { - WindowPrompt(tr("Console Locked"),tr("USB Loader GX is protected"),tr("OK")); - Settings.godmode = 0; - menu = MENU_DISCLIST; - } - } - } - static const char *opts[] = {trNOOP("Locked"),trNOOP("Unlocked")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.godmode])); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Password")); - if (ret == Idx) { - if ( Settings.godmode == 1) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[20] = ""; - strlcpy(entered, Settings.unlockCode, sizeof(entered)); - int result = OnScreenKeyboard(entered, 20,0); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - strlcpy(Settings.unlockCode, entered, sizeof(Settings.unlockCode)); - WindowPrompt(tr("Password Changed"),tr("Password has been changed"),tr("OK")); - } - } else { - WindowPrompt(tr("Password Changed"),tr("Console should be unlocked to modify it."),tr("OK")); - } - } - if ( Settings.godmode != 1) options2.SetValue(Idx, "********"); - else if (!strcmp("", Settings.unlockCode)) options2.SetValue(Idx, "%s",tr("not set")); - else options2.SetValue(Idx, Settings.unlockCode); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Controllevel")); - if (ret == Idx && Settings.godmode == 1 && ++Settings.parentalcontrol >= 5 ) - Settings.parentalcontrol = 0; - if (Settings.godmode == 1) - options2.SetValue(Idx,"%s",tr(opts_parentalcontrol[Settings.parentalcontrol])); - else - options2.SetValue(Idx, "********"); - } - - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - pageToDisplay = 1; - MainButton3.ResetState(); - break; - } - - else if (MainButton4.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton4.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Sound")); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - VIDEO_WaitVSync (); - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - - char * oggfile; - - bool firstRun = true; - while (!exit) { - VIDEO_WaitVSync (); - - bool returnhere = true; - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - else if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } - - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if (firstRun || ret >= 0) { - int Idx = -1; - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Backgroundmusic")); - if (ret == Idx) { - if (isInserted(bootDevice)) { - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); - mainWindow->Remove(&w); - while (returnhere) - returnhere = MenuOGG(); - HaltGui(); - mainWindow->Append(&w); - w.SetEffect(EFFECT_FADE, 20); - ResumeGui(); - while (w.GetEffect()>0) usleep(50); - } else - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to use this option."),tr("OK")); - } - if (!strcmp("notset", Settings.ogg_path)) - options2.SetValue(Idx, "%s", tr("Standard")); - else { - oggfile = strrchr(Settings.ogg_path, '/')+1; - options2.SetValue(Idx, "%s", oggfile); - } - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Music Volume")); - if (ret == Idx) { - Settings.volume += 10; - if (Settings.volume > 100) - Settings.volume = 0; - bgMusic->SetVolume(Settings.volume); - } - if (Settings.volume > 0) - options2.SetValue(Idx,"%i", Settings.volume); - else - options2.SetValue(Idx,"%s", tr("OFF")); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("SFX Volume")); - if (ret == Idx) { - Settings.sfxvolume += 10; - if (Settings.sfxvolume > 100) - Settings.sfxvolume = 0; - btnSoundOver.SetVolume(Settings.sfxvolume); - btnClick2->SetVolume(Settings.sfxvolume); - btnClick1.SetVolume(Settings.sfxvolume); - } - if (Settings.sfxvolume > 0) - options2.SetValue(Idx,"%i", Settings.sfxvolume); - else - options2.SetValue(Idx,"%s", tr("OFF")); - } - - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Game Sound Mode")); - if (ret == Idx) { - Settings.gamesound++; - if (Settings.gamesound > 2) - Settings.gamesound = 0; - } - - if (Settings.gamesound == 1) + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); + ResumeGui(); + + VIDEO_WaitVSync (); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + + int returnhere = 1; + char * languagefile; + languagefile = strrchr(Settings.language_path, '/')+1; + + bool firstRun = true; + while (!exit) + { + VIDEO_WaitVSync (); + + returnhere = 1; + + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); + + else if (backBtn.GetState() == STATE_CLICKED) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if (menu == MENU_DISCLIST) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + WindowCredits(); + w.Append(&optionBrowser2); + w.Append(&backBtn); + } + + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } + + ret = optionBrowser2.GetClickedOption(); + + if(firstRun || ret >= 0) + { + int Idx = -1; + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("App Language")); + if(ret == Idx) + { + if (isInserted(bootDevice)) + { + if ( Settings.godmode == 1) + { + w.SetEffect(EFFECT_FADE, -20); + while (w.GetEffect()>0) usleep(50); + mainWindow->Remove(&w); + while (returnhere == 1) + returnhere = MenuLanguageSelect(); + if (returnhere == 2) + { + menu = MENU_SETTINGS; + pageToDisplay = 0; + exit = true; + mainWindow->Append(&w); + break; + } + else + { + HaltGui(); + mainWindow->Append(&w); + w.SetEffect(EFFECT_FADE, 20); + ResumeGui(); + while (w.GetEffect()>0) usleep(50); + } + } + else + { + WindowPrompt(tr("Language change:"),tr("Console should be unlocked to modify it."),tr("OK")); + } + } + else + { + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to use this option."),tr("OK")); + } + } + + if (!strcmp("notset", Settings.language_path)) + options2.SetValue(Idx, "%s", tr("Default")); + else + options2.SetValue(Idx, "%s", languagefile); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Display")); + if(ret == Idx && ++Settings.sinfo >= settings_sinfo_max) + Settings.sinfo = 0; + static const char *opts[settings_sinfo_max] = {trNOOP("Game ID"),trNOOP("Game Region"),trNOOP("Both"),trNOOP("Neither")}; + options2.SetValue(Idx,"%s",tr(opts[Settings.sinfo])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Clock")); + if(ret == Idx && ++Settings.hddinfo >= settings_clock_max) + Settings.hddinfo = 0; //CLOCK + if (Settings.hddinfo == hr12) options2.SetValue(Idx,"12 %s",tr("Hour")); + else if (Settings.hddinfo == hr24) options2.SetValue(Idx,"24 %s",tr("Hour")); + else if (Settings.hddinfo == Off) options2.SetValue(Idx,"%s",tr("OFF")); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Tooltips")); + if(ret == Idx && ++Settings.tooltips >= settings_tooltips_max) + Settings.tooltips = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.tooltips])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Flip-X")); + if(ret == Idx && ++Settings.xflip >= settings_xflip_max) + Settings.xflip = 0; + static const char *opts[settings_xflip_max][3] = { {trNOOP("Right"),"/",trNOOP("Next")}, + {trNOOP("Left"),"/",trNOOP("Prev")}, + {trNOOP("Like SysMenu"),"",""}, + {trNOOP("Right"),"/",trNOOP("Prev")}, + {trNOOP("DiskFlip"),"",""}}; + options2.SetValue(Idx,"%s%s%s",tr(opts[Settings.xflip][0]),opts[Settings.xflip][1],tr(opts[Settings.xflip][2])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Prompts Buttons")); + if(ret == Idx && ++Settings.wsprompt >= settings_off_on_max ) + Settings.wsprompt = 0; + static const char *opts[settings_off_on_max] = {trNOOP("Normal"),trNOOP("Widescreen Fix")}; + options2.SetValue(Idx,"%s",tr(opts[Settings.wsprompt])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Keyboard")); + if(ret == Idx && ++Settings.keyset >= settings_keyset_max) + Settings.keyset = 0; + static const char *opts[settings_keyset_max] = {"QWERTY","QWERTY 2","DVORAK","QWERTZ","AZERTY"}; + options2.SetValue(Idx,"%s", opts[Settings.keyset]); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Disc Artwork Download")); + if(ret == Idx && ++Settings.discart >= 4) + Settings.discart = 0; + static const char *opts[4] = {trNOOP("Only Original"),trNOOP("Only Customs"),trNOOP("Original/Customs"),trNOOP("Customs/Original")}; + options2.SetValue(Idx,"%s",tr(opts[Settings.discart])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Wiilight")); + if(ret == Idx && ++Settings.wiilight >= settings_wiilight_max ) + Settings.wiilight = 0; + static const char *opts[settings_wiilight_max] = {trNOOP("OFF"),trNOOP("ON"),trNOOP("Only for Install")}; + options2.SetValue(Idx,"%s",tr(opts[Settings.wiilight])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Rumble")); + if(ret == Idx && ++Settings.rumble >= settings_rumble_max) + Settings.rumble = 0; //RUMBLE + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.rumble])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("AutoInit Network")); + if(ret == Idx && ++Settings.autonetwork >= settings_off_on_max) + Settings.autonetwork = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.autonetwork])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("BETA revisions")); + if(ret == Idx && ++Settings.beta_upgrades >= settings_off_on_max) + Settings.beta_upgrades = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.beta_upgrades])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Titles from WiiTDB")); + if(ret == Idx && ++Settings.titlesOverride >= settings_off_on_max) + Settings.titlesOverride = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.titlesOverride])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Screensaver")); + if(ret == Idx && ++Settings.screensaver >= settings_screensaver_max) + Settings.screensaver = 0; //RUMBLE + static const char *opts[settings_screensaver_max] = {trNOOP("OFF"),trNOOP("3 min"),trNOOP("5 min"),trNOOP("10 min"),trNOOP("20 min"),trNOOP("30 min"),trNOOP("1 hour")}; + options2.SetValue(Idx,"%s",tr(opts[Settings.screensaver])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Mark new games")); + if(ret == Idx && ++Settings.marknewtitles >= settings_off_on_max) + Settings.marknewtitles = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.marknewtitles])); + } + + firstRun = false; + } + } + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + titleTxt.SetText(tr("Settings")); + slidedirection = FADE; + if (returnhere != 2) + pageToDisplay = 1; + MainButton1.ResetState(); + break; + } + + else if (MainButton2.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton2.GetEffect() > 0) usleep(50); + HaltGui(); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + titleTxt.SetText(tr("Game Load")); + exit = false; + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); + ResumeGui(); + + VIDEO_WaitVSync (); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + + bool firstRun = true; + while (!exit) + { + VIDEO_WaitVSync (); + + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); + + else if (backBtn.GetState() == STATE_CLICKED) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } + + ret = optionBrowser2.GetClickedOption(); + + if(firstRun || ret >= 0) + { + int Idx = -1; + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Video Mode")); + if(ret == Idx && ++Settings.video >= settings_video_max) + Settings.video = 0; + options2.SetValue(Idx,"%s%s",opts_videomode[Settings.video][0], tr(opts_videomode[Settings.video][1])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("VIDTV Patch")); + if(ret == Idx && ++Settings.vpatch >= settings_off_on_max) + Settings.vpatch = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.vpatch])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Game Language")); + if(ret == Idx && ++Settings.language >= settings_language_max) + Settings.language = 0; + options2.SetValue(Idx,"%s",tr(opts_language[Settings.language])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Patch Country Strings")); + if(ret == Idx && ++Settings.patchcountrystrings >= settings_off_on_max) + Settings.patchcountrystrings = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.patchcountrystrings])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "Ocarina"); + if(ret == Idx && ++Settings.ocarina >= settings_off_on_max) + Settings.ocarina = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.ocarina])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx,"%s", tr("Boot/Standard")); + if(ret == Idx && Settings.godmode == 1) { + if (++Settings.cios >= settings_cios_max) { + Settings.cios = 0; + } + if ((Settings.cios == 1 && ios222rev!=4) || (Settings.cios == 2 && ios223rev != 4)) { + WindowPrompt(tr("Hermes CIOS"),tr("USB Loader GX will only run with Hermes CIOS rev 4! Please make sure you have revision 4 installed!"),tr("OK")); + } + } + if (Settings.godmode == 1) + options2.SetValue(Idx, "%s", opts_cios[Settings.cios]); + else + options2.SetValue(Idx, "********"); + } + + if (ret == ++Idx || firstRun) + { + if (firstRun) options2.SetName(Idx, "%s", tr("Partition")); + if (ret == Idx) { + // Select the next valid partition, even if that's the same one + do + { + Settings.partition = Settings.partition + 1 == partitions.num ? 0 : Settings.partition + 1; + } + while (!IsValidPartition(partitions.pinfo[Settings.partition].fs_type, Settings.cios)); + } + + PartInfo pInfo = partitions.pinfo[Settings.partition]; + f32 partition_size = partitions.pentry[Settings.partition].size * (partitions.sector_size / GB_SIZE); + + // Get the partition name and it's size in GB's + options2.SetValue(Idx,"%s%d (%.2fGB)", pInfo.fs_type == FS_TYPE_FAT32 ? "FAT" : pInfo.fs_type == FS_TYPE_NTFS ? "NTFS" : "WBFS", + pInfo.index, + partition_size); + } + + if (ret == ++Idx || firstRun) + { + if (firstRun) options2.SetName(Idx, "%s", tr("FAT: Use directories")); + if (ret == Idx && ++Settings.FatInstallToDir >= settings_installdir_max) + Settings.FatInstallToDir = 0; + options2.SetValue(Idx, "%s", tr(opts_installdir[Settings.FatInstallToDir])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Quick Boot")); + if(ret == Idx && ++Settings.qboot >= settings_off_on_max) + Settings.qboot = 0; + options2.SetValue(Idx,"%s",tr(opts_no_yes[Settings.qboot])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Error 002 fix")); + if(ret == Idx && ++Settings.error002 >= settings_error002_max) + Settings.error002 = 0; + options2.SetValue(Idx,"%s",tr(opts_error002[Settings.error002])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Install partitions")); + if(ret == Idx && ++Settings.partitions_to_install >= settings_partitions_max) + Settings.partitions_to_install = 0; + options2.SetValue(Idx,"%s",tr(opts_partitions[Settings.partitions_to_install])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Install 1:1 Copy")); + if(ret == Idx) { + Settings.fullcopy = Settings.fullcopy == 0 ? 1 : 0; + } + options2.SetValue(Idx,"%s",tr(opts_no_yes[Settings.fullcopy])); + } + + firstRun = false; + } + } + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + titleTxt.SetText(tr("Settings")); + slidedirection = FADE; + pageToDisplay = 1; + MainButton2.ResetState(); + break; + } + + else if (MainButton3.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton3.GetEffect() > 0) usleep(50); + HaltGui(); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + titleTxt.SetText(tr("Parental Control")); + exit = false; + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); + ResumeGui(); + + VIDEO_WaitVSync (); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + + bool firstRun = true; + while (!exit) + { + VIDEO_WaitVSync (); + + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); + + else if (backBtn.GetState() == STATE_CLICKED) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } + + ret = optionBrowser2.GetClickedOption(); + + if(firstRun || ret >= 0) + { + + int Idx = -1; + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Console")); + if(ret == Idx) + { + if (!strcmp("", Settings.unlockCode) && Settings.parental.enabled == 0) + { + Settings.godmode = !Settings.godmode; + } + else if ( Settings.godmode == 0 ) + { + char entered[20]; + memset(entered, 0, 20); + + //password check to unlock Install,Delete and Format + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + int result = Settings.parental.enabled == 0 ? OnScreenKeyboard(entered, 20,0) : OnScreenNumpad(entered, 5); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + if (!strcmp(entered, Settings.unlockCode) || !memcmp(entered, Settings.parental.pin, 4)) { //if password correct + if (Settings.godmode == 0) + { + WindowPrompt(tr("Correct Password"),tr("All the features of USB Loader GX are unlocked."),tr("OK")); + Settings.godmode = 1; + menu = MENU_DISCLIST; + } + } + else + WindowPrompt(tr("Wrong Password"),tr("USB Loader GX is protected"),tr("OK")); + } + } + else + { + int choice = WindowPrompt (tr("Lock Console"),tr("Are you sure?"),tr("Yes"),tr("No")); + if (choice == 1) + { + WindowPrompt(tr("Console Locked"),tr("USB Loader GX is protected"),tr("OK")); + Settings.godmode = 0; + menu = MENU_DISCLIST; + } + } + } + static const char *opts[] = {trNOOP("Locked"),trNOOP("Unlocked")}; + options2.SetValue(Idx,"%s",tr(opts[Settings.godmode])); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Password")); + if(ret == Idx) + { + if ( Settings.godmode == 1) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[20] = ""; + strlcpy(entered, Settings.unlockCode, sizeof(entered)); + int result = OnScreenKeyboard(entered, 20,0); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + strlcpy(Settings.unlockCode, entered, sizeof(Settings.unlockCode)); + WindowPrompt(tr("Password Changed"),tr("Password has been changed"),tr("OK")); + } + } + else + { + WindowPrompt(tr("Password Changed"),tr("Console should be unlocked to modify it."),tr("OK")); + } + } + if ( Settings.godmode != 1) options2.SetValue(Idx, "********"); + else if (!strcmp("", Settings.unlockCode)) options2.SetValue(Idx, "%s",tr("not set")); + else options2.SetValue(Idx, Settings.unlockCode); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Controllevel")); + if(ret == Idx && Settings.godmode == 1 && ++Settings.parentalcontrol >= 5 ) + Settings.parentalcontrol = 0; + if (Settings.godmode == 1) + options2.SetValue(Idx,"%s",tr(opts_parentalcontrol[Settings.parentalcontrol])); + else + options2.SetValue(Idx, "********"); + } + + firstRun = false; + } + } + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + titleTxt.SetText(tr("Settings")); + slidedirection = FADE; + pageToDisplay = 1; + MainButton3.ResetState(); + break; + } + + else if (MainButton4.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton4.GetEffect() > 0) usleep(50); + HaltGui(); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + titleTxt.SetText(tr("Sound")); + exit = false; + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); + ResumeGui(); + + VIDEO_WaitVSync (); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + + + char * oggfile; + + bool firstRun = true; + while (!exit) + { + VIDEO_WaitVSync (); + + bool returnhere = true; + + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); + else if (backBtn.GetState() == STATE_CLICKED) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } + + ret = optionBrowser2.GetClickedOption(); + + if(firstRun || ret >= 0) + { + int Idx = -1; + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Backgroundmusic")); + if(ret == Idx) + { + if (isInserted(bootDevice)) + { + w.SetEffect(EFFECT_FADE, -20); + while (w.GetEffect()>0) usleep(50); + mainWindow->Remove(&w); + while (returnhere) + returnhere = MenuOGG(); + HaltGui(); + mainWindow->Append(&w); + w.SetEffect(EFFECT_FADE, 20); + ResumeGui(); + while (w.GetEffect()>0) usleep(50); + } else + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to use this option."),tr("OK")); + } + if (!strcmp("notset", Settings.ogg_path)) + options2.SetValue(Idx, "%s", tr("Standard")); + else + { + oggfile = strrchr(Settings.ogg_path, '/')+1; + options2.SetValue(Idx, "%s", oggfile); + } + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Music Volume")); + if(ret == Idx) + { + Settings.volume += 10; + if (Settings.volume > 100) + Settings.volume = 0; + bgMusic->SetVolume(Settings.volume); + } + if (Settings.volume > 0) + options2.SetValue(Idx,"%i", Settings.volume); + else + options2.SetValue(Idx,"%s", tr("OFF")); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("SFX Volume")); + if(ret == Idx) + { + Settings.sfxvolume += 10; + if (Settings.sfxvolume > 100) + Settings.sfxvolume = 0; + btnSoundOver.SetVolume(Settings.sfxvolume); + btnClick2->SetVolume(Settings.sfxvolume); + btnClick1.SetVolume(Settings.sfxvolume); + } + if (Settings.sfxvolume > 0) + options2.SetValue(Idx,"%i", Settings.sfxvolume); + else + options2.SetValue(Idx,"%s", tr("OFF")); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Game Sound Mode")); + if(ret == Idx) + { + Settings.gamesound++; + if (Settings.gamesound > 2) + Settings.gamesound = 0; + } + + if(Settings.gamesound == 1) options2.SetValue(Idx,"%s", tr("Sound+BGM")); - else if (Settings.gamesound == 2) + else if(Settings.gamesound == 2) options2.SetValue(Idx,"%s", tr("Loop Sound")); else options2.SetValue(Idx,"%s", tr("Sound+Quiet")); - } + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Game Sound Volume")); - if (ret == Idx) { - Settings.gamesoundvolume += 10; - if (Settings.gamesoundvolume > 100) - Settings.gamesoundvolume = 0; - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Game Sound Volume")); + if(ret == Idx) + { + Settings.gamesoundvolume += 10; + if (Settings.gamesoundvolume > 100) + Settings.gamesoundvolume = 0; + } - if (Settings.gamesoundvolume > 0) - options2.SetValue(Idx,"%i", Settings.gamesoundvolume); - else - options2.SetValue(Idx,"%s", tr("OFF")); - } + if (Settings.gamesoundvolume > 0) + options2.SetValue(Idx,"%i", Settings.gamesoundvolume); + else + options2.SetValue(Idx,"%s", tr("OFF")); + } - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - pageToDisplay = 1; - MainButton4.ResetState(); - break; - } - } + firstRun = false; + } + } + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + titleTxt.SetText(tr("Settings")); + slidedirection = FADE; + pageToDisplay = 1; + MainButton4.ResetState(); + break; + } + } - else if ( pageToDisplay == 2) { - if (MainButton1.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton1.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Custom Paths")); - exit = false; - options2.SetLength(0); + else if ( pageToDisplay == 2) + { + if (MainButton1.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton1.GetEffect() > 0) usleep(50); + HaltGui(); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + titleTxt.SetText(tr("Custom Paths")); + exit = false; + options2.SetLength(0); // optionBrowser2.SetScrollbar(1); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); + ResumeGui(); - VIDEO_WaitVSync (); - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); + VIDEO_WaitVSync (); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) usleep(50); - if (Settings.godmode) { - bool firstRun = true; - while (!exit) { - VIDEO_WaitVSync (); + if (Settings.godmode) + { + bool firstRun = true; + while (!exit) + { + VIDEO_WaitVSync (); - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); - else if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } + else if (backBtn.GetState() == STATE_CLICKED) + { + backBtn.ResetState(); + exit = true; + break; + } - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } - ret = optionBrowser2.GetClickedOption(); + ret = optionBrowser2.GetClickedOption(); - if (firstRun || ret >= 0) { + if(firstRun || ret >= 0) + { - int Idx = -1; - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("3D Cover Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.covers_path, sizeof(entered)); - titleTxt.SetText(tr("3D Cover Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.covers_path, entered, sizeof(Settings.covers_path)); - WindowPrompt(tr("Cover Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.covers_path); - } + int Idx = -1; + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("3D Cover Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.covers_path, sizeof(entered)); + titleTxt.SetText(tr("3D Cover Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.covers_path, entered, sizeof(Settings.covers_path)); + WindowPrompt(tr("Cover Path Changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.covers_path); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("2D Cover Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.covers2d_path, sizeof(entered)); - titleTxt.SetText(tr("2D Cover Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.covers2d_path, entered, sizeof(Settings.covers2d_path)); - WindowPrompt(tr("Cover Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.covers2d_path); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("2D Cover Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.covers2d_path, sizeof(entered)); + titleTxt.SetText(tr("2D Cover Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.covers2d_path, entered, sizeof(Settings.covers2d_path)); + WindowPrompt(tr("Cover Path Changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.covers2d_path); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Disc Artwork Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.disc_path, sizeof(entered)); - titleTxt.SetText(tr("Disc Artwork Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.disc_path, entered, sizeof(Settings.disc_path)); - WindowPrompt(tr("Disc Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.disc_path); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Disc Artwork Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.disc_path, sizeof(entered)); + titleTxt.SetText(tr("Disc Artwork Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.disc_path, entered, sizeof(Settings.disc_path)); + WindowPrompt(tr("Disc Path Changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.disc_path); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Theme Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - titleTxt.SetText(tr("Theme Path")); - strlcpy(entered, CFG.theme_path, sizeof(entered)); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - HaltGui(); - w.RemoveAll(); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(CFG.theme_path, entered, sizeof(CFG.theme_path)); - WindowPrompt(tr("Theme Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - else - cfg_save_global(); - mainWindow->Remove(bgImg); - HaltGui(); - CFG_Load(); - CFG_LoadGlobal(); - ResumeGui(); - menu = MENU_SETTINGS; - snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", CFG.theme_path); - pointer[0] = new GuiImageData(imgPath, player1_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", CFG.theme_path); - pointer[1] = new GuiImageData(imgPath, player2_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", CFG.theme_path); - pointer[2] = new GuiImageData(imgPath, player3_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", CFG.theme_path); - pointer[3] = new GuiImageData(imgPath, player4_point_png); - if (CFG.widescreen) - snprintf(imgPath, sizeof(imgPath), "%swbackground.png", CFG.theme_path); - else - snprintf(imgPath, sizeof(imgPath), "%sbackground.png", CFG.theme_path); + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Theme Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + titleTxt.SetText(tr("Theme Path")); + strlcpy(entered, CFG.theme_path, sizeof(entered)); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + HaltGui(); + w.RemoveAll(); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(CFG.theme_path, entered, sizeof(CFG.theme_path)); + WindowPrompt(tr("Theme Path Changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + else + cfg_save_global(); + mainWindow->Remove(bgImg); + HaltGui(); + CFG_Load(); + CFG_LoadGlobal(); + ResumeGui(); + menu = MENU_SETTINGS; + snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", CFG.theme_path); + pointer[0] = new GuiImageData(imgPath, player1_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", CFG.theme_path); + pointer[1] = new GuiImageData(imgPath, player2_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", CFG.theme_path); + pointer[2] = new GuiImageData(imgPath, player3_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", CFG.theme_path); + pointer[3] = new GuiImageData(imgPath, player4_point_png); + if (CFG.widescreen) + snprintf(imgPath, sizeof(imgPath), "%swbackground.png", CFG.theme_path); + else + snprintf(imgPath, sizeof(imgPath), "%sbackground.png", CFG.theme_path); - background = new GuiImageData(imgPath, CFG.widescreen? wbackground_png : background_png); + background = new GuiImageData(imgPath, CFG.widescreen? wbackground_png : background_png); - bgImg = new GuiImage(background); - mainWindow->Append(bgImg); - mainWindow->Append(&w); - } - w.Append(&settingsbackground); - w.Append(&titleTxt); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&backBtn); - w.Append(&optionBrowser2); - ResumeGui(); - } - options2.SetValue(Idx, "%s", CFG.theme_path); - } + bgImg = new GuiImage(background); + mainWindow->Append(bgImg); + mainWindow->Append(&w); + } + w.Append(&settingsbackground); + w.Append(&titleTxt); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&backBtn); + w.Append(&optionBrowser2); + ResumeGui(); + } + options2.SetValue(Idx, "%s", CFG.theme_path); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("WiiTDB Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - titleTxt.SetText(tr("WiiTDB Path")); - strlcpy(entered, Settings.titlestxt_path, sizeof(entered)); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - w.Append(&optionBrowser2); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.titlestxt_path, entered, sizeof(Settings.titlestxt_path)); - WindowPrompt(tr("WiiTDB Path changed."),0,tr("OK")); - if (isInserted(bootDevice)) { - cfg_save_global(); - HaltGui(); - CFG_Load(); - ResumeGui(); - } else - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.titlestxt_path); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("WiiTDB Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + titleTxt.SetText(tr("WiiTDB Path")); + strlcpy(entered, Settings.titlestxt_path, sizeof(entered)); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + w.Append(&optionBrowser2); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.titlestxt_path, entered, sizeof(Settings.titlestxt_path)); + WindowPrompt(tr("WiiTDB Path changed."),0,tr("OK")); + if (isInserted(bootDevice)) + { + cfg_save_global(); + HaltGui(); + CFG_Load(); + ResumeGui(); + } + else + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.titlestxt_path); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Update Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.update_path, sizeof(entered)); - titleTxt.SetText(tr("Update Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.update_path, entered, sizeof(Settings.update_path)); - WindowPrompt(tr("Update Path changed."),0,tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.update_path); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Update Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.update_path, sizeof(entered)); + titleTxt.SetText(tr("Update Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.update_path, entered, sizeof(Settings.update_path)); + WindowPrompt(tr("Update Path changed."),0,tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.update_path); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("GCT Cheatcodes Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.Cheatcodespath, sizeof(entered)); - titleTxt.SetText(tr("GCT Cheatcodes Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.Cheatcodespath, entered, sizeof(Settings.Cheatcodespath)); - WindowPrompt(tr("GCT Cheatcodes Path changed"),0,tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.Cheatcodespath); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("GCT Cheatcodes Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.Cheatcodespath, sizeof(entered)); + titleTxt.SetText(tr("GCT Cheatcodes Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.Cheatcodespath, entered, sizeof(Settings.Cheatcodespath)); + WindowPrompt(tr("GCT Cheatcodes Path changed"),0,tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.Cheatcodespath); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("TXT Cheatcodes Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.TxtCheatcodespath, sizeof(entered)); - titleTxt.SetText(tr("TXT Cheatcodes Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.TxtCheatcodespath, entered, sizeof(Settings.TxtCheatcodespath)); - WindowPrompt(tr("TXT Cheatcodes Path changed"),0,tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.TxtCheatcodespath); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("TXT Cheatcodes Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.TxtCheatcodespath, sizeof(entered)); + titleTxt.SetText(tr("TXT Cheatcodes Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.TxtCheatcodespath, entered, sizeof(Settings.TxtCheatcodespath)); + WindowPrompt(tr("TXT Cheatcodes Path changed"),0,tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.TxtCheatcodespath); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("DOL Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.dolpath, sizeof(entered)); - titleTxt.SetText(tr("DOL Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.dolpath, entered, sizeof(Settings.dolpath)); - WindowPrompt(tr("DOL path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) { - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - } - options2.SetValue(Idx, "%s", Settings.dolpath); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("DOL Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.dolpath, sizeof(entered)); + titleTxt.SetText(tr("DOL Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.dolpath, entered, sizeof(Settings.dolpath)); + WindowPrompt(tr("DOL path changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + { + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + } + options2.SetValue(Idx, "%s", Settings.dolpath); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Homebrew Apps Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.homebrewapps_path, sizeof(entered)); - titleTxt.SetText(tr("Homebrew Apps Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.homebrewapps_path, entered, sizeof(Settings.homebrewapps_path)); - WindowPrompt(tr("Homebrew Appspath changed"),0,tr("OK")); - if (!isInserted(bootDevice)) { - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - } - options2.SetValue(Idx, "%s", Settings.homebrewapps_path); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Homebrew Apps Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.homebrewapps_path, sizeof(entered)); + titleTxt.SetText(tr("Homebrew Apps Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.homebrewapps_path, entered, sizeof(Settings.homebrewapps_path)); + WindowPrompt(tr("Homebrew Appspath changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + { + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + } + options2.SetValue(Idx, "%s", Settings.homebrewapps_path); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Theme Download Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.theme_downloadpath, sizeof(entered)); - titleTxt.SetText(tr("Theme Download Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.theme_downloadpath, entered, sizeof(Settings.theme_downloadpath)); - WindowPrompt(tr("Theme Download Path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.theme_downloadpath); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Theme Download Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.theme_downloadpath, sizeof(entered)); + titleTxt.SetText(tr("Theme Download Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.theme_downloadpath, entered, sizeof(Settings.theme_downloadpath)); + WindowPrompt(tr("Theme Download Path changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.theme_downloadpath); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("BCA Codes Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.BcaCodepath, sizeof(entered)); - titleTxt.SetText(tr("BCA Codes Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.BcaCodepath, entered, sizeof(Settings.BcaCodepath)); - WindowPrompt(tr("BCA Codes Path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.BcaCodepath); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("BCA Codes Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.BcaCodepath, sizeof(entered)); + titleTxt.SetText(tr("BCA Codes Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.BcaCodepath, entered, sizeof(Settings.BcaCodepath)); + WindowPrompt(tr("BCA Codes Path changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.BcaCodepath); + } + + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("WIP Patches Path")); + if(ret == Idx) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + char entered[100] = ""; + strlcpy(entered, Settings.WipCodepath, sizeof(entered)); + titleTxt.SetText(tr("WIP Patches Path")); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); + titleTxt.SetText(tr("Custom Paths")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + if ( result == 1 ) + { + int len = (strlen(entered)-1); + if (entered[len] !='/') + strncat (entered, "/", 1); + strlcpy(Settings.WipCodepath, entered, sizeof(Settings.WipCodepath)); + WindowPrompt(tr("WIP Patches Path changed"),0,tr("OK")); + if (!isInserted(bootDevice)) + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + } + } + options2.SetValue(Idx, "%s", Settings.WipCodepath); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("WIP Patches Path")); - if (ret == Idx) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.WipCodepath, sizeof(entered)); - titleTxt.SetText(tr("WIP Patches Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.WipCodepath, entered, sizeof(Settings.WipCodepath)); - WindowPrompt(tr("WIP Patches Path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.WipCodepath); - } + firstRun = false; + } + } + /** If not godmode don't let him inside **/ + } + else + WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + titleTxt.SetText(tr("Settings")); + slidedirection = FADE; + pageToDisplay = 2; + MainButton1.ResetState(); + break; + } - firstRun = false; - } - } - /** If not godmode don't let him inside **/ - } else - WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - pageToDisplay = 2; - MainButton1.ResetState(); - break; - } + else if (MainButton2.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton2.GetEffect() > 0) usleep(50); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + if (isInserted(bootDevice) && Settings.godmode) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + int ret = ProgressUpdateWindow(); + if (ret < 0) + WindowPrompt(tr("Update failed"),0,tr("OK")); + w.Append(&optionBrowser2); + w.Append(&backBtn); + } + else + WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); + slidedirection = FADE; + pageToDisplay = 2; + MainButton2.ResetState(); + break; + } - else if (MainButton2.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton2.GetEffect() > 0) usleep(50); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - if (isInserted(bootDevice) && Settings.godmode) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - int ret = ProgressUpdateWindow(); - if (ret < 0) - WindowPrompt(tr("Update failed"),0,tr("OK")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - } else - WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); - slidedirection = FADE; - pageToDisplay = 2; - MainButton2.ResetState(); - break; - } + else if (MainButton3.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton3.GetEffect() > 0) usleep(50); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + w.Remove(&backBtn); + w.Remove(&optionBrowser2); + if (Settings.godmode) + { + int choice = WindowPrompt(tr("Are you sure?"), 0, tr("Yes"), tr("Cancel")); + if (choice == 1) + { + if (isInserted(bootDevice)) + { + char GXGlobal_cfg[26]; + sprintf(GXGlobal_cfg, "%s/config/GXGlobal.cfg", bootDevice); + remove(GXGlobal_cfg); + } + gettextCleanUp(); + HaltGui(); + CFG_Load(); + ResumeGui(); + menu = MENU_SETTINGS; + pageToDisplay = 0; + } + } + else + WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); + w.Append(&backBtn); + w.Append(&optionBrowser2); + slidedirection = FADE; + pageToDisplay = 2; + MainButton3.ResetState(); + break; + } - else if (MainButton3.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton3.GetEffect() > 0) usleep(50); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - w.Remove(&backBtn); - w.Remove(&optionBrowser2); - if (Settings.godmode) { - int choice = WindowPrompt(tr("Are you sure?"), 0, tr("Yes"), tr("Cancel")); - if (choice == 1) { - if (isInserted(bootDevice)) { - char GXGlobal_cfg[26]; - sprintf(GXGlobal_cfg, "%s/config/GXGlobal.cfg", bootDevice); - remove(GXGlobal_cfg); - } - gettextCleanUp(); - HaltGui(); - CFG_Load(); - ResumeGui(); - menu = MENU_SETTINGS; - pageToDisplay = 0; - } - } else - WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); - w.Append(&backBtn); - w.Append(&optionBrowser2); - slidedirection = FADE; - pageToDisplay = 2; - MainButton3.ResetState(); - break; - } + else if (MainButton4.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton4.GetEffect() > 0) usleep(50); + w.Remove(&PageIndicatorBtn1); + w.Remove(&PageIndicatorBtn2); + w.Remove(&PageIndicatorBtn3); + w.Remove(&GoRightBtn); + w.Remove(&GoLeftBtn); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + WindowCredits(); + slidedirection = FADE; + pageToDisplay = 2; + MainButton4.ResetState(); + break; + } + } - else if (MainButton4.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton4.GetEffect() > 0) usleep(50); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - WindowCredits(); - slidedirection = FADE; - pageToDisplay = 2; - MainButton4.ResetState(); - break; - } - } - - else if (pageToDisplay == 3) { - if (MainButton1.GetState() == STATE_CLICKED) { - if (isInserted(bootDevice)) - cfg_save_global(); - menu = MENU_THEMEDOWNLOADER; - pageToDisplay = 0; - break; - } - } + else if(pageToDisplay == 3) + { + if (MainButton1.GetState() == STATE_CLICKED) + { + if (isInserted(bootDevice)) + cfg_save_global(); + menu = MENU_THEMEDOWNLOADER; + pageToDisplay = 0; + break; + } + } - if (backBtn.GetState() == STATE_CLICKED) { - //Add the procedure call to save the global configuration - if (isInserted(bootDevice)) - cfg_save_global(); - menu = MENU_DISCLIST; - pageToDisplay = 0; - break; - } + if (backBtn.GetState() == STATE_CLICKED) + { + //Add the procedure call to save the global configuration + if (isInserted(bootDevice)) + cfg_save_global(); + menu = MENU_DISCLIST; + pageToDisplay = 0; + break; + } - else if (GoLeftBtn.GetState() == STATE_CLICKED) { - pageToDisplay--; - /** Change direction of the flying buttons **/ - if (pageToDisplay < 1) - pageToDisplay = 3; - slidedirection = LEFT; - GoLeftBtn.ResetState(); - break; - } + else if (GoLeftBtn.GetState() == STATE_CLICKED) + { + pageToDisplay--; + /** Change direction of the flying buttons **/ + if (pageToDisplay < 1) + pageToDisplay = 3; + slidedirection = LEFT; + GoLeftBtn.ResetState(); + break; + } - else if (GoRightBtn.GetState() == STATE_CLICKED) { - pageToDisplay++; - /** Change direction of the flying buttons **/ - if (pageToDisplay > 3) - pageToDisplay = 1; - slidedirection = RIGHT; - GoRightBtn.ResetState(); - break; - } else if (PageIndicatorBtn1.GetState() == STATE_CLICKED) { - if (pageToDisplay > 1) { - slidedirection = LEFT; - pageToDisplay = 1; - PageIndicatorBtn1.ResetState(); - break; - } - PageIndicatorBtn1.ResetState(); - } else if (PageIndicatorBtn2.GetState() == STATE_CLICKED) { - if (pageToDisplay < 2) { - slidedirection = RIGHT; - pageToDisplay = 2; - PageIndicatorBtn2.ResetState(); - break; - } else if (pageToDisplay > 2) { - slidedirection = LEFT; - pageToDisplay = 2; - PageIndicatorBtn2.ResetState(); - break; - } else - PageIndicatorBtn2.ResetState(); - } else if (PageIndicatorBtn3.GetState() == STATE_CLICKED) { - if (pageToDisplay < 3) { - slidedirection = RIGHT; - pageToDisplay = 3; - PageIndicatorBtn3.ResetState(); - break; - } else - PageIndicatorBtn3.ResetState(); - } else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); + else if (GoRightBtn.GetState() == STATE_CLICKED) + { + pageToDisplay++; + /** Change direction of the flying buttons **/ + if (pageToDisplay > 3) + pageToDisplay = 1; + slidedirection = RIGHT; + GoRightBtn.ResetState(); + break; + } + else if (PageIndicatorBtn1.GetState() == STATE_CLICKED) + { + if (pageToDisplay > 1) + { + slidedirection = LEFT; + pageToDisplay = 1; + PageIndicatorBtn1.ResetState(); + break; + } + PageIndicatorBtn1.ResetState(); + } + else if (PageIndicatorBtn2.GetState() == STATE_CLICKED) + { + if (pageToDisplay < 2) + { + slidedirection = RIGHT; + pageToDisplay = 2; + PageIndicatorBtn2.ResetState(); + break; + } + else if (pageToDisplay > 2) + { + slidedirection = LEFT; + pageToDisplay = 2; + PageIndicatorBtn2.ResetState(); + break; + } + else + PageIndicatorBtn2.ResetState(); + } + else if (PageIndicatorBtn3.GetState() == STATE_CLICKED) + { + if (pageToDisplay < 3) + { + slidedirection = RIGHT; + pageToDisplay = 3; + PageIndicatorBtn3.ResetState(); + break; + } + else + PageIndicatorBtn3.ResetState(); + } + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - } - } + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } + } + } - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); + w.SetEffect(EFFECT_FADE, -20); + while (w.GetEffect()>0) usleep(50); - // if partition has changed, Reinitialize it - if (Settings.partition != settingspartitionold) { - WBFS_Close(); - PartInfo pinfo = partitions.pinfo[Settings.partition]; - partitionEntry pentry = partitions.pentry[Settings.partition]; - WBFS_OpenPart(load_from_fs, pinfo.index, pentry.sector, pentry.size, (char *) &game_partition); - load_from_fs = pinfo.part_fs; - } + // if partition has changed, Reinitialize it + if (Settings.partition != settingspartitionold) { + WBFS_Close(); + PartInfo pinfo = partitions.pinfo[Settings.partition]; + partitionEntry pentry = partitions.pentry[Settings.partition]; + WBFS_OpenPart(load_from_fs, pinfo.index, pentry.sector, pentry.size, (char *) &game_partition); + load_from_fs = pinfo.part_fs; + } + + // if language has changed, reload titles + char opt_langnew[100]; + strcpy(opt_langnew,Settings.language_path); + int opt_overridenew = Settings.titlesOverride; + bool reloaddatabasefile = false; + if (strcmp(opt_lang,opt_langnew) || (opt_override != opt_overridenew && Settings.titlesOverride==1) || (Settings.partition != settingspartitionold)) { + if (Settings.partition != settingspartitionold) { + reloaddatabasefile = true; + CloseXMLDatabase(); + } + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, reloaddatabasefile, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory + } + // disable titles from database if setting has changed + if (opt_override != opt_overridenew && Settings.titlesOverride==0) + titles_default(); - // if language has changed, reload titles - char opt_langnew[100]; - strcpy(opt_langnew,Settings.language_path); - int opt_overridenew = Settings.titlesOverride; - bool reloaddatabasefile = false; - if (strcmp(opt_lang,opt_langnew) || (opt_override != opt_overridenew && Settings.titlesOverride==1) || (Settings.partition != settingspartitionold)) { - if (Settings.partition != settingspartitionold) { - reloaddatabasefile = true; - CloseXMLDatabase(); - } - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, reloaddatabasefile, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory - } - // disable titles from database if setting has changed - if (opt_override != opt_overridenew && Settings.titlesOverride==0) - titles_default(); + HaltGui(); - HaltGui(); + mainWindow->RemoveAll(); + mainWindow->Append(bgImg); - mainWindow->RemoveAll(); - mainWindow->Append(bgImg); - - ResumeGui(); - return menu; -} + ResumeGui(); + return menu; + } /******************************************************************************** *Game specific settings *********************************************************************************/ -int GameSettings(struct discHdr * header) { - int menu = MENU_NONE; - int ret; - int choice = 0; - bool exit = false; +int GameSettings(struct discHdr * header) +{ + int menu = MENU_NONE; + int ret; + int choice = 0; + bool exit = false; - int retVal = 0; + int retVal = 0; - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - char imgPath[100]; + char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path); - GuiImageData MainButtonImgData(imgPath, settings_title_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path); + GuiImageData MainButtonImgData(imgPath, settings_title_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path); - GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path); + GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigHome; - trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + GuiTrigger trigA; + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + GuiTrigger trigHome; + trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - char gameName[31]; - if (!mountMethod) { - if (strlen(get_title(header)) < (27 + 3)) - sprintf(gameName, "%s", get_title(header)); - else { - strncpy(gameName, get_title(header), 27); - gameName[27] = '\0'; - strncat(gameName, "...", 3); - } - } else - sprintf(gameName, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); + char gameName[31]; + if (!mountMethod) + { + if (strlen(get_title(header)) < (27 + 3)) + sprintf(gameName, "%s", get_title(header)); + else + { + strncpy(gameName, get_title(header), 27); + gameName[27] = '\0'; + strncat(gameName, "...", 3); + } + } + else + sprintf(gameName, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - GuiText titleTxt(!mountMethod?get_title(header):gameName, 28, (GXColor) {0, 0, 0, 255}); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetPosition(12,40); - titleTxt.SetMaxWidth(356, GuiText::SCROLL); + GuiText titleTxt(!mountMethod?get_title(header):gameName, 28, (GXColor) {0, 0, 0, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(12,40); + titleTxt.SetMaxWidth(356, GuiText::SCROLL); - GuiImage settingsbackground(&settingsbg); + GuiImage settingsbackground(&settingsbg); - GuiText backBtnTxt(tr("Back"), 22, THEME.prompttext); - backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage backBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); + GuiText backBtnTxt(tr("Back"), 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); + GuiImage backBtnImg(&btnOutline); + if (Settings.wsprompt == yes) + { + backBtnTxt.SetWidescreen(CFG.widescreen); + backBtnImg.SetWidescreen(CFG.widescreen); + } + GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); + backBtn.SetLabel(&backBtnTxt); + backBtn.SetTrigger(&trigB); - GuiButton homo(1,1); - homo.SetTrigger(&trigHome); + GuiButton homo(1,1); + homo.SetTrigger(&trigHome); - GuiText saveBtnTxt(tr("Save"), 22, THEME.prompttext); - saveBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage saveBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - saveBtnTxt.SetWidescreen(CFG.widescreen); - saveBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton saveBtn(&saveBtnImg,&saveBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2,1); - saveBtn.SetLabel(&saveBtnTxt); + GuiText saveBtnTxt(tr("Save"), 22, THEME.prompttext); + saveBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); + GuiImage saveBtnImg(&btnOutline); + if (Settings.wsprompt == yes) + { + saveBtnTxt.SetWidescreen(CFG.widescreen); + saveBtnImg.SetWidescreen(CFG.widescreen); + } + GuiButton saveBtn(&saveBtnImg,&saveBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2,1); + saveBtn.SetLabel(&saveBtnTxt); - char MainButtonText[50]; - snprintf(MainButtonText, sizeof(MainButtonText), "%s", " "); + char MainButtonText[50]; + snprintf(MainButtonText, sizeof(MainButtonText), "%s", " "); - GuiImage MainButton1Img(&MainButtonImgData); - GuiImage MainButton1ImgOver(&MainButtonImgOverData); - GuiText MainButton1Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth()); - GuiButton MainButton1(MainButton1Img.GetWidth(), MainButton1Img.GetHeight()); - MainButton1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton1.SetPosition(0, 90); - MainButton1.SetImage(&MainButton1Img); - MainButton1.SetImageOver(&MainButton1ImgOver); - MainButton1.SetLabel(&MainButton1Txt); - MainButton1.SetSoundOver(&btnSoundOver); - MainButton1.SetSoundClick(&btnClick1); - MainButton1.SetEffectGrow(); - MainButton1.SetTrigger(&trigA); + GuiImage MainButton1Img(&MainButtonImgData); + GuiImage MainButton1ImgOver(&MainButtonImgOverData); + GuiText MainButton1Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); + MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth()); + GuiButton MainButton1(MainButton1Img.GetWidth(), MainButton1Img.GetHeight()); + MainButton1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton1.SetPosition(0, 90); + MainButton1.SetImage(&MainButton1Img); + MainButton1.SetImageOver(&MainButton1ImgOver); + MainButton1.SetLabel(&MainButton1Txt); + MainButton1.SetSoundOver(&btnSoundOver); + MainButton1.SetSoundClick(&btnClick1); + MainButton1.SetEffectGrow(); + MainButton1.SetTrigger(&trigA); - GuiImage MainButton2Img(&MainButtonImgData); - GuiImage MainButton2ImgOver(&MainButtonImgOverData); - GuiText MainButton2Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()); - GuiButton MainButton2(MainButton2Img.GetWidth(), MainButton2Img.GetHeight()); - MainButton2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton2.SetPosition(0, 160); - MainButton2.SetImage(&MainButton2Img); - MainButton2.SetImageOver(&MainButton2ImgOver); - MainButton2.SetLabel(&MainButton2Txt); - MainButton2.SetSoundOver(&btnSoundOver); - MainButton2.SetSoundClick(&btnClick1); - MainButton2.SetEffectGrow(); - MainButton2.SetTrigger(&trigA); + GuiImage MainButton2Img(&MainButtonImgData); + GuiImage MainButton2ImgOver(&MainButtonImgOverData); + GuiText MainButton2Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); + MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()); + GuiButton MainButton2(MainButton2Img.GetWidth(), MainButton2Img.GetHeight()); + MainButton2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton2.SetPosition(0, 160); + MainButton2.SetImage(&MainButton2Img); + MainButton2.SetImageOver(&MainButton2ImgOver); + MainButton2.SetLabel(&MainButton2Txt); + MainButton2.SetSoundOver(&btnSoundOver); + MainButton2.SetSoundClick(&btnClick1); + MainButton2.SetEffectGrow(); + MainButton2.SetTrigger(&trigA); - GuiImage MainButton3Img(&MainButtonImgData); - GuiImage MainButton3ImgOver(&MainButtonImgOverData); - GuiText MainButton3Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()); - GuiButton MainButton3(MainButton3Img.GetWidth(), MainButton3Img.GetHeight()); - MainButton3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton3.SetPosition(0, 230); - MainButton3.SetImage(&MainButton3Img); - MainButton3.SetImageOver(&MainButton3ImgOver); - MainButton3.SetLabel(&MainButton3Txt); - MainButton3.SetSoundOver(&btnSoundOver); - MainButton3.SetSoundClick(&btnClick1); - MainButton3.SetEffectGrow(); - MainButton3.SetTrigger(&trigA); + GuiImage MainButton3Img(&MainButtonImgData); + GuiImage MainButton3ImgOver(&MainButtonImgOverData); + GuiText MainButton3Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); + MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()); + GuiButton MainButton3(MainButton3Img.GetWidth(), MainButton3Img.GetHeight()); + MainButton3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton3.SetPosition(0, 230); + MainButton3.SetImage(&MainButton3Img); + MainButton3.SetImageOver(&MainButton3ImgOver); + MainButton3.SetLabel(&MainButton3Txt); + MainButton3.SetSoundOver(&btnSoundOver); + MainButton3.SetSoundClick(&btnClick1); + MainButton3.SetEffectGrow(); + MainButton3.SetTrigger(&trigA); - GuiImage MainButton4Img(&MainButtonImgData); - GuiImage MainButton4ImgOver(&MainButtonImgOverData); - GuiText MainButton4Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()); - GuiButton MainButton4(MainButton4Img.GetWidth(), MainButton4Img.GetHeight()); - MainButton4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton4.SetPosition(0, 300); - MainButton4.SetImage(&MainButton4Img); - MainButton4.SetImageOver(&MainButton4ImgOver); - MainButton4.SetLabel(&MainButton4Txt); - MainButton4.SetSoundOver(&btnSoundOver); - MainButton4.SetSoundClick(&btnClick1); - MainButton4.SetEffectGrow(); - MainButton4.SetTrigger(&trigA); + GuiImage MainButton4Img(&MainButtonImgData); + GuiImage MainButton4ImgOver(&MainButtonImgOverData); + GuiText MainButton4Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); + MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()); + GuiButton MainButton4(MainButton4Img.GetWidth(), MainButton4Img.GetHeight()); + MainButton4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + MainButton4.SetPosition(0, 300); + MainButton4.SetImage(&MainButton4Img); + MainButton4.SetImageOver(&MainButton4ImgOver); + MainButton4.SetLabel(&MainButton4Txt); + MainButton4.SetSoundOver(&btnSoundOver); + MainButton4.SetSoundClick(&btnClick1); + MainButton4.SetEffectGrow(); + MainButton4.SetTrigger(&trigA); - customOptionList options2(MAXOPTIONS); - GuiCustomOptionBrowser optionBrowser2(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150); - optionBrowser2.SetPosition(0, 90); - optionBrowser2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + customOptionList options2(MAXOPTIONS); + GuiCustomOptionBrowser optionBrowser2(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150); + optionBrowser2.SetPosition(0, 90); + optionBrowser2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - GuiWindow w(screenwidth, screenheight); - //int opt_lang = languageChoice; // backup language setting - struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); + GuiWindow w(screenwidth, screenheight); + //int opt_lang = languageChoice; // backup language setting + struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); - int pageToDisplay = 1; - while ( pageToDisplay > 0) { //set pageToDisplay to 0 to quit - VIDEO_WaitVSync (); + int pageToDisplay = 1; + while ( pageToDisplay > 0) { //set pageToDisplay to 0 to quit + VIDEO_WaitVSync (); - menu = MENU_NONE; + menu = MENU_NONE; - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - HaltGui(); + HaltGui(); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Game Load")); - MainButton1Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "Ocarina"); - MainButton2Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Uninstall Menu")); - MainButton3Txt.SetText(MainButtonText); - snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Default Gamesettings")); - MainButton4Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Game Load")); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "Ocarina"); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Uninstall Menu")); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", tr("Default Gamesettings")); + MainButton4Txt.SetText(MainButtonText); - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&MainButton1); - w.Append(&MainButton2); - w.Append(&MainButton3); - w.Append(&MainButton4); + mainWindow->RemoveAll(); + mainWindow->Append(&w); + w.RemoveAll(); + w.Append(&settingsbackground); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&homo); + w.Append(&MainButton1); + w.Append(&MainButton2); + w.Append(&MainButton3); + w.Append(&MainButton4); - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable(false); + /** Default no scrollbar and reset position **/ // optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); + optionBrowser2.SetOffset(0); - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); + MainButton1.SetEffect(EFFECT_FADE, 20); + MainButton2.SetEffect(EFFECT_FADE, 20); + MainButton3.SetEffect(EFFECT_FADE, 20); + MainButton4.SetEffect(EFFECT_FADE, 20); - mainWindow->Append(&w); + mainWindow->Append(&w); - if (game_cfg) { //if there are saved settings for this game use them - videoChoice = game_cfg->video; - languageChoice = game_cfg->language; - ocarinaChoice = game_cfg->ocarina; - viChoice = game_cfg->vipatch; - iosChoice = game_cfg->ios; - parentalcontrolChoice = game_cfg->parentalcontrol; - fix002 = game_cfg->errorfix002; - countrystrings = game_cfg->patchcountrystrings; - alternatedol = game_cfg->loadalternatedol; - alternatedoloffset = game_cfg->alternatedolstart; - reloadblock = game_cfg->iosreloadblock; - strlcpy(alternatedname, game_cfg->alternatedolname, sizeof(alternatedname)); - } else { - videoChoice = Settings.video; - languageChoice = Settings.language; - ocarinaChoice = Settings.ocarina; - viChoice = Settings.vpatch; - if (Settings.cios == ios222) - iosChoice = i222; - else if (Settings.cios == ios250) - iosChoice = i250; - else if (Settings.cios == ios223) - iosChoice = i223; - else - iosChoice = i249; - parentalcontrolChoice = 0; - fix002 = Settings.error002; - countrystrings = Settings.patchcountrystrings; - alternatedol = off; - alternatedoloffset = 0; - reloadblock = off; - strcpy(alternatedname, ""); - } + if (game_cfg) { //if there are saved settings for this game use them + videoChoice = game_cfg->video; + languageChoice = game_cfg->language; + ocarinaChoice = game_cfg->ocarina; + viChoice = game_cfg->vipatch; + iosChoice = game_cfg->ios; + parentalcontrolChoice = game_cfg->parentalcontrol; + fix002 = game_cfg->errorfix002; + countrystrings = game_cfg->patchcountrystrings; + alternatedol = game_cfg->loadalternatedol; + alternatedoloffset = game_cfg->alternatedolstart; + reloadblock = game_cfg->iosreloadblock; + strlcpy(alternatedname, game_cfg->alternatedolname, sizeof(alternatedname)); + } + else + { + videoChoice = Settings.video; + languageChoice = Settings.language; + ocarinaChoice = Settings.ocarina; + viChoice = Settings.vpatch; + if (Settings.cios == ios222) + iosChoice = i222; + else if (Settings.cios == ios250) + iosChoice = i250; + else if (Settings.cios == ios223) + iosChoice = i223; + else + iosChoice = i249; + parentalcontrolChoice = 0; + fix002 = Settings.error002; + countrystrings = Settings.patchcountrystrings; + alternatedol = off; + alternatedoloffset = 0; + reloadblock = off; + strcpy(alternatedname, ""); + } - ResumeGui(); + ResumeGui(); - while (MainButton1.GetEffect() > 0) usleep(50); + while (MainButton1.GetEffect() > 0) usleep(50); - while (menu == MENU_NONE) { - VIDEO_WaitVSync (); + while (menu == MENU_NONE) + { + VIDEO_WaitVSync (); - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); - if (MainButton1.GetState() == STATE_CLICKED) { - w.Append(&saveBtn); - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton1.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - exit = false; - options2.SetLength(0); + if (MainButton1.GetState() == STATE_CLICKED) + { + w.Append(&saveBtn); + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton1.GetEffect() > 0) usleep(50); + HaltGui(); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + exit = false; + options2.SetLength(0); // optionBrowser2.SetScrollbar(1); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); + ResumeGui(); - VIDEO_WaitVSync (); - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); + VIDEO_WaitVSync (); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) usleep(50); - int returnhere = 1; - char * languagefile; - languagefile = strrchr(Settings.language_path, '/')+1; + int returnhere = 1; + char * languagefile; + languagefile = strrchr(Settings.language_path, '/')+1; - bool firstRun = true; - while (!exit) { - VIDEO_WaitVSync (); + bool firstRun = true; + while (!exit) + { + VIDEO_WaitVSync (); - returnhere = 1; + returnhere = 1; - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); + if (backBtn.GetState() == STATE_CLICKED) + { + backBtn.ResetState(); + exit = true; + break; + } - else if (menu == MENU_DISCLIST) { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - WindowCredits(); - w.Append(&optionBrowser2); - w.Append(&backBtn); - } + else if (menu == MENU_DISCLIST) + { + w.Remove(&optionBrowser2); + w.Remove(&backBtn); + WindowCredits(); + w.Append(&optionBrowser2); + w.Append(&backBtn); + } - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } - else if (saveBtn.GetState() == STATE_CLICKED) { - if (isInserted(bootDevice)) { - if (CFG_save_game_opt(header->id)) { - /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database - // if game language has changed when saving game settings, reload titles - int opt_langnew = 0; - game_cfg = CFG_get_game_opt(header->id); - if (game_cfg) opt_langnew = game_cfg->language; - if (Settings.titlesOverride==1 && opt_lang != opt_langnew) - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory - // titles are refreshed in menu.cpp as soon as this function returns - */ - game_cfg = CFG_get_game_opt(header->id); // needed here for "if (game_cfg)" earlier in case it's the first time settings are saved for a game - WindowPrompt(tr("Successfully Saved"),0,tr("OK")); - } else - WindowPrompt(tr("Save Failed"),0,tr("OK")); - } else - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); + else if (saveBtn.GetState() == STATE_CLICKED) + { + if (isInserted(bootDevice)) + { + if (CFG_save_game_opt(header->id)) + { + /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database + // if game language has changed when saving game settings, reload titles + int opt_langnew = 0; + game_cfg = CFG_get_game_opt(header->id); + if (game_cfg) opt_langnew = game_cfg->language; + if (Settings.titlesOverride==1 && opt_lang != opt_langnew) + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory + // titles are refreshed in menu.cpp as soon as this function returns + */ + game_cfg = CFG_get_game_opt(header->id); // needed here for "if (game_cfg)" earlier in case it's the first time settings are saved for a game + WindowPrompt(tr("Successfully Saved"),0,tr("OK")); + } + else + WindowPrompt(tr("Save Failed"),0,tr("OK")); + } + else + WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - saveBtn.ResetState(); - optionBrowser2.SetFocus(1); - } + saveBtn.ResetState(); + optionBrowser2.SetFocus(1); + } - ret = optionBrowser2.GetClickedOption(); + ret = optionBrowser2.GetClickedOption(); - if (ret >= 0 || firstRun == true) { - int Idx = -1; + if(ret >= 0 || firstRun == true) + { + int Idx = -1; - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("Video Mode")); - if (ret == Idx && ++videoChoice >= settings_video_max) - videoChoice = 0; - options2.SetValue(Idx,"%s%s",opts_videomode[videoChoice][0], tr(opts_videomode[videoChoice][1])); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("Video Mode")); + if(ret == Idx && ++videoChoice >= settings_video_max) + videoChoice = 0; + options2.SetValue(Idx,"%s%s",opts_videomode[videoChoice][0], tr(opts_videomode[videoChoice][1])); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s",tr("VIDTV Patch")); - if (ret == Idx && ++viChoice >= settings_off_on_max) - viChoice = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[viChoice])); + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s",tr("VIDTV Patch")); + if(ret == Idx && ++viChoice >= settings_off_on_max) + viChoice = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[viChoice])); - } + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Game Language")); - if (ret == Idx && ++languageChoice >= settings_language_max) - languageChoice = 0; - options2.SetValue(Idx,"%s",tr(opts_language[languageChoice])); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Game Language")); + if(ret == Idx && ++languageChoice >= settings_language_max) + languageChoice = 0; + options2.SetValue(Idx,"%s",tr(opts_language[languageChoice])); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "Ocarina"); - if (ret == Idx && ++ocarinaChoice >= settings_off_on_max) - ocarinaChoice = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[ocarinaChoice])); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "Ocarina"); + if(ret == Idx && ++ocarinaChoice >= settings_off_on_max) + ocarinaChoice = 0; + options2.SetValue(Idx,"%s",tr(opts_off_on[ocarinaChoice])); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "IOS"); - if (ret == Idx && ++iosChoice >= settings_ios_max) - iosChoice = 0; - options2.SetValue(Idx,"%s",opts_cios[iosChoice]); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "IOS"); + if(ret == Idx && ++iosChoice >= settings_ios_max) + iosChoice = 0; + options2.SetValue(Idx,"%s",opts_cios[iosChoice]); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Parental Control")); - if (ret == Idx && ++parentalcontrolChoice >= 5) - parentalcontrolChoice = 0; - options2.SetValue(Idx,"%s", tr(opts_parentalcontrol[parentalcontrolChoice])); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Parental Control")); + if(ret == Idx && ++parentalcontrolChoice >= 5) + parentalcontrolChoice = 0; + options2.SetValue(Idx,"%s", tr(opts_parentalcontrol[parentalcontrolChoice])); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Error 002 fix")); - if (ret == Idx && ++fix002 >= settings_error002_max) - fix002 = 0; - options2.SetValue(Idx,"%s", tr(opts_error002[fix002])); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Error 002 fix")); + if(ret == Idx && ++fix002 >= settings_error002_max) + fix002 = 0; + options2.SetValue(Idx,"%s", tr(opts_error002[fix002])); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Patch Country Strings")); - if (ret == Idx && ++countrystrings >= settings_off_on_max) - countrystrings = 0; - options2.SetValue(Idx,"%s", tr(opts_off_on[countrystrings])); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Patch Country Strings")); + if(ret == Idx && ++countrystrings >= settings_off_on_max) + countrystrings = 0; + options2.SetValue(Idx,"%s", tr(opts_off_on[countrystrings])); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Alternate DOL")); - int last_alternatedol = alternatedol; - if (ret == Idx && (alternatedol = (alternatedol+2) % 3) >= 3) // 0->2->1->0 - alternatedol = 0; - static const char *opts[] = {trNOOP("Default"),trNOOP("Load From SD/USB"),trNOOP("Select a DOL")}; - options2.SetValue(Idx,"%s", tr(opts[alternatedol])); - if (last_alternatedol != 1) { - firstRun = true; // force re-init follow Entries - options2.SetLength(Idx+1); - } - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Alternate DOL")); + int last_alternatedol = alternatedol; + if(ret == Idx && (alternatedol = (alternatedol+2) % 3) >= 3) // 0->2->1->0 + alternatedol = 0; + static const char *opts[] = {trNOOP("Default"),trNOOP("Load From SD/USB"),trNOOP("Select a DOL")}; + options2.SetValue(Idx,"%s", tr(opts[alternatedol])); + if(last_alternatedol != 1) + { + firstRun = true; // force re-init follow Entries + options2.SetLength(Idx+1); + } + } - if (alternatedol == 2 && (ret == ++Idx || firstRun)) { - if (firstRun) options2.SetName(Idx, "%s", tr("Selected DOL")); - if (ret == Idx) { - if (alternatedol == 2) { - char filename[10]; - snprintf(filename,sizeof(filename),"%c%c%c%c%c%c",header->id[0], header->id[1], header->id[2], - header->id[3],header->id[4], header->id[5]); - int dolchoice = 0; - //alt dol menu for games that require more than a single alt dol - int autodol = autoSelectDolMenu(filename, false); + if(alternatedol == 2 && (ret == ++Idx || firstRun)) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Selected DOL")); + if(ret == Idx) + { + if (alternatedol == 2) + { + char filename[10]; + snprintf(filename,sizeof(filename),"%c%c%c%c%c%c",header->id[0], header->id[1], header->id[2], + header->id[3],header->id[4], header->id[5]); + int dolchoice = 0; + //alt dol menu for games that require more than a single alt dol + int autodol = autoSelectDolMenu(filename, false); - if (autodol>0) { - alternatedoloffset = autodol; - snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", tr("AUTO"), autodol); - } else if (autodol == 0) - alternatedol = 0; // default was chosen - else { - //check to see if we already know the offset of the correct dol - int autodol = autoSelectDol(filename, false); - //if we do know that offset ask if they want to use it - if (autodol>0) { - dolchoice = WindowPrompt(0,tr("Do you want to use the alternate DOL that is known to be correct?"),tr("Yes"),tr("Pick from a list"),tr("Cancel")); - if (dolchoice==0) - alternatedol = 0; - else if (dolchoice==1) { - alternatedoloffset = autodol; - snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", tr("AUTO"),autodol); - } else if (dolchoice==2) { //they want to search for the correct dol themselves - int res = DiscBrowse(header); - if ((res >= 0)&&(res !=696969)) //if res==696969 they pressed the back button - alternatedoloffset = res; - } - } else { - int res = DiscBrowse(header); - if ((res >= 0)&&(res !=696969)) { - alternatedoloffset = res; - char tmp[170]; - snprintf(tmp,sizeof(tmp),"%s %s - %i",tr("It seems that you have some information that will be helpful to us. Please pass this information along to the DEV team.") ,filename,alternatedoloffset); - WindowPrompt(0,tmp,tr("OK")); - } - } - } - } - } - if (alternatedol == 0) { - firstRun = true; // force re-init follow Entries - options2.SetLength(Idx--); // remove this Entry - options2.SetValue(Idx, "%s", tr("Default")); // re-set prev Entry - } else - options2.SetValue(Idx, alternatedname); - } + if (autodol>0) + { + alternatedoloffset = autodol; + snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", tr("AUTO"), autodol); + } + else if (autodol == 0) + alternatedol = 0; // default was chosen + else + { + //check to see if we already know the offset of the correct dol + int autodol = autoSelectDol(filename, false); + //if we do know that offset ask if they want to use it + if (autodol>0) + { + dolchoice = WindowPrompt(0,tr("Do you want to use the alternate DOL that is known to be correct?"),tr("Yes"),tr("Pick from a list"),tr("Cancel")); + if (dolchoice==0) + alternatedol = 0; + else if (dolchoice==1) + { + alternatedoloffset = autodol; + snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", tr("AUTO"),autodol); + } + else if (dolchoice==2) //they want to search for the correct dol themselves + { + int res = DiscBrowse(header); + if ((res >= 0)&&(res !=696969)) //if res==696969 they pressed the back button + alternatedoloffset = res; + } + } + else + { + int res = DiscBrowse(header); + if ((res >= 0)&&(res !=696969)) + { + alternatedoloffset = res; + char tmp[170]; + snprintf(tmp,sizeof(tmp),"%s %s - %i",tr("It seems that you have some information that will be helpful to us. Please pass this information along to the DEV team.") ,filename,alternatedoloffset); + WindowPrompt(0,tmp,tr("OK")); + } + } + } + } + } + if(alternatedol == 0) + { + firstRun = true; // force re-init follow Entries + options2.SetLength(Idx--); // remove this Entry + options2.SetValue(Idx, "%s", tr("Default")); // re-set prev Entry + } + else + options2.SetValue(Idx, alternatedname); + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx, "%s", tr("Block IOS Reload")); - if (ret == Idx && ++reloadblock >= settings_off_on_max) - reloadblock = 0; - options2.SetValue(Idx,"%s", tr(opts_off_on[reloadblock])); - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx, "%s", tr("Block IOS Reload")); + if(ret == Idx && ++reloadblock >= settings_off_on_max) + reloadblock = 0; + options2.SetValue(Idx,"%s", tr(opts_off_on[reloadblock])); + } - firstRun = false; - } - } + firstRun = false; + } + } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - MainButton1.ResetState(); - break; - w.Remove(&saveBtn); - } + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + MainButton1.ResetState(); + break; + w.Remove(&saveBtn); + } - else if (MainButton2.GetState() == STATE_CLICKED) { - char ID[7]; - snprintf (ID,sizeof(ID),"%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - CheatMenu(ID); - MainButton2.ResetState(); - break; - } + else if (MainButton2.GetState() == STATE_CLICKED) + { + char ID[7]; + snprintf (ID,sizeof(ID),"%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); + CheatMenu(ID); + MainButton2.ResetState(); + break; + } - else if (MainButton3.GetState() == STATE_CLICKED) { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton3.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); + else if (MainButton3.GetState() == STATE_CLICKED) + { + MainButton1.SetEffect(EFFECT_FADE, -20); + MainButton2.SetEffect(EFFECT_FADE, -20); + MainButton3.SetEffect(EFFECT_FADE, -20); + MainButton4.SetEffect(EFFECT_FADE, -20); + while (MainButton3.GetEffect() > 0) usleep(50); + HaltGui(); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); + exit = false; + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); + ResumeGui(); - bool firstRun = true; + bool firstRun = true; - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) usleep(50); - while (!exit) { - VIDEO_WaitVSync (); + while (!exit) + { + VIDEO_WaitVSync (); - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } + if (shutdown == 1) + Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); + if (backBtn.GetState() == STATE_CLICKED) + { + backBtn.ResetState(); + exit = true; + break; + } - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } - ret = optionBrowser2.GetClickedOption(); + ret = optionBrowser2.GetClickedOption(); - if (firstRun || ret >= 0) { - int Idx = -1; - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx,"%s", tr("Uninstall Game")); - if (ret == Idx) { - int choice1 = WindowPrompt(tr("Do you really want to delete:"),gameName,tr("Yes"),tr("Cancel")); - if (choice1 == 1 && !mountMethod) { - CFG_forget_game_opt(header->id); - CFG_forget_game_num(header->id); - ret = WBFS_RemoveGame(header->id); - if (ret < 0) { - WindowPrompt( - tr("Can't delete:"), - gameName, - tr("OK")); - } else { - WindowPrompt(tr("Successfully deleted:"),gameName,tr("OK")); - retVal = 1; - } - } else if (choice1 == 0) - optionBrowser2.SetFocus(1); - } - } + if(firstRun || ret >= 0) + { + int Idx = -1; + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx,"%s", tr("Uninstall Game")); + if(ret == Idx) + { + int choice1 = WindowPrompt(tr("Do you really want to delete:"),gameName,tr("Yes"),tr("Cancel")); + if (choice1 == 1 && !mountMethod) + { + CFG_forget_game_opt(header->id); + CFG_forget_game_num(header->id); + ret = WBFS_RemoveGame(header->id); + if (ret < 0) + { + WindowPrompt( + tr("Can't delete:"), + gameName, + tr("OK")); + } + else + { + WindowPrompt(tr("Successfully deleted:"),gameName,tr("OK")); + retVal = 1; + } + } + else if (choice1 == 0) + optionBrowser2.SetFocus(1); + } + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx,"%s", tr("Reset Playcounter")); - if (ret == Idx) { - int result = WindowPrompt(tr("Are you sure?"),0,tr("Yes"),tr("Cancel")); - if (result == 1) { - if (isInserted(bootDevice)) { - struct Game_NUM* game_num = CFG_get_game_num(header->id); - if (game_num) { - favoritevar = game_num->favorite; - playcount = game_num->count; - } else { - favoritevar = 0; - playcount = 0; - } - playcount = 0; - CFG_save_game_num(header->id); - } - } - } - } + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx,"%s", tr("Reset Playcounter")); + if(ret == Idx) + { + int result = WindowPrompt(tr("Are you sure?"),0,tr("Yes"),tr("Cancel")); + if (result == 1) + { + if (isInserted(bootDevice)) + { + struct Game_NUM* game_num = CFG_get_game_num(header->id); + if (game_num) + { + favoritevar = game_num->favorite; + playcount = game_num->count; + } + else + { + favoritevar = 0; + playcount = 0; + } + playcount = 0; + CFG_save_game_num(header->id); + } + } + } + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx,"%s", tr("Delete Cover Artwork")); - if (ret == Idx) { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.png", Settings.covers_path, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx,"%s", tr("Delete Cover Artwork")); + if(ret == Idx) + { + char tmp[200]; + snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.png", Settings.covers_path, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) { - if (checkfile(tmp)) - remove(tmp); - } - } - } + int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); + if (choice1==1) + { + if (checkfile(tmp)) + remove(tmp); + } + } + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx,"%s", tr("Delete Disc Artwork")); - if (ret == Idx) { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.png", Settings.disc_path, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx,"%s", tr("Delete Disc Artwork")); + if(ret == Idx) + { + char tmp[200]; + snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.png", Settings.disc_path, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) { - if (checkfile(tmp)) - remove(tmp); - } - } - } + int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); + if (choice1==1) + { + if (checkfile(tmp)) + remove(tmp); + } + } + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx,"%s", tr("Delete Cheat TXT")); - if (ret == Idx) { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.txt", Settings.TxtCheatcodespath, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx,"%s", tr("Delete Cheat TXT")); + if(ret == Idx) + { + char tmp[200]; + snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.txt", Settings.TxtCheatcodespath, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) { - if (checkfile(tmp)) - remove(tmp); - } - } - } + int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); + if (choice1==1) + { + if (checkfile(tmp)) + remove(tmp); + } + } + } - if (ret == ++Idx || firstRun) { - if (firstRun) options2.SetName(Idx,"%s", tr("Delete Cheat GCT")); - if (ret == Idx) { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.gct", Settings.Cheatcodespath, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); + if(ret == ++Idx || firstRun) + { + if(firstRun) options2.SetName(Idx,"%s", tr("Delete Cheat GCT")); + if(ret == Idx) + { + char tmp[200]; + snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.gct", Settings.Cheatcodespath, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) { - if (checkfile(tmp)) - remove(tmp); - } - } - } + int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); + if (choice1==1) + { + if (checkfile(tmp)) + remove(tmp); + } + } + } - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - pageToDisplay = 1; - MainButton3.ResetState(); - break; - } + firstRun = false; + } + } + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) usleep(50); + pageToDisplay = 1; + MainButton3.ResetState(); + break; + } - else if (MainButton4.GetState() == STATE_CLICKED) { - int choice1 = WindowPrompt(tr("Are you sure?"),0,tr("Yes"),tr("Cancel")); - if (choice1 == 1) { - videoChoice = Settings.video; - viChoice = Settings.vpatch; - languageChoice = Settings.language; - ocarinaChoice = Settings.ocarina; - fix002 = Settings.error002; - countrystrings = Settings.patchcountrystrings; - alternatedol = off; - alternatedoloffset = 0; - reloadblock = off; - if (Settings.cios == ios222) - iosChoice = i222; - else if (Settings.cios == ios250) - iosChoice = i250; - else if (Settings.cios == ios223) - iosChoice = i223; - else - iosChoice = i249; - parentalcontrolChoice = 0; - strcpy(alternatedname, ""); - CFG_forget_game_opt(header->id); - /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database - // if default language is different than language from main settings, reload titles - int opt_langnew = 0; - opt_langnew = Settings.language; - if (Settings.titlesOverride==1 && opt_lang != opt_langnew) - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory - // titles are refreshed in menu.cpp as soon as this function returns - */ - } + else if (MainButton4.GetState() == STATE_CLICKED) + { + int choice1 = WindowPrompt(tr("Are you sure?"),0,tr("Yes"),tr("Cancel")); + if (choice1 == 1) + { + videoChoice = Settings.video; + viChoice = Settings.vpatch; + languageChoice = Settings.language; + ocarinaChoice = Settings.ocarina; + fix002 = Settings.error002; + countrystrings = Settings.patchcountrystrings; + alternatedol = off; + alternatedoloffset = 0; + reloadblock = off; + if (Settings.cios == ios222) + iosChoice = i222; + else if (Settings.cios == ios250) + iosChoice = i250; + else if (Settings.cios == ios223) + iosChoice = i223; + else + iosChoice = i249; + parentalcontrolChoice = 0; + strcpy(alternatedname, ""); + CFG_forget_game_opt(header->id); + /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database + // if default language is different than language from main settings, reload titles + int opt_langnew = 0; + opt_langnew = Settings.language; + if (Settings.titlesOverride==1 && opt_lang != opt_langnew) + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory + // titles are refreshed in menu.cpp as soon as this function returns + */ + } - pageToDisplay = 1; - MainButton4.ResetState(); - break; - } + pageToDisplay = 1; + MainButton4.ResetState(); + break; + } - else if (backBtn.GetState() == STATE_CLICKED) { - menu = MENU_DISCLIST; - pageToDisplay = 0; - break; - } + else if (backBtn.GetState() == STATE_CLICKED) + { + menu = MENU_DISCLIST; + pageToDisplay = 0; + break; + } - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); + else if (homo.GetState() == STATE_CLICKED) + { + cfg_save_global(); + optionBrowser2.SetState(STATE_DISABLED); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - } - } - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); + if (choice == 3) + Sys_LoadMenu(); // Back to System Menu + else if (choice == 2) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); + } + } + } + w.SetEffect(EFFECT_FADE, -20); + while (w.GetEffect()>0) usleep(50); - HaltGui(); + HaltGui(); - mainWindow->RemoveAll(); - mainWindow->Append(bgImg); + mainWindow->RemoveAll(); + mainWindow->Append(bgImg); - ResumeGui(); - return retVal; + ResumeGui(); + return retVal; } diff --git a/source/settings/SettingsPrompts.cpp b/source/settings/SettingsPrompts.cpp index a6fe0652..6a87e2c3 100644 --- a/source/settings/SettingsPrompts.cpp +++ b/source/settings/SettingsPrompts.cpp @@ -38,9 +38,9 @@ bool MenuOGG() { bool returnhere = false; GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; @@ -193,8 +193,8 @@ bool MenuOGG() { if (strcmp("", Settings.oggload_path) && strcmp("notset", Settings.ogg_path)) { bgMusic->Load(Settings.ogg_path); } else { - bgMusic->Load(bg_music_ogg, bg_music_ogg_size, true); - } + bgMusic->Load(bg_music_ogg, bg_music_ogg_size, true); + } bgMusic->Play(); } backBtn.ResetState(); @@ -205,14 +205,14 @@ bool MenuOGG() { choice = WindowPrompt(tr("Loading standard music."),0,tr("OK"), tr("Cancel")); if (choice == 1) { sprintf(Settings.ogg_path, "notset"); - bgMusic->Load(bg_music_ogg, bg_music_ogg_size, true); + bgMusic->Load(bg_music_ogg, bg_music_ogg_size, true); bgMusic->Play(); bgMusic->SetVolume(Settings.volume); cfg_save_global(); } defaultBtn.ResetState(); - if (countoggs > 0) - optionBrowser4.SetFocus(1); + if (countoggs > 0) + optionBrowser4.SetFocus(1); } if (pathBtn.GetState() == STATE_CLICKED) { @@ -321,9 +321,9 @@ int MenuLanguageSelect() { int returnhere = 0; GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; @@ -470,13 +470,13 @@ int MenuLanguageSelect() { sprintf(Settings.language_path, "notset"); cfg_save_global(); gettextCleanUp(); - HaltGui(); + HaltGui(); CFG_Load(); - ResumeGui(); + ResumeGui(); returnhere = 2; } defaultBtn.ResetState(); - //optionBrowser4.SetFocus(1); // commented out to prevent crash + //optionBrowser4.SetFocus(1); // commented out to prevent crash } else if (updateBtn.GetState() == STATE_CLICKED) { @@ -526,8 +526,8 @@ int MenuLanguageSelect() { break; } } - updateBtn.ResetState(); - //optionBrowser4.SetFocus(1); // commented out to prevent crash + updateBtn.ResetState(); + //optionBrowser4.SetFocus(1); // commented out to prevent crash } else if (pathBtn.GetState() == STATE_CLICKED) { @@ -575,9 +575,9 @@ int MenuLanguageSelect() { WindowPrompt(tr("File not found."),tr("Loading standard language."),tr("OK")); } gettextCleanUp(); - HaltGui(); - CFG_Load(); - ResumeGui(); + HaltGui(); + CFG_Load(); + ResumeGui(); returnhere = 2; break; } else { diff --git a/source/settings/cfg.c b/source/settings/cfg.c index c5681dcb..4d89cb2b 100644 --- a/source/settings/cfg.c +++ b/source/settings/cfg.c @@ -198,130 +198,130 @@ void CFG_Default(int widescreen) { // -1 = non forced Mode snprintf(Settings.homebrewapps_path, sizeof(Settings.homebrewapps_path), "%s/apps/", bootDevice); snprintf(Settings.Cheatcodespath, sizeof(Settings.Cheatcodespath), "%s/codes/", bootDevice); snprintf(Settings.TxtCheatcodespath, sizeof(Settings.TxtCheatcodespath), "%s/txtcodes/", bootDevice); - snprintf(Settings.BcaCodepath, sizeof(Settings.BcaCodepath), "%s/bca/", bootDevice); - snprintf(Settings.WipCodepath, sizeof(Settings.WipCodepath), "%s/wip/", bootDevice); + snprintf(Settings.BcaCodepath, sizeof(Settings.BcaCodepath), "%s/bca/", bootDevice); + snprintf(Settings.WipCodepath, sizeof(Settings.WipCodepath), "%s/wip/", bootDevice); snprintf(Settings.dolpath, sizeof(Settings.dolpath), "%s/", bootDevice); snprintf(Settings.oggload_path, sizeof(Settings.oggload_path), "%s/config/backgroundmusic/", bootDevice); sprintf(Settings.ogg_path, "notset"); - } - //always set Theme defaults - //all alignments are left top here - THEME.gamelist_x = 200; - THEME.gamelist_y = 49;//40; - THEME.gamelist_w = 396; - THEME.gamelist_h = 280; - THEME.gamegrid_w = 640; - THEME.gamegrid_h = 400; - THEME.gamegrid_x = 0; - THEME.gamegrid_y = 20; - THEME.gamecarousel_w = 640; - THEME.gamecarousel_h = 400; - THEME.gamecarousel_x = 0; - THEME.gamecarousel_y = -20; + } + //always set Theme defaults + //all alignments are left top here + THEME.gamelist_x = 200; + THEME.gamelist_y = 49;//40; + THEME.gamelist_w = 396; + THEME.gamelist_h = 280; + THEME.gamegrid_w = 640; + THEME.gamegrid_h = 400; + THEME.gamegrid_x = 0; + THEME.gamegrid_y = 20; + THEME.gamecarousel_w = 640; + THEME.gamecarousel_h = 400; + THEME.gamecarousel_x = 0; + THEME.gamecarousel_y = -20; - THEME.covers_x = 26; - THEME.covers_y = 58; + THEME.covers_x = 26; + THEME.covers_y = 58; - THEME.show_id = 1; - THEME.id_x = 68; - THEME.id_y = 305; - THEME.show_region = 1; - THEME.region_x = 68; - THEME.region_y = 30; + THEME.show_id = 1; + THEME.id_x = 68; + THEME.id_y = 305; + THEME.show_region = 1; + THEME.region_x = 68; + THEME.region_y = 30; - THEME.sdcard_x = 160; - THEME.sdcard_y = 395; - THEME.homebrew_x = 410; - THEME.homebrew_y = 405; - THEME.power_x = 576; - THEME.power_y = 355; - THEME.home_x = 489;//215; - THEME.home_y = 371; - THEME.setting_x = 64;//-210 - THEME.setting_y = 371; - THEME.install_x = 16;//-280 - THEME.install_y = 355; + THEME.sdcard_x = 160; + THEME.sdcard_y = 395; + THEME.homebrew_x = 410; + THEME.homebrew_y = 405; + THEME.power_x = 576; + THEME.power_y = 355; + THEME.home_x = 489;//215; + THEME.home_y = 371; + THEME.setting_x = 64;//-210 + THEME.setting_y = 371; + THEME.install_x = 16;//-280 + THEME.install_y = 355; - THEME.clock = (GXColor) {138, 138, 138, 240}; - THEME.clock_align = CFG_ALIGN_CENTRE; - THEME.clock_x = 0; - THEME.clock_y = 335;//330; + THEME.clock = (GXColor) {138, 138, 138, 240}; + THEME.clock_align = CFG_ALIGN_CENTRE; + THEME.clock_x = 0; + THEME.clock_y = 335;//330; - THEME.info = (GXColor) { 55, 190, 237, 255}; - THEME.show_hddinfo = 1; //default - THEME.hddinfo_align = CFG_ALIGN_CENTRE; - THEME.hddinfo_x = 0; - THEME.hddinfo_y = 400; - THEME.show_gamecount = 1; //default - THEME.gamecount_align = CFG_ALIGN_CENTRE; - THEME.gamecount_x = 0; - THEME.gamecount_y = 420; + THEME.info = (GXColor) {55, 190, 237, 255}; + THEME.show_hddinfo = 1; //default + THEME.hddinfo_align = CFG_ALIGN_CENTRE; + THEME.hddinfo_x = 0; + THEME.hddinfo_y = 400; + THEME.show_gamecount = 1; //default + THEME.gamecount_align = CFG_ALIGN_CENTRE; + THEME.gamecount_x = 0; + THEME.gamecount_y = 420; - THEME.show_tooltip = 1; //1 means use settings, 0 means force turn off - THEME.tooltipAlpha = 255; + THEME.show_tooltip = 1; //1 means use settings, 0 means force turn off + THEME.tooltipAlpha = 255; - THEME.prompttext = (GXColor) {0, 0, 0, 255}; - THEME.settingstext = (GXColor) {0, 0, 0, 255}; - THEME.gametext = (GXColor) {0, 0, 0, 255}; + THEME.prompttext = (GXColor) {0, 0, 0, 255}; + THEME.settingstext = (GXColor) {0, 0, 0, 255}; + THEME.gametext = (GXColor) {0, 0, 0, 255}; - THEME.pagesize = 9; + THEME.pagesize = 9; - THEME.gamelist_favorite_x = CFG.widescreen ? 256 : 220; - THEME.gamelist_favorite_y = 13; - THEME.gamelist_search_x = CFG.widescreen ? 288 : 260; - THEME.gamelist_search_y = 13; - THEME.gamelist_abc_x = CFG.widescreen ? 320 : 300; - THEME.gamelist_abc_y = 13; - THEME.gamelist_count_x = CFG.widescreen ? 352 : 340; - THEME.gamelist_count_y = 13; - THEME.gamelist_list_x = CFG.widescreen ? 384 : 380; - THEME.gamelist_list_y = 13; - THEME.gamelist_grid_x = CFG.widescreen ? 416 : 420; - THEME.gamelist_grid_y = 13; - THEME.gamelist_carousel_x = CFG.widescreen ? 448 : 460; - THEME.gamelist_carousel_y = 13; - THEME.gamelist_lock_x = CFG.widescreen ? 480 : 500; - THEME.gamelist_lock_y = 13; - THEME.gamelist_dvd_x = CFG.widescreen ? 512 : 540; - THEME.gamelist_dvd_y = 13; + THEME.gamelist_favorite_x = CFG.widescreen ? 256 : 220; + THEME.gamelist_favorite_y = 13; + THEME.gamelist_search_x = CFG.widescreen ? 288 : 260; + THEME.gamelist_search_y = 13; + THEME.gamelist_abc_x = CFG.widescreen ? 320 : 300; + THEME.gamelist_abc_y = 13; + THEME.gamelist_count_x = CFG.widescreen ? 352 : 340; + THEME.gamelist_count_y = 13; + THEME.gamelist_list_x = CFG.widescreen ? 384 : 380; + THEME.gamelist_list_y = 13; + THEME.gamelist_grid_x = CFG.widescreen ? 416 : 420; + THEME.gamelist_grid_y = 13; + THEME.gamelist_carousel_x = CFG.widescreen ? 448 : 460; + THEME.gamelist_carousel_y = 13; + THEME.gamelist_lock_x = CFG.widescreen ? 480 : 500; + THEME.gamelist_lock_y = 13; + THEME.gamelist_dvd_x = CFG.widescreen ? 512 : 540; + THEME.gamelist_dvd_y = 13; - THEME.gamegrid_favorite_x = CFG.widescreen ? 192 : 160; - THEME.gamegrid_favorite_y = 13; - THEME.gamegrid_search_x = CFG.widescreen ? 224 : 200; - THEME.gamegrid_search_y = 13; - THEME.gamegrid_abc_x = CFG.widescreen ? 256 : 240; - THEME.gamegrid_abc_y = 13; - THEME.gamegrid_count_x = CFG.widescreen ? 288 : 280; - THEME.gamegrid_count_y = 13; - THEME.gamegrid_list_x = CFG.widescreen ? 320 : 320; - THEME.gamegrid_list_y = 13; - THEME.gamegrid_grid_x = CFG.widescreen ? 352 : 360; - THEME.gamegrid_grid_y = 13; - THEME.gamegrid_carousel_x = CFG.widescreen ? 384 : 400; - THEME.gamegrid_carousel_y = 13; - THEME.gamegrid_lock_x = CFG.widescreen ? 416 : 440; - THEME.gamegrid_lock_y = 13; - THEME.gamegrid_dvd_x = CFG.widescreen ? 448 : 480; - THEME.gamegrid_dvd_y = 13; + THEME.gamegrid_favorite_x = CFG.widescreen ? 192 : 160; + THEME.gamegrid_favorite_y = 13; + THEME.gamegrid_search_x = CFG.widescreen ? 224 : 200; + THEME.gamegrid_search_y = 13; + THEME.gamegrid_abc_x = CFG.widescreen ? 256 : 240; + THEME.gamegrid_abc_y = 13; + THEME.gamegrid_count_x = CFG.widescreen ? 288 : 280; + THEME.gamegrid_count_y = 13; + THEME.gamegrid_list_x = CFG.widescreen ? 320 : 320; + THEME.gamegrid_list_y = 13; + THEME.gamegrid_grid_x = CFG.widescreen ? 352 : 360; + THEME.gamegrid_grid_y = 13; + THEME.gamegrid_carousel_x = CFG.widescreen ? 384 : 400; + THEME.gamegrid_carousel_y = 13; + THEME.gamegrid_lock_x = CFG.widescreen ? 416 : 440; + THEME.gamegrid_lock_y = 13; + THEME.gamegrid_dvd_x = CFG.widescreen ? 448 : 480; + THEME.gamegrid_dvd_y = 13; - THEME.gamecarousel_favorite_x = CFG.widescreen ? 192 : 160; - THEME.gamecarousel_favorite_y = 13; - THEME.gamecarousel_search_x = CFG.widescreen ? 224 : 200; - THEME.gamecarousel_search_y = 13; - THEME.gamecarousel_abc_x = CFG.widescreen ? 256 : 240; - THEME.gamecarousel_abc_y = 13; - THEME.gamecarousel_count_x = CFG.widescreen ? 288 : 280; - THEME.gamecarousel_count_y = 13; - THEME.gamecarousel_list_x = CFG.widescreen ? 320 : 320; - THEME.gamecarousel_list_y = 13; - THEME.gamecarousel_grid_x = CFG.widescreen ? 352 : 360; - THEME.gamecarousel_grid_y = 13; - THEME.gamecarousel_carousel_x = CFG.widescreen ? 384 : 400; - THEME.gamecarousel_carousel_y = 13; - THEME.gamecarousel_lock_x = CFG.widescreen ? 416 : 440; - THEME.gamecarousel_lock_y = 13; - THEME.gamecarousel_dvd_x = CFG.widescreen ? 448 : 480; - THEME.gamecarousel_dvd_y = 13; + THEME.gamecarousel_favorite_x = CFG.widescreen ? 192 : 160; + THEME.gamecarousel_favorite_y = 13; + THEME.gamecarousel_search_x = CFG.widescreen ? 224 : 200; + THEME.gamecarousel_search_y = 13; + THEME.gamecarousel_abc_x = CFG.widescreen ? 256 : 240; + THEME.gamecarousel_abc_y = 13; + THEME.gamecarousel_count_x = CFG.widescreen ? 288 : 280; + THEME.gamecarousel_count_y = 13; + THEME.gamecarousel_list_x = CFG.widescreen ? 320 : 320; + THEME.gamecarousel_list_y = 13; + THEME.gamecarousel_grid_x = CFG.widescreen ? 352 : 360; + THEME.gamecarousel_grid_y = 13; + THEME.gamecarousel_carousel_x = CFG.widescreen ? 384 : 400; + THEME.gamecarousel_carousel_y = 13; + THEME.gamecarousel_lock_x = CFG.widescreen ? 416 : 440; + THEME.gamecarousel_lock_y = 13; + THEME.gamecarousel_dvd_x = CFG.widescreen ? 448 : 480; + THEME.gamecarousel_dvd_y = 13; } void Global_Default(void) { @@ -358,37 +358,39 @@ void Global_Default(void) { snprintf(Settings.db_language, sizeof(Settings.db_language), empty); Settings.db_JPtoEN = 0; Settings.screensaver = 3; - Settings.partition = -1; - Settings.marknewtitles = 1; - Settings.FatInstallToDir = 0; - Settings.partitions_to_install = install_game_only; - Settings.fullcopy = 0; - Settings.beta_upgrades = 0; + Settings.partition = -1; + Settings.marknewtitles = 1; + Settings.FatInstallToDir = 0; + Settings.partitions_to_install = install_game_only; + Settings.fullcopy = 0; + Settings.beta_upgrades = 0; - memset(&Settings.parental, 0, sizeof(struct SParental)); + memset(&Settings.parental, 0, sizeof(struct SParental)); - char buf[0x4a]; - CONF_Init(); - s32 res = CONF_Get("IPL.PC", buf, 0x4A); - if (res > 0) { - if (buf[2] != 0x14) { - Settings.parental.enabled = 1; - Settings.parental.rating = buf[2]; - } - Settings.parental.question = buf[7]; - memcpy(Settings.parental.pin, buf + 3, 4); - memcpy(Settings.parental.answer, buf + 8, 32); - } - Settings.godmode = (Settings.parental.enabled == 0) ? 1 : 0; + char buf[0x4a]; + CONF_Init(); + s32 res = CONF_Get("IPL.PC", buf, 0x4A); + if (res > 0) { + if (buf[2] != 0x14) { + Settings.parental.enabled = 1; + Settings.parental.rating = buf[2]; + } + Settings.parental.question = buf[7]; + memcpy(Settings.parental.pin, buf + 3, 4); + memcpy(Settings.parental.answer, buf + 8, 32); + } + Settings.godmode = (Settings.parental.enabled == 0) ? 1 : 0; } -char *cfg_get_title(u8 *id) { - if (!id) +char *cfg_get_title(u8 *id) +{ + if(!id) return NULL; int i; - for (i=0; iid); @@ -405,12 +408,13 @@ char *get_title(struct discHdr *header) { return header->title; } -void title_set(char *id, char *title) { - if (!id || !title) +void title_set(char *id, char *title) +{ + if(!id || !title) return; - if (!cfg_title) - cfg_title = (struct ID_Title *) malloc(sizeof(struct ID_Title)); + if(!cfg_title) + cfg_title = (struct ID_Title *) malloc(sizeof(struct ID_Title)); char *idt = cfg_get_title((u8*)id); if (idt) { @@ -436,8 +440,8 @@ void title_set(char *id, char *title) { } void titles_default() { - int i; - for (i=0; iiosreloadblock = reloadblock; game->patchcountrystrings = countrystrings; game->loadalternatedol = alternatedol; - if (game->loadalternatedol == 0) { - alternatedoloffset = 0; - strcpy(alternatedname, ""); - } + if (game->loadalternatedol == 0) { + alternatedoloffset = 0; + strcpy(alternatedname, ""); + } game->alternatedolstart = alternatedoloffset; strlcpy(game->alternatedolname, alternatedname,sizeof(game->alternatedolname)); } @@ -1362,8 +1372,8 @@ bool cfg_save_global() { // save global settings fprintf(f, "theme_downloadpath = %s\n ", Settings.theme_downloadpath); fprintf(f, "homebrewapps_path = %s\n ", Settings.homebrewapps_path); fprintf(f, "Cheatcodespath = %s\n ", Settings.Cheatcodespath); - fprintf(f, "BcaCodepath = %s\n ", Settings.BcaCodepath); - fprintf(f, "WipCodepath = %s\n ", Settings.WipCodepath); + fprintf(f, "BcaCodepath = %s\n ", Settings.BcaCodepath); + fprintf(f, "WipCodepath = %s\n ", Settings.WipCodepath); fprintf(f, "titlesOverride = %d\n ", Settings.titlesOverride); //fprintf(f, "db_url = %s\n ", Settings.db_url); //fprintf(f, "db_JPtoEN = %d\n ", Settings.db_JPtoEN); @@ -1373,12 +1383,12 @@ bool cfg_save_global() { // save global settings fprintf(f, "error002 = %d\n ", Settings.error002); fprintf(f, "autonetwork = %d\n ", Settings.autonetwork); fprintf(f, "discart = %d\n ", Settings.discart); - fprintf(f, "partition = %d\n ", Settings.partition); - fprintf(f, "marknewtitles = %d\n ", Settings.marknewtitles); - fprintf(f, "fatInstallToDir = %d\n ", Settings.FatInstallToDir); - fprintf(f, "partitions = %d\n ", Settings.partitions_to_install); - fprintf(f, "fullcopy = %d\n ", Settings.fullcopy); - fprintf(f, "beta_upgrades = %d\n ", Settings.beta_upgrades); + fprintf(f, "partition = %d\n ", Settings.partition); + fprintf(f, "marknewtitles = %d\n ", Settings.marknewtitles); + fprintf(f, "fatInstallToDir = %d\n ", Settings.FatInstallToDir); + fprintf(f, "partitions = %d\n ", Settings.partitions_to_install); + fprintf(f, "fullcopy = %d\n ", Settings.fullcopy); + fprintf(f, "beta_upgrades = %d\n ", Settings.beta_upgrades); fclose(f); return true; } @@ -1709,7 +1719,7 @@ bool cfg_load_global() { Settings.gamesoundvolume = 80; Settings.titlesOverride = 1; - Settings.partition = -1; + Settings.partition = -1; char * empty = ""; snprintf(Settings.db_url, sizeof(Settings.db_url), empty); snprintf(Settings.db_language, sizeof(Settings.db_language), empty); @@ -1797,26 +1807,25 @@ void CFG_Load(void) { cfg_parsefile(pathname, &widescreen_set); //first set widescreen cfg_parsefile(pathname, &path_set); //then set config and layout options - WorkAroundIconSet=0; - WorkAroundBarOffset=100; // set Workaroundstuff to defaults - CLEAR_wCOORD_FLAGS; - snprintf(pathname, sizeof(pathname), "%sGXtheme.cfg", CFG.theme_path); + WorkAroundIconSet=0; WorkAroundBarOffset=100; // set Workaroundstuff to defaults + CLEAR_wCOORD_FLAGS; + snprintf(pathname, sizeof(pathname), "%sGXtheme.cfg", CFG.theme_path); cfg_parsefile(pathname, &theme_set); //finally set theme information - // set GUI language, use Wii's language setting if language is set to default - int wiilang; - bool langisdefault = false; - wiilang = CONF_GetLanguage(); - if (!strcmp("notset", Settings.language_path)) { - snprintf(Settings.language_path, sizeof(Settings.language_path), "%s%s.lang", Settings.languagefiles_path, map_get_name(map_language, wiilang + 1)); // + 1 because because CONF_LANG starts at 0 - if (!checkfile(Settings.language_path)) { - sprintf(Settings.language_path, "notset"); - } - gettextLoadLanguage(Settings.language_path); - langisdefault = true; - } - snprintf(pathname, sizeof(pathname), Settings.language_path); - gettextLoadLanguage(pathname); + // set GUI language, use Wii's language setting if language is set to default + int wiilang; + bool langisdefault = false; + wiilang = CONF_GetLanguage(); + if (!strcmp("notset", Settings.language_path)) { + snprintf(Settings.language_path, sizeof(Settings.language_path), "%s%s.lang", Settings.languagefiles_path, map_get_name(map_language, wiilang + 1)); // + 1 because because CONF_LANG starts at 0 + if (!checkfile(Settings.language_path)) { + sprintf(Settings.language_path, "notset"); + } + gettextLoadLanguage(Settings.language_path); + langisdefault = true; + } + snprintf(pathname, sizeof(pathname), Settings.language_path); + gettextLoadLanguage(pathname); // cfg_parsefile(pathname, &language_set); @@ -1830,36 +1839,36 @@ void CFG_Load(void) { Global_Default(); //global default depends on theme information CFG_LoadGlobal(); - // use GUI language for the database (Settings.db_language is used for game info/titles and covers) - char * languagefile; + // use GUI language for the database (Settings.db_language is used for game info/titles and covers) + char * languagefile; languagefile = strrchr(Settings.language_path, '/')+1; - int mainlangid = -1; - int i; - if (strcmp("notset", Settings.language_path)) { - for (i=0; map_language[i].name != NULL; i++) { - if (strstr(languagefile, map_language[i].name) != NULL) { - mainlangid = i - 1; // - 1 because CONF_LANG starts at 0 - break; - } - } - } else { + int mainlangid = -1; + int i; + if(strcmp("notset", Settings.language_path)) { + for (i=0; map_language[i].name != NULL; i++) { + if (strstr(languagefile, map_language[i].name) != NULL) { + mainlangid = i - 1; // - 1 because CONF_LANG starts at 0 + break; + } + } + } else { mainlangid = wiilang; - } - GetLanguageToLangCode(&mainlangid, Settings.db_language); + } + GetLanguageToLangCode(&mainlangid, Settings.db_language); - // set language code for countries that don't have a language setting on the Wii - if (!strcmp(Settings.db_language,"")) { - if (strstr(languagefile, "portuguese") != NULL) - strcpy(Settings.db_language,"PT"); - } - if (CONF_GetArea() == CONF_AREA_AUS) - strcpy(Settings.db_language,"AU"); + // set language code for countries that don't have a language setting on the Wii + if (!strcmp(Settings.db_language,"")) { + if (strstr(languagefile, "portuguese") != NULL) + strcpy(Settings.db_language,"PT"); + } + if (CONF_GetArea() == CONF_AREA_AUS) + strcpy(Settings.db_language,"AU"); - // if GUI language is set to default Settings.language_path needs to remain "notset" (if the detected setting was kept detection wouldn't work next time) - if (langisdefault) - sprintf(Settings.language_path, "notset"); + // if GUI language is set to default Settings.language_path needs to remain "notset" (if the detected setting was kept detection wouldn't work next time) + if (langisdefault) + sprintf(Settings.language_path, "notset"); - Settings.godmode = (Settings.parental.enabled == 0 && (Settings.parentalcontrol == 0 || strlen(Settings.unlockCode) == 0)) ? 1 : 0; + Settings.godmode = (Settings.parental.enabled == 0 && (Settings.parentalcontrol == 0 || strlen(Settings.unlockCode) == 0)) ? 1 : 0; } void CFG_LoadGlobal(void) { @@ -1868,10 +1877,12 @@ void CFG_LoadGlobal(void) { cfg_parsefile(GXGlobal_cfg, &global_cfg_set); } -void CFG_Cleanup(void) { +void CFG_Cleanup(void) +{ int i = 0; - for (i = 0; i < num_title; i++) { - if (cfg_title[i].title) + for(i = 0; i < num_title; i++) + { + if(cfg_title[i].title) free(cfg_title[i].title); cfg_title[i].title = NULL; } @@ -1885,8 +1896,8 @@ void CFG_Cleanup(void) { /* map language id (or Wii language settting if langid is set to -1) to language code. CONF_LANG_JAPANESE = 0, not 1 */ void GetLanguageToLangCode(int *langid, char *langcode) { - if (langid < 0) - *langid = CONF_GetLanguage(); + if (langid < 0) + *langid = CONF_GetLanguage(); switch (*langid) { case CONF_LANG_JAPANESE: diff --git a/source/settings/cfg.h b/source/settings/cfg.h index 939e2685..3aac08ba 100644 --- a/source/settings/cfg.h +++ b/source/settings/cfg.h @@ -44,434 +44,434 @@ extern "C" { extern char bootDevice[10]; //extern char *cfg_path; - struct CFG { - short widescreen; - char theme_path[100]; - }; + struct CFG { + short widescreen; + char theme_path[100]; + }; - struct THEME { - short gamelist_x; - short gamelist_y; - short gamelist_w; - short gamelist_h; - short gamegrid_x; - short gamegrid_y; - short gamegrid_w; - short gamegrid_h; - short gamecarousel_x; - short gamecarousel_y; - short gamecarousel_w; - short gamecarousel_h; + struct THEME { + short gamelist_x; + short gamelist_y; + short gamelist_w; + short gamelist_h; + short gamegrid_x; + short gamegrid_y; + short gamegrid_w; + short gamegrid_h; + short gamecarousel_x; + short gamecarousel_y; + short gamecarousel_w; + short gamecarousel_h; - short covers_x; - short covers_y; + short covers_x; + short covers_y; - short show_id; - short id_x; - short id_y; - short show_region; - short region_x; - short region_y; + short show_id; + short id_x; + short id_y; + short show_region; + short region_x; + short region_y; - short sdcard_x; - short sdcard_y; - short homebrew_x; - short homebrew_y; - short power_x; - short power_y; - short home_x; - short home_y; - short setting_x; - short setting_y; - short install_x; - short install_y; - GXColor clock; - short clock_align; - short clock_x; - short clock_y; + short sdcard_x; + short sdcard_y; + short homebrew_x; + short homebrew_y; + short power_x; + short power_y; + short home_x; + short home_y; + short setting_x; + short setting_y; + short install_x; + short install_y; + GXColor clock; + short clock_align; + short clock_x; + short clock_y; - GXColor info; - short show_hddinfo; - short hddinfo_align; - short hddinfo_x; - short hddinfo_y; + GXColor info; + short show_hddinfo; + short hddinfo_align; + short hddinfo_x; + short hddinfo_y; - short show_gamecount; - short gamecount_align; - short gamecount_x; - short gamecount_y; + short show_gamecount; + short gamecount_align; + short gamecount_x; + short gamecount_y; - short show_tooltip; - int tooltipAlpha; + short show_tooltip; + int tooltipAlpha; - GXColor prompttext; - GXColor settingstext; - GXColor gametext; - short pagesize; + GXColor prompttext; + GXColor settingstext; + GXColor gametext; + short pagesize; - // Toolbar Icons in GameList - /* - short favorite_x; - short favorite_y; - short search_x; - short search_y; - short abc_x; - short abc_y; - short count_x; - short count_y; - short list_x; - short list_y; - short grid_x; - short grid_y; - short carousel_x; - short carousel_y; - short sortBarOffset; - */ - // Toolbar Icons in GameList - short gamelist_favorite_x; - short gamelist_favorite_y; - short gamelist_search_x; - short gamelist_search_y; - short gamelist_abc_x; - short gamelist_abc_y; - short gamelist_count_x; - short gamelist_count_y; - short gamelist_list_x; - short gamelist_list_y; - short gamelist_grid_x; - short gamelist_grid_y; - short gamelist_carousel_x; - short gamelist_carousel_y; - short gamelist_dvd_x; - short gamelist_dvd_y; - short gamelist_lock_x; - short gamelist_lock_y; - // Toolbar Icons in GameGrid - short gamegrid_favorite_x; - short gamegrid_favorite_y; - short gamegrid_search_x; - short gamegrid_search_y; - short gamegrid_abc_x; - short gamegrid_abc_y; - short gamegrid_count_x; - short gamegrid_count_y; - short gamegrid_list_x; - short gamegrid_list_y; - short gamegrid_grid_x; - short gamegrid_grid_y; - short gamegrid_carousel_x; - short gamegrid_carousel_y; - short gamegrid_dvd_x; - short gamegrid_dvd_y; - short gamegrid_lock_x; - short gamegrid_lock_y; - // Toolbar Icons in GameCarousel - short gamecarousel_favorite_x; - short gamecarousel_favorite_y; - short gamecarousel_search_x; - short gamecarousel_search_y; - short gamecarousel_abc_x; - short gamecarousel_abc_y; - short gamecarousel_count_x; - short gamecarousel_count_y; - short gamecarousel_list_x; - short gamecarousel_list_y; - short gamecarousel_grid_x; - short gamecarousel_grid_y; - short gamecarousel_carousel_x; - short gamecarousel_carousel_y; - short gamecarousel_dvd_x; - short gamecarousel_dvd_y; - short gamecarousel_lock_x; - short gamecarousel_lock_y; - }; + // Toolbar Icons in GameList + /* + short favorite_x; + short favorite_y; + short search_x; + short search_y; + short abc_x; + short abc_y; + short count_x; + short count_y; + short list_x; + short list_y; + short grid_x; + short grid_y; + short carousel_x; + short carousel_y; + short sortBarOffset; + */ + // Toolbar Icons in GameList + short gamelist_favorite_x; + short gamelist_favorite_y; + short gamelist_search_x; + short gamelist_search_y; + short gamelist_abc_x; + short gamelist_abc_y; + short gamelist_count_x; + short gamelist_count_y; + short gamelist_list_x; + short gamelist_list_y; + short gamelist_grid_x; + short gamelist_grid_y; + short gamelist_carousel_x; + short gamelist_carousel_y; + short gamelist_dvd_x; + short gamelist_dvd_y; + short gamelist_lock_x; + short gamelist_lock_y; + // Toolbar Icons in GameGrid + short gamegrid_favorite_x; + short gamegrid_favorite_y; + short gamegrid_search_x; + short gamegrid_search_y; + short gamegrid_abc_x; + short gamegrid_abc_y; + short gamegrid_count_x; + short gamegrid_count_y; + short gamegrid_list_x; + short gamegrid_list_y; + short gamegrid_grid_x; + short gamegrid_grid_y; + short gamegrid_carousel_x; + short gamegrid_carousel_y; + short gamegrid_dvd_x; + short gamegrid_dvd_y; + short gamegrid_lock_x; + short gamegrid_lock_y; + // Toolbar Icons in GameCarousel + short gamecarousel_favorite_x; + short gamecarousel_favorite_y; + short gamecarousel_search_x; + short gamecarousel_search_y; + short gamecarousel_abc_x; + short gamecarousel_abc_y; + short gamecarousel_count_x; + short gamecarousel_count_y; + short gamecarousel_list_x; + short gamecarousel_list_y; + short gamecarousel_grid_x; + short gamecarousel_grid_y; + short gamecarousel_carousel_x; + short gamecarousel_carousel_y; + short gamecarousel_dvd_x; + short gamecarousel_dvd_y; + short gamecarousel_lock_x; + short gamecarousel_lock_y; + }; - extern struct CFG CFG; - extern struct THEME THEME; - extern u8 ocarinaChoice; - extern u16 playcnt; - extern u8 videoChoice; - extern u8 languageChoice; - extern u8 viChoice; - extern u8 iosChoice; - extern u8 parentalcontrolChoice; - extern u8 fix002; - extern u8 reloadblock; - extern u8 countrystrings; - extern u8 alternatedol; - extern u32 alternatedoloffset; - extern u8 xflip; - extern u8 qboot; - extern u8 sort; - extern u8 fave; - extern u8 wsprompt; - extern u8 keyset; - extern u8 gameDisplay; - extern u16 playcount; - extern u8 favoritevar; - extern char alternatedname[40]; + extern struct CFG CFG; + extern struct THEME THEME; + extern u8 ocarinaChoice; + extern u16 playcnt; + extern u8 videoChoice; + extern u8 languageChoice; + extern u8 viChoice; + extern u8 iosChoice; + extern u8 parentalcontrolChoice; + extern u8 fix002; + extern u8 reloadblock; + extern u8 countrystrings; + extern u8 alternatedol; + extern u32 alternatedoloffset; + extern u8 xflip; + extern u8 qboot; + extern u8 sort; + extern u8 fave; + extern u8 wsprompt; + extern u8 keyset; + extern u8 gameDisplay; + extern u16 playcount; + extern u8 favoritevar; + extern char alternatedname[40]; - struct Game_CFG { - u8 id[8]; - u8 video; - u8 language; - u8 ocarina; - u8 vipatch; - u8 ios; - u8 parentalcontrol; - u8 errorfix002; - u8 iosreloadblock; - u8 loadalternatedol; - u32 alternatedolstart; - u8 patchcountrystrings; - char alternatedolname[40]; - }; - struct Game_NUM { - u8 id[8]; - u8 favorite; - u16 count; - }; + struct Game_CFG { + u8 id[8]; + u8 video; + u8 language; + u8 ocarina; + u8 vipatch; + u8 ios; + u8 parentalcontrol; + u8 errorfix002; + u8 iosreloadblock; + u8 loadalternatedol; + u32 alternatedolstart; + u8 patchcountrystrings; + char alternatedolname[40]; + }; + struct Game_NUM { + u8 id[8]; + u8 favorite; + u16 count; + }; - void CFG_Default(int widescreen); // -1 = non forced mode - void CFG_Load(void); - struct Game_CFG* CFG_get_game_opt(u8 *id); - struct Game_NUM* CFG_get_game_num(u8 *id); - bool CFG_save_game_opt(u8 *id); - bool CFG_save_game_num(u8 *id); - bool CFG_reset_all_playcounters(); - bool CFG_forget_game_opt(u8 *id); - bool CFG_forget_game_num(u8 *id); + void CFG_Default(int widescreen); // -1 = non forced mode + void CFG_Load(void); + struct Game_CFG* CFG_get_game_opt(u8 *id); + struct Game_NUM* CFG_get_game_num(u8 *id); + bool CFG_save_game_opt(u8 *id); + bool CFG_save_game_num(u8 *id); + bool CFG_reset_all_playcounters(); + bool CFG_forget_game_opt(u8 *id); + bool CFG_forget_game_num(u8 *id); - enum { - ConsoleLangDefault=0, - jap, - eng, - ger, - fren, - esp, - it, - dut, - schin, - tchin, - kor, - settings_language_max // always the last entry - }; + enum { + ConsoleLangDefault=0, + jap, + eng, + ger, + fren, + esp, + it, + dut, + schin, + tchin, + kor, + settings_language_max // always the last entry + }; - enum { - systemdefault=0, - discdefault, - patch, - pal50, - pal60, - ntsc, - settings_video_max // always the last entry - }; + enum { + systemdefault=0, + discdefault, + patch, + pal50, + pal60, + ntsc, + settings_video_max // always the last entry + }; - enum { - off=0, - on, - settings_off_on_max // always the last entry - }; - enum { - //off=0, - //on, - anti=2, - settings_error002_max // always the last entry - }; + enum { + off=0, + on, + settings_off_on_max // always the last entry + }; + enum { + //off=0, + //on, + anti=2, + settings_error002_max // always the last entry + }; - enum { - wiilight_off=0, - wiilight_on, - wiilight_forInstall, - settings_wiilight_max // always the last entry - }; + enum { + wiilight_off=0, + wiilight_on, + wiilight_forInstall, + settings_wiilight_max // always the last entry + }; - enum { - GameID, - GameRegion, - Both, - Neither, - settings_sinfo_max // always the last entry - }; + enum { + GameID, + GameRegion, + Both, + Neither, + settings_sinfo_max // always the last entry + }; - enum { - i249=0, - i222, - i223, - i250, - settings_ios_max // always the last entry - }; + enum { + i249=0, + i222, + i223, + i250, + settings_ios_max // always the last entry + }; - enum { - ios249=0, - ios222, - ios223, - ios250, - settings_cios_max // always the last entry - }; + enum { + ios249=0, + ios222, + ios223, + ios250, + settings_cios_max // always the last entry + }; - enum { - hr12=0, - hr24, - Off, - settings_clock_max // always the last entry - }; - enum { - all=0, - pcount, - }; + enum { + hr12=0, + hr24, + Off, + settings_clock_max // always the last entry + }; + enum { + all=0, + pcount, + }; - enum { - RumbleOff=0, - RumbleOn, - settings_rumble_max // always the last entry - }; + enum { + RumbleOff=0, + RumbleOn, + settings_rumble_max // always the last entry + }; - enum { - TooltipsOff=0, - TooltipsOn, - settings_tooltips_max // always the last entry - }; + enum { + TooltipsOff=0, + TooltipsOn, + settings_tooltips_max // always the last entry + }; - enum { - min3=1, - min5, - min10, - min20, - min30, - min60, - settings_screensaver_max // always the last entry - }; + enum { + min3=1, + min5, + min10, + min20, + min30, + min60, + settings_screensaver_max // always the last entry + }; - enum { - no=0, - yes, - sysmenu, - wtf, - disk3d, - settings_xflip_max // always the last entry - }; - enum { - us=0, - qwerty, - dvorak, - euro, - azerty, - settings_keyset_max // always the last entry - }; - enum { - list, - grid, - carousel, - settings_display_max - }; - enum { - scrollDefault, - scrollMarquee, - settings_scrolleffect_max // always the last entry - }; - enum { - install_game_only, - install_all, - install_all_but_update, - settings_partitions_max // always the last entry - }; - enum { - not_install_to_dir, - install_to_gameid_name, - install_to_name_gameid, - settings_installdir_max // always the last entry - }; - struct SParental { - u8 enabled; - u8 rating; - u8 pin[4]; - u8 question; - wchar_t answer[32]; // IS WCHAR! - }; - struct SSettings { - u8 video; - u8 language; - u8 ocarina; - u8 vpatch; - int ios; - u8 sinfo; - u8 hddinfo; - u8 rumble; - u8 xflip; - int volume; - int sfxvolume; - int gamesoundvolume; - u8 tooltips; - char unlockCode[20]; - u8 parentalcontrol; - u8 cios; - u8 qboot; - u8 wsprompt; - u8 keyset; - u8 sort; - u8 fave; - u8 wiilight; - u8 gameDisplay; - u8 patchcountrystrings; - u8 screensaver; - s8 partition; - short godmode; - char covers_path[100]; - char covers2d_path[100]; - char theme_path[100]; - char wtheme_path[100]; + enum { + no=0, + yes, + sysmenu, + wtf, + disk3d, + settings_xflip_max // always the last entry + }; + enum { + us=0, + qwerty, + dvorak, + euro, + azerty, + settings_keyset_max // always the last entry + }; + enum { + list, + grid, + carousel, + settings_display_max + }; + enum { + scrollDefault, + scrollMarquee, + settings_scrolleffect_max // always the last entry + }; + enum { + install_game_only, + install_all, + install_all_but_update, + settings_partitions_max // always the last entry + }; + enum { + not_install_to_dir, + install_to_gameid_name, + install_to_name_gameid, + settings_installdir_max // always the last entry + }; + struct SParental { + u8 enabled; + u8 rating; + u8 pin[4]; + u8 question; + wchar_t answer[32]; // IS WCHAR! + }; + struct SSettings { + u8 video; + u8 language; + u8 ocarina; + u8 vpatch; + int ios; + u8 sinfo; + u8 hddinfo; + u8 rumble; + u8 xflip; + int volume; + int sfxvolume; + int gamesoundvolume; + u8 tooltips; + char unlockCode[20]; + u8 parentalcontrol; + u8 cios; + u8 qboot; + u8 wsprompt; + u8 keyset; + u8 sort; + u8 fave; + u8 wiilight; + u8 gameDisplay; + u8 patchcountrystrings; + u8 screensaver; + s8 partition; + short godmode; + char covers_path[100]; + char covers2d_path[100]; + char theme_path[100]; + char wtheme_path[100]; char theme_downloadpath[100]; - char disc_path[100]; - char titlestxt_path[100]; - char language_path[100]; - char languagefiles_path[100]; - char oggload_path[100]; - char ogg_path[150]; - char dolpath[150]; - char update_path[150]; - char homebrewapps_path[150]; - char selected_homebrew[200]; - char Cheatcodespath[100]; - char TxtCheatcodespath[100]; - char BcaCodepath[100]; - char WipCodepath[100]; - short error002; - u8 titlesOverride; // db_titles - char db_url[200]; - char db_language[20]; - u8 db_JPtoEN; - u8 gridRows; - u8 autonetwork; - u8 discart; - short gamesound; - u8 marknewtitles; - u8 FatInstallToDir; - u8 partitions_to_install; - u8 fullcopy; - u8 beta_upgrades; - struct SParental parental; - }; - extern struct SSettings Settings; + char disc_path[100]; + char titlestxt_path[100]; + char language_path[100]; + char languagefiles_path[100]; + char oggload_path[100]; + char ogg_path[150]; + char dolpath[150]; + char update_path[150]; + char homebrewapps_path[150]; + char selected_homebrew[200]; + char Cheatcodespath[100]; + char TxtCheatcodespath[100]; + char BcaCodepath[100]; + char WipCodepath[100]; + short error002; + u8 titlesOverride; // db_titles + char db_url[200]; + char db_language[20]; + u8 db_JPtoEN; + u8 gridRows; + u8 autonetwork; + u8 discart; + short gamesound; + u8 marknewtitles; + u8 FatInstallToDir; + u8 partitions_to_install; + u8 fullcopy; + u8 beta_upgrades; + struct SParental parental; + }; + extern struct SSettings Settings; - void CFG_LoadGlobal(void); - bool cfg_save_global(void); + void CFG_LoadGlobal(void); + bool cfg_save_global(void); - void GetLanguageToLangCode(int *langid, char *langcode); - bool OpenXMLDatabase(char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool freemem); + void GetLanguageToLangCode(int *langid, char *langcode); + bool OpenXMLDatabase(char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool freemem); - char *get_title(struct discHdr *header); - char *cfg_get_title(u8 *id) ; - void title_set(char *id, char *title); - void titles_default(); - u8 get_block(struct discHdr *header); - s8 get_pegi_block(struct discHdr *header); + char *get_title(struct discHdr *header); + char *cfg_get_title(u8 *id) ; + void title_set(char *id, char *title); + void titles_default(); + u8 get_block(struct discHdr *header); + s8 get_pegi_block(struct discHdr *header); - void CFG_Cleanup(void); + void CFG_Cleanup(void); #ifdef __cplusplus } diff --git a/source/settings/newtitles.cpp b/source/settings/newtitles.cpp index fbe139df..d1ca11dc 100644 --- a/source/settings/newtitles.cpp +++ b/source/settings/newtitles.cpp @@ -9,161 +9,171 @@ NewTitles *NewTitles::instance = NULL; -NewTitles* NewTitles::Instance() { - if (instance == NULL) { - instance = new NewTitles(); - } - return instance; +NewTitles* NewTitles::Instance() +{ + if (instance == NULL) { + instance = new NewTitles(); + } + return instance; } -void NewTitles::DestroyInstance() { - if (instance != NULL) { - delete instance; - instance = NULL; - } +void NewTitles::DestroyInstance() +{ + if (instance != NULL) + { + delete instance; + instance = NULL; + } } -NewTitles::NewTitles() { - firstTitle = lastTitle = NULL; - isDirty = isNewFile = false; +NewTitles::NewTitles() +{ + firstTitle = lastTitle = NULL; + isDirty = isNewFile = false; - // Read the text file - char path[255]; - strcpy(path, Settings.titlestxt_path); - path[strlen(Settings.titlestxt_path) - 1] = '/'; - strcat(path, GAMETITLES); + // Read the text file + char path[255]; + strcpy(path, Settings.titlestxt_path); + path[strlen(Settings.titlestxt_path) - 1] = '/'; + strcat(path, GAMETITLES); - char line[20]; - FILE *fp = fopen(path, "r"); - if (fp != NULL) { - while (fgets(line, sizeof(line), fp)) { - // This is one line - if (line[0] != '#' || line[0] != ';') { - Title *title = new Title(); - if (sscanf(line, "%6c:%ld", (u8 *) &title->titleId, &title->timestamp) == 2) { - if (firstTitle == NULL) { - firstTitle = title; - lastTitle = title; - } else { - lastTitle->next = title; - lastTitle = title; - } - } else { - delete title; // Invalid title entry, ignore - } - } - } - - fclose(fp); - } else { - isNewFile = true; - } + char line[20]; + FILE *fp = fopen(path, "r"); + if (fp != NULL) { + while (fgets(line, sizeof(line), fp)) { + // This is one line + if (line[0] != '#' || line[0] != ';') { + Title *title = new Title(); + if (sscanf(line, "%6c:%ld", (u8 *) &title->titleId, &title->timestamp) == 2) { + if (firstTitle == NULL) { + firstTitle = title; + lastTitle = title; + } else { + lastTitle->next = title; + lastTitle = title; + } + } + else { + delete title; // Invalid title entry, ignore + } + } + } + + fclose(fp); + } else { + isNewFile = true; + } } -NewTitles::~NewTitles() { - Save(); - - Title *t = firstTitle; - while (t != NULL) { - Title *temp = (Title *) t->next; - delete t; - t = temp; - } - firstTitle = lastTitle = NULL; +NewTitles::~NewTitles() +{ + Save(); + + Title *t = firstTitle; + while (t != NULL) { + Title *temp = (Title *) t->next; + delete t; + t = temp; + } + firstTitle = lastTitle = NULL; } -void NewTitles::CheckGame(u8 *titleid) { - if (titleid == NULL || strlen((char *) titleid) == 0) { - return; - } +void NewTitles::CheckGame(u8 *titleid) +{ + if (titleid == NULL || strlen((char *) titleid) == 0) { + return; + } - Title *t = firstTitle; - while (t != NULL) { - // Loop all titles, search for the correct titleid - if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { - return; // Game found, which is excellent - } - t = (Title *) t->next; - } + Title *t = firstTitle; + while (t != NULL) { + // Loop all titles, search for the correct titleid + if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { + return; // Game found, which is excellent + } + t = (Title *) t->next; + } - // Not found, add it - t = new Title(); - strncpy((char *) t->titleId, (char *) titleid, 6); - t->timestamp = time(NULL); - if (isNewFile) { - t->timestamp -= (NEW_SECONDS + 1); // Mark all games as not new if this is a new file - } + // Not found, add it + t = new Title(); + strncpy((char *) t->titleId, (char *) titleid, 6); + t->timestamp = time(NULL); + if (isNewFile) { + t->timestamp -= (NEW_SECONDS + 1); // Mark all games as not new if this is a new file + } - if (firstTitle == NULL) { - firstTitle = t; - lastTitle = t; - } else { - lastTitle -> next = t; - lastTitle = t; - } - isDirty = true; + if (firstTitle == NULL) { + firstTitle = t; + lastTitle = t; + } else { + lastTitle -> next = t; + lastTitle = t; + } + isDirty = true; } -bool NewTitles::IsNew(u8 *titleid) { - if (titleid == NULL || strlen((char *) titleid) == 0) { - return false; - } +bool NewTitles::IsNew(u8 *titleid) +{ + if (titleid == NULL || strlen((char *) titleid) == 0) { + return false; + } - Title *t = firstTitle; - - while (t != NULL) { - // Loop all titles, search for the correct titleid - if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { - // This title is less than 24 hours old - if ((time(NULL) - t->timestamp) < NEW_SECONDS) { - // Only count the game as new when it's never been played through GX - Game_NUM *gnum = CFG_get_game_num(titleid); - return gnum == NULL || gnum->count == 0; - } - return false; - } - t = (Title *) t->next; - } - // We should never get here, since all files should be added by now! - CheckGame(titleid); - - return !isNewFile; // If this is a new file, return false + Title *t = firstTitle; + + while (t != NULL) { + // Loop all titles, search for the correct titleid + if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { + // This title is less than 24 hours old + if ((time(NULL) - t->timestamp) < NEW_SECONDS) { + // Only count the game as new when it's never been played through GX + Game_NUM *gnum = CFG_get_game_num(titleid); + return gnum == NULL || gnum->count == 0; + } + return false; + } + t = (Title *) t->next; + } + // We should never get here, since all files should be added by now! + CheckGame(titleid); + + return !isNewFile; // If this is a new file, return false } -void NewTitles::Remove(u8 *titleid) { - Title *t = firstTitle, *prev = NULL; - while (t != NULL) { - if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { - if (prev == NULL) { - firstTitle = (Title *) t->next; - } else { - prev->next = t->next; - } - delete t; - isDirty = true; - - return; - } - prev = t; - t = (Title *) t->next; - } +void NewTitles::Remove(u8 *titleid) +{ + Title *t = firstTitle, *prev = NULL; + while (t != NULL) { + if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { + if (prev == NULL) { + firstTitle = (Title *) t->next; + } else { + prev->next = t->next; + } + delete t; + isDirty = true; + + return; + } + prev = t; + t = (Title *) t->next; + } } -void NewTitles::Save() { - if (!isDirty) return; +void NewTitles::Save() +{ + if (!isDirty) return; - char path[255]; - strcpy(path, Settings.titlestxt_path); - path[strlen(Settings.titlestxt_path) - 1] = '/'; - strcat(path, GAMETITLES); + char path[255]; + strcpy(path, Settings.titlestxt_path); + path[strlen(Settings.titlestxt_path) - 1] = '/'; + strcat(path, GAMETITLES); - FILE *fp = fopen(path, "w"); - if (fp != NULL) { - Title *t = firstTitle; - while (t != NULL && strlen((char *) t->titleId) > 0) { - fprintf(fp, "%s:%ld\n", t->titleId, t->timestamp); - t = (Title *) t->next; - } - fclose(fp); - } + FILE *fp = fopen(path, "w"); + if (fp != NULL) { + Title *t = firstTitle; + while (t != NULL && strlen((char *) t->titleId) > 0) { + fprintf(fp, "%s:%ld\n", t->titleId, t->timestamp); + t = (Title *) t->next; + } + fclose(fp); + } } diff --git a/source/settings/newtitles.h b/source/settings/newtitles.h index 0a967076..c6e2538a 100644 --- a/source/settings/newtitles.h +++ b/source/settings/newtitles.h @@ -3,32 +3,33 @@ #include -class NewTitles { +class NewTitles +{ public: - static NewTitles *Instance(); - static void DestroyInstance(); - - void Save(); - void CheckGame(u8 *titleid); - bool IsNew(u8 *titleid); - void Remove(u8 *titleid); + static NewTitles *Instance(); + static void DestroyInstance(); + + void Save(); + void CheckGame(u8 *titleid); + bool IsNew(u8 *titleid); + void Remove(u8 *titleid); private: - NewTitles(); - ~NewTitles(); - - static NewTitles *instance; - - class Title { - public: - u8 titleId[6]; - time_t timestamp; - void *next; - }; - - Title *firstTitle; - Title *lastTitle; - bool isDirty; - bool isNewFile; + NewTitles(); + ~NewTitles(); + + static NewTitles *instance; + + class Title { + public: + u8 titleId[6]; + time_t timestamp; + void *next; + }; + + Title *firstTitle; + Title *lastTitle; + bool isDirty; + bool isNewFile; }; #endif //_NEWTITLES_H diff --git a/source/sounds/bg_music.ogg b/source/sounds/bg_music.ogg index b7063987..a22a73ae 100644 Binary files a/source/sounds/bg_music.ogg and b/source/sounds/bg_music.ogg differ diff --git a/source/sounds/button_click.pcm b/source/sounds/button_click.pcm index bb84a8f2..de3d55e3 100644 Binary files a/source/sounds/button_click.pcm and b/source/sounds/button_click.pcm differ diff --git a/source/sounds/button_click2.pcm b/source/sounds/button_click2.pcm index 362303c0..113b4321 100644 Binary files a/source/sounds/button_click2.pcm and b/source/sounds/button_click2.pcm differ diff --git a/source/sounds/button_over.pcm b/source/sounds/button_over.pcm index dd32825f..64f519cf 100644 Binary files a/source/sounds/button_over.pcm and b/source/sounds/button_over.pcm differ diff --git a/source/sounds/credits_music.ogg b/source/sounds/credits_music.ogg index 4eb40b38..4010c41c 100644 Binary files a/source/sounds/credits_music.ogg and b/source/sounds/credits_music.ogg differ diff --git a/source/sounds/menuin.ogg b/source/sounds/menuin.ogg index 6f63bfeb..65ea7d73 100644 Binary files a/source/sounds/menuin.ogg and b/source/sounds/menuin.ogg differ diff --git a/source/sounds/menuout.ogg b/source/sounds/menuout.ogg index f4b9f053..3d840b0e 100644 Binary files a/source/sounds/menuout.ogg and b/source/sounds/menuout.ogg differ diff --git a/source/sounds/success.ogg b/source/sounds/success.ogg index 54ecc027..bb3821e5 100644 Binary files a/source/sounds/success.ogg and b/source/sounds/success.ogg differ diff --git a/source/stub.S b/source/stub.S index 36eee045..14468da7 100644 --- a/source/stub.S +++ b/source/stub.S @@ -1,6 +1,6 @@ -.rodata + .rodata -.globl data1 -.balign 32 + .globl data1 + .balign 32 data1: -.incbin "../source/data1" + .incbin "../source/data1" diff --git a/source/sys.cpp b/source/sys.cpp index 2e6c3d25..18996532 100644 --- a/source/sys.cpp +++ b/source/sys.cpp @@ -67,46 +67,46 @@ void Sys_Reboot(void) { } int Sys_ChangeIos(int ios) { - s32 prevIos = IOS_GetVersion(); + s32 prevIos = IOS_GetVersion(); + + SDCard_deInit(); + USBDevice_deInit(); + + WPAD_Flush(0); + WPAD_Disconnect(0); + WPAD_Shutdown(); + + WDVD_Close(); + + USBStorage_Deinit(); + + s32 ret = IOS_ReloadIOSsafe(ios); + if (ret < 0) { + ios = prevIos; + } + + SDCard_Init(); - SDCard_deInit(); - USBDevice_deInit(); - - WPAD_Flush(0); - WPAD_Disconnect(0); - WPAD_Shutdown(); - - WDVD_Close(); - - USBStorage_Deinit(); - - s32 ret = IOS_ReloadIOSsafe(ios); - if (ret < 0) { - ios = prevIos; - } - - SDCard_Init(); - - if (ios == 222 || ios == 223) { - load_ehc_module(); - } - USBDevice_Init(); + if (ios == 222 || ios == 223) { + load_ehc_module(); + } + USBDevice_Init(); PAD_Init(); Wpad_Init(); WPAD_SetDataFormat(WPAD_CHAN_ALL,WPAD_FMT_BTNS_ACC_IR); WPAD_SetVRes(WPAD_CHAN_ALL, screenwidth, screenheight); - WBFS_Init(WBFS_DEVICE_USB); - Disc_Init(); - - if (Sys_IsHermes()) { - WBFS_OpenNamed((char *) &game_partition); - } else { - WBFS_Open(); - } - - return ret; + WBFS_Init(WBFS_DEVICE_USB); + Disc_Init(); + + if (Sys_IsHermes()) { + WBFS_OpenNamed((char *) &game_partition); + } else { + WBFS_Open(); + } + + return ret; } int Sys_IosReload(int IOS) { @@ -205,16 +205,16 @@ void Sys_BackToLoader(void) { } bool Sys_IsHermes() { - return IOS_GetVersion() == 222 || IOS_GetVersion() == 223; + return IOS_GetVersion() == 222 || IOS_GetVersion() == 223; } #include "prompts/PromptWindows.h" void ShowMemInfo() { - char buf[255]; + char buf[255]; struct mallinfo mymallinfo = mallinfo(); sprintf((char *) &buf,"Total: %d, Used: %d, Can be freed: %d", mymallinfo.arena/1024, mymallinfo.uordblks/1024, mymallinfo.keepcost/1024); - WindowPrompt("Mem info", (char *) &buf, "OK"); + WindowPrompt("Mem info", (char *) &buf, "OK"); } @@ -225,49 +225,58 @@ s32 ios223rev = -69; s32 ios249rev = -69; s32 ios250rev = -69; -s32 IOS_ReloadIOSsafe(int ios) { - if (ios==222) { - if (ios222rev == -69) - ios222rev = getIOSrev(0x00000001000000dell); - - if (ios222rev >= 0 && (ios222rev != 4 && ios222rev != 5))return -2; - } else if (ios==223) { - if (ios223rev == -69) - ios223rev = getIOSrev(0x00000001000000dfll); - - if (ios223rev >= 0 && (ios223rev != 4 && ios223rev != 5))return -2; - } else if (ios==249) { - if (ios249rev == -69) - ios249rev = getIOSrev(0x00000001000000f9ll); - - if (ios249rev >= 0 && !(ios249rev>=9 && ios249rev<65280))return -2; - } else if (ios==250) { - if (ios250rev == -69) - ios250rev = getIOSrev(0x00000001000000fall); - - if (ios250rev >= 0 && !(ios250rev>=9 && ios250rev<65280))return -2; - } - - s32 r = IOS_ReloadIOS(ios); - if (r >= 0) { - WII_Initialize(); - } - return r; +s32 IOS_ReloadIOSsafe(int ios) +{ + if (ios==222) + { + if (ios222rev == -69) + ios222rev = getIOSrev(0x00000001000000dell); + + if (ios222rev >= 0 && (ios222rev != 4 && ios222rev != 5))return -2; + } + else if (ios==223) + { + if (ios223rev == -69) + ios223rev = getIOSrev(0x00000001000000dfll); + + if (ios223rev >= 0 && (ios223rev != 4 && ios223rev != 5))return -2; + } + else if (ios==249) + { + if (ios249rev == -69) + ios249rev = getIOSrev(0x00000001000000f9ll); + + if (ios249rev >= 0 && !(ios249rev>=9 && ios249rev<65280))return -2; + } + else if (ios==250) + { + if (ios250rev == -69) + ios250rev = getIOSrev(0x00000001000000fall); + + if (ios250rev >= 0 && !(ios250rev>=9 && ios250rev<65280))return -2; + } + + s32 r = IOS_ReloadIOS(ios); + if (r >= 0) { + WII_Initialize(); + } + return r; } #include -void ScreenShot() { - time_t rawtime; - struct tm * timeinfo; - char buffer [80]; - char buffer2 [80]; +void ScreenShot() +{ + time_t rawtime; + struct tm * timeinfo; + char buffer [80]; + char buffer2 [80]; - time ( &rawtime ); - timeinfo = localtime ( &rawtime ); - //USBLoader_GX_ScreenShot-Month_Day_Hour_Minute_Second_Year.png - strftime (buffer,80,"USBLoader_GX_ScreenShot-%b%d%H%M%S%y.png",timeinfo); - sprintf(buffer2, "%s/config/%s", bootDevice, buffer); + time ( &rawtime ); + timeinfo = localtime ( &rawtime ); + //USBLoader_GX_ScreenShot-Month_Day_Hour_Minute_Second_Year.png + strftime (buffer,80,"USBLoader_GX_ScreenShot-%b%d%H%M%S%y.png",timeinfo); + sprintf(buffer2, "%s/config/%s", bootDevice, buffer); - TakeScreenshot(buffer2); + TakeScreenshot(buffer2); } diff --git a/source/themes/Theme_Downloader.cpp b/source/themes/Theme_Downloader.cpp index 9f942d83..b1d00630 100644 --- a/source/themes/Theme_Downloader.cpp +++ b/source/themes/Theme_Downloader.cpp @@ -36,8 +36,9 @@ extern u8 shutdown; extern u8 reset; -int DownloadTheme(const char *url, const char *title) { - if (!url) +int DownloadTheme(const char *url, const char *title) +{ + if(!url) return 0; char filename[255]; @@ -45,7 +46,8 @@ int DownloadTheme(const char *url, const char *title) { int filesize = download_request(url, (char *) &filename); - if (filesize <= 0) { + if(filesize <= 0) + { WindowPrompt(tr("Download request failed."), 0, tr("OK")); return 0; } @@ -60,7 +62,8 @@ int DownloadTheme(const char *url, const char *title) { snprintf(filepath, sizeof(filepath), "%s/%s", path, filename); FILE *file = fopen(filepath, "wb"); - if (!file) { + if(!file) + { WindowPrompt(tr("Download failed."), tr("Can't create file"), tr("OK")); return 0; } @@ -71,21 +74,24 @@ int DownloadTheme(const char *url, const char *title) { u8 *buffer = new u8[blocksize]; - while (done < (u32) filesize) { - if ((u32) blocksize > filesize-done) + while(done < (u32) filesize) + { + if((u32) blocksize > filesize-done) blocksize = filesize-done; ShowProgress(tr("Downloading file"), 0, (char*) filename, done, filesize, true); int ret = network_read(buffer, blocksize); - if (ret < 0) { + if(ret < 0) + { free(buffer); fclose(file); remove(path); ProgressStop(); WindowPrompt(tr("Download failed."), tr("Transfer failed."), tr("OK")); return 0; - } else if (ret == 0) + } + else if (ret == 0) break; fwrite(buffer, 1, blocksize, file); @@ -98,7 +104,8 @@ int DownloadTheme(const char *url, const char *title) { ProgressStop(); - if (done != (u32) filesize) { + if(done != (u32) filesize) + { remove(filepath); WindowPrompt(tr("Download failed."), tr("Connection lost..."), tr("OK")); return 0; @@ -107,15 +114,19 @@ int DownloadTheme(const char *url, const char *title) { ZipFile zipfile(filepath); int result = zipfile.ExtractAll(path); - if (result) { + if(result) + { remove(filepath); int choice = WindowPrompt(tr("Successfully extracted theme."), tr("Do you want to apply it now?"), tr("Yes"), tr("No")); - if (choice) { + if(choice) + { char real_themepath[1024]; sprintf(real_themepath, "%s", CFG.theme_path); - if (SearchFile(path, "GXtheme.cfg", real_themepath) == true) { + if(SearchFile(path, "GXtheme.cfg", real_themepath) == true) + { char *ptr = strrchr(real_themepath, '/'); - if (ptr) { + if(ptr) + { ptr++; ptr[0] = '\0'; } @@ -124,25 +135,28 @@ int DownloadTheme(const char *url, const char *title) { CFG_Load(); CFG_LoadGlobal(); result = 2; - } else + } + else WindowPrompt(tr("ERROR: Can't set up theme."), tr("GXtheme.cfg not found in any subfolder."), tr("OK")); } - } else + } + else WindowPrompt(tr("Failed to extract."), tr("Unsupported format, try to extract manually."), tr("OK")); return result; } -static int Theme_Prompt(const char *title, const char *author, GuiImageData *thumbimageData, const char *downloadlink) { +static int Theme_Prompt(const char *title, const char *author, GuiImageData *thumbimageData, const char *downloadlink) +{ gprintf("\nTheme_Prompt(%s ,%s, , %s)",title,author,downloadlink); bool leave = false; int result = 0; GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); @@ -182,7 +196,8 @@ static int Theme_Prompt(const char *title, const char *author, GuiImageData *thu GuiText downloadBtnTxt(tr("Download") , 22, THEME.prompttext); downloadBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); GuiImage downloadBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { + if (Settings.wsprompt == yes) + { downloadBtnTxt.SetWidescreen(CFG.widescreen); downloadBtnImg.SetWidescreen(CFG.widescreen); } @@ -193,7 +208,8 @@ static int Theme_Prompt(const char *title, const char *author, GuiImageData *thu GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); GuiImage backBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { + if (Settings.wsprompt == yes) + { backBtnTxt.SetWidescreen(CFG.widescreen); backBtnImg.SetWidescreen(CFG.widescreen); } @@ -225,7 +241,8 @@ static int Theme_Prompt(const char *title, const char *author, GuiImageData *thu mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - while (!leave) { + while (!leave) + { VIDEO_WaitVSync(); if (shutdown == 1) @@ -233,11 +250,13 @@ static int Theme_Prompt(const char *title, const char *author, GuiImageData *thu else if (reset == 1) Sys_Reboot(); - if (downloadBtn.GetState() == STATE_CLICKED) { + if (downloadBtn.GetState() == STATE_CLICKED) + { int choice = WindowPrompt(tr("Do you want to download this theme?"), title, tr("Yes"), tr("Cancel")); - if (choice) { + if(choice) + { result = DownloadTheme(downloadlink, title); - if (result == 2) + if(result == 2) leave = true; } mainWindow->SetState(STATE_DISABLED); @@ -246,7 +265,8 @@ static int Theme_Prompt(const char *title, const char *author, GuiImageData *thu downloadBtn.ResetState(); } - else if (backBtn.GetState() == STATE_CLICKED) { + else if (backBtn.GetState() == STATE_CLICKED) + { leave = true; backBtn.ResetState(); } @@ -263,7 +283,8 @@ static int Theme_Prompt(const char *title, const char *author, GuiImageData *thu } -int Theme_Downloader() { +int Theme_Downloader() +{ int pagesize = 4; int menu = MENU_NONE; bool listchanged = false; @@ -275,9 +296,9 @@ int Theme_Downloader() { /*** Sound Variables ***/ GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); /*** Image Variables ***/ @@ -334,7 +355,8 @@ int Theme_Downloader() { /*** Buttons ***/ - for (int i = 0; i < pagesize; i++) { + for (int i = 0; i < pagesize; i++) + { ImageData[i] = NULL; Image[i] = NULL; MainButtonTxt[i] = NULL; @@ -350,15 +372,16 @@ int Theme_Downloader() { } /*** Positions ***/ - MainButton[0]->SetPosition(90, 75); - MainButton[1]->SetPosition(340, 75); - MainButton[2]->SetPosition(90, 230); - MainButton[3]->SetPosition(340, 230); + MainButton[0]->SetPosition(90, 75); + MainButton[1]->SetPosition(340, 75); + MainButton[2]->SetPosition(90, 230); + MainButton[3]->SetPosition(340, 230); GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); GuiImage backBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { + if (Settings.wsprompt == yes) + { backBtnTxt.SetWidescreen(CFG.widescreen); backBtnImg.SetWidescreen(CFG.widescreen); } @@ -394,7 +417,7 @@ int Theme_Downloader() { GoRightBtn.SetTrigger(&trigPlus); GuiImage PageindicatorImg(&PageindicatorImgData); - GuiText PageindicatorTxt(NULL, 22, (GXColor) {0, 0, 0, 255 }); + GuiText PageindicatorTxt(NULL, 22, (GXColor) { 0, 0, 0, 255}); GuiButton PageIndicatorBtn(PageindicatorImg.GetWidth(), PageindicatorImg.GetHeight()); PageIndicatorBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); PageIndicatorBtn.SetPosition(110, 400); @@ -406,7 +429,8 @@ int Theme_Downloader() { PageIndicatorBtn.SetEffectGrow(); GuiImage wifiImg(&wifiImgData); - if (Settings.wsprompt == yes) { + if (Settings.wsprompt == yes) + { wifiImg.SetWidescreen(CFG.widescreen); } GuiButton wifiBtn(wifiImg.GetWidth(), wifiImg.GetHeight()); @@ -424,7 +448,7 @@ int Theme_Downloader() { mainWindow->Append(&w); ResumeGui(); - if (!IsNetworkInit()) + if(!IsNetworkInit()) NetworkInitPrompt(); char url[300]; @@ -449,12 +473,14 @@ int Theme_Downloader() { int ThemesOnPage = Theme->GetThemeCount(); - if (!ThemesOnPage) { + if(!ThemesOnPage) + { WindowPrompt(tr("No themes found on the site."), 0, "OK"); menu = MENU_SETTINGS; } - while (menu == MENU_NONE) { + while(menu == MENU_NONE) + { HaltGui(); w.RemoveAll(); w.Append(&background); @@ -472,22 +498,24 @@ int Theme_Downloader() { int n = 0; - for (int i = currenttheme; (i < (currenttheme+pagesize)); i++) { + for(int i = currenttheme; (i < (currenttheme+pagesize)); i++) + { ShowProgress(tr("Downloading image:"), 0, (char *) Theme->GetThemeTitle(i), n, pagesize); - if (MainButtonTxt[n]) + if(MainButtonTxt[n]) delete MainButtonTxt[n]; - if (ImageData[n]) + if(ImageData[n]) delete ImageData[n]; - if (Image[n]) + if(Image[n]) delete Image[n]; MainButtonTxt[n] = NULL; ImageData[n] = NULL; Image[n] = NULL; - if (i < ThemesOnPage) { - MainButtonTxt[n] = new GuiText(Theme->GetThemeTitle(i), 18, (GXColor) {0, 0, 0, 255}); + if(i < ThemesOnPage) + { + MainButtonTxt[n] = new GuiText(Theme->GetThemeTitle(i), 18, (GXColor) { 0, 0, 0, 255}); MainButtonTxt[n]->SetAlignment(ALIGN_CENTER, ALIGN_TOP); MainButtonTxt[n]->SetPosition(0, 10); MainButtonTxt[n]->SetMaxWidth(theme_box_Data.GetWidth()-10, GuiText::DOTTED); @@ -499,19 +527,23 @@ int Theme_Downloader() { FILE * storefile = fopen(filepath, "rb"); - if (!storefile) { + if(!storefile) + { struct block file = downloadfile(url); char storepath[300]; snprintf(storepath, sizeof(storepath), "%s/tmp/", Settings.theme_downloadpath); subfoldercreate(storepath); - if (file.data) { + if(file.data) + { storefile = fopen(filepath, "wb"); fwrite(file.data, 1, file.size, storefile); fclose(storefile); } ImageData[n] = new GuiImageData(file.data, file.size); free(file.data); - } else { + } + else + { fseek(storefile, 0, SEEK_END); u32 filesize = ftell(storefile); u8 *buffer = (u8*) malloc(filesize); @@ -534,15 +566,17 @@ int Theme_Downloader() { ProgressStop(); HaltGui(); - for (int i = 0; i < pagesize; i++) { - if (MainButtonTxt[i]) + for(int i = 0; i < pagesize; i++) + { + if(MainButtonTxt[i]) w.Append(MainButton[i]); } ResumeGui(); listchanged = false; - while (!listchanged) { + while(!listchanged) + { VIDEO_WaitVSync (); if (shutdown == 1) @@ -550,40 +584,52 @@ int Theme_Downloader() { else if (reset == 1) Sys_Reboot(); - else if (wifiBtn.GetState() == STATE_CLICKED) { + else if (wifiBtn.GetState() == STATE_CLICKED) + { Initialize_Network(); wifiBtn.ResetState(); - } else if (backBtn.GetState() == STATE_CLICKED) { + } + else if (backBtn.GetState() == STATE_CLICKED) + { listchanged = true; menu = MENU_SETTINGS; backBtn.ResetState(); break; - } else if (GoRightBtn.GetState() == STATE_CLICKED) { + } + else if (GoRightBtn.GetState() == STATE_CLICKED) + { listchanged = true; currenttheme += pagesize; currentpage++; - if (currenttheme >= ThemesOnPage) { + if(currenttheme >= ThemesOnPage) + { currentpage = 1; currenttheme = 0; } GoRightBtn.ResetState(); - } else if (GoLeftBtn.GetState() == STATE_CLICKED) { + } + else if (GoLeftBtn.GetState() == STATE_CLICKED) + { listchanged = true; currenttheme -= pagesize; currentpage--; - if (currenttheme < 0) { + if(currenttheme < 0) + { currentpage = roundup((ThemesOnPage+1.0f)/pagesize); currenttheme = currentpage*pagesize-pagesize; } GoLeftBtn.ResetState(); } - for (int i = 0; i < pagesize; i++) { - if (MainButton[i]->GetState() == STATE_CLICKED) { + for(int i = 0; i < pagesize; i++) + { + if(MainButton[i]->GetState() == STATE_CLICKED) + { snprintf(url, sizeof(url), "%s", Theme->GetDownloadLink(currenttheme+i)); int ret = Theme_Prompt(Theme->GetThemeTitle(currenttheme+i), Theme->GetThemeAuthor(currenttheme+i), ImageData[i], url); MainButton[i]->ResetState(); - if (ret == 2) { + if(ret == 2) + { listchanged = true; menu = MENU_THEMEDOWNLOADER; } @@ -594,25 +640,26 @@ int Theme_Downloader() { w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect() > 0) usleep(100); + while(w.GetEffect() > 0) usleep(100); HaltGui(); mainWindow->Remove(&w); - for (int i = 0; i < pagesize; i++) { - if (MainButton[i]) + for (int i = 0; i < pagesize; i++) + { + if(MainButton[i]) delete MainButton[i]; - if (theme_box_img[i]) + if(theme_box_img[i]) delete theme_box_img[i]; - if (ImageData[i]) + if(ImageData[i]) delete ImageData[i]; - if (Image[i]) + if(Image[i]) delete Image[i]; - if (MainButtonTxt[i]) + if(MainButtonTxt[i]) delete MainButtonTxt[i]; } - if (Theme) + if(Theme) delete Theme; Theme = NULL; diff --git a/source/themes/Theme_List.cpp b/source/themes/Theme_List.cpp index 8f3e9b1f..5bf02bf4 100644 --- a/source/themes/Theme_List.cpp +++ b/source/themes/Theme_List.cpp @@ -35,12 +35,14 @@ #define stringcompare(text, cmp, pos) strncasecmp((const char*) &text[pos-strlen(cmp)], (const char*) cmp, strlen((const char*) cmp)) -static void copyhtmlsting(const char *from, char *outtext, const char *stopat, u32 &cnt) { +static void copyhtmlsting(const char *from, char *outtext, const char *stopat, u32 &cnt) +{ u32 cnt2 = 0; u32 stringlength = strlen(from); - while ((stringcompare(from, stopat, cnt+strlen(stopat)) != 0) && (cnt2 < 1024) && (cnt < stringlength)) { + while ((stringcompare(from, stopat, cnt+strlen(stopat)) != 0) && (cnt2 < 1024) && (cnt < stringlength)) + { outtext[cnt2] = from[cnt]; cnt2++; cnt++; @@ -48,42 +50,48 @@ static void copyhtmlsting(const char *from, char *outtext, const char *stopat, u outtext[cnt2] = '\0'; } -Theme_List::Theme_List(const char * url) { +Theme_List::Theme_List(const char * url) +{ Theme = NULL; themescount = 0; - if (!IsNetworkInit()) { + if (!IsNetworkInit()) + { themescount = -1; return; } struct block file = downloadfile(url); - if (!file.data || !file.size) { + if (!file.data || !file.size) + { themescount = -2; return; } - themescount = CountThemes(file.data); - if (themescount <= 0) { + themescount = CountThemes(file.data); + if (themescount <= 0) + { free(file.data); return; - } + } - ParseXML(file.data); + ParseXML(file.data); free(file.data); } -Theme_List::~Theme_List() { - for (int i = 0; i < themescount; i++) { - if (Theme[i].themetitle) +Theme_List::~Theme_List() +{ + for (int i = 0; i < themescount; i++) + { + if(Theme[i].themetitle) delete [] Theme[i].themetitle; - if (Theme[i].author) + if(Theme[i].author) delete [] Theme[i].author; - if (Theme[i].imagelink) + if(Theme[i].imagelink) delete [] Theme[i].imagelink; - if (Theme[i].downloadlink) + if(Theme[i].downloadlink) delete [] Theme[i].downloadlink; Theme[i].themetitle = NULL; Theme[i].author = NULL; @@ -91,129 +99,144 @@ Theme_List::~Theme_List() { Theme[i].downloadlink = NULL; } - if (Theme) + if(Theme) delete [] Theme; Theme = NULL; } -int Theme_List::CountThemes(const u8 * xmlfile) { - char tmp[200]; - u32 cnt = 0; - u32 stringlength = strlen((const char *) xmlfile); - memset(tmp, 0, sizeof(tmp)); +int Theme_List::CountThemes(const u8 * xmlfile) +{ + char tmp[200]; + u32 cnt = 0; + u32 stringlength = strlen((const char *) xmlfile); + memset(tmp, 0, sizeof(tmp)); - while (cnt < stringlength) { - if (stringcompare(xmlfile, "", cnt) == 0) { - copyhtmlsting((const char *) xmlfile, tmp, ">", cnt); - break; - } - cnt++; - } - tmp[cnt+1] = 0; + while (cnt < stringlength) + { + if (stringcompare(xmlfile, "", cnt) == 0) + { + copyhtmlsting((const char *) xmlfile, tmp, ">", cnt); + break; + } + cnt++; + } + tmp[cnt+1] = 0; - return atoi(tmp); + return atoi(tmp); } -bool Theme_List::ParseXML(const u8 * xmlfile) { - char element_text[1024]; - memset(element_text, 0, sizeof(element_text)); - mxml_node_t *nodetree=NULL; - mxml_node_t *nodedata=NULL; - mxml_node_t *nodeid=NULL; - mxml_index_t *nodeindex=NULL; +bool Theme_List::ParseXML(const u8 * xmlfile) +{ + char element_text[1024]; + memset(element_text, 0, sizeof(element_text)); + mxml_node_t *nodetree=NULL; + mxml_node_t *nodedata=NULL; + mxml_node_t *nodeid=NULL; + mxml_index_t *nodeindex=NULL; - nodetree = mxmlLoadString(NULL, (const char *) xmlfile, MXML_OPAQUE_CALLBACK); + nodetree = mxmlLoadString(NULL, (const char *) xmlfile, MXML_OPAQUE_CALLBACK); - if (nodetree == NULL) { + if (nodetree == NULL) + { return false; - } + } nodedata = mxmlFindElement(nodetree, nodetree, "themes", NULL, NULL, MXML_DESCEND); - if (nodedata == NULL) { + if (nodedata == NULL) + { return false; } nodeindex = mxmlIndexNew(nodedata,"name", NULL); nodeid = mxmlIndexReset(nodeindex); - Theme = new Theme_Info[themescount]; - memset(Theme, 0, sizeof(Theme)); + Theme = new Theme_Info[themescount]; + memset(Theme, 0, sizeof(Theme)); - for (int i = 0; i < themescount; i++) { - nodeid = mxmlIndexFind(nodeindex,"name", NULL); - if (nodeid != NULL) { - get_nodetext(nodeid, element_text, sizeof(element_text)); + for (int i = 0; i < themescount; i++) + { + nodeid = mxmlIndexFind(nodeindex,"name", NULL); + if (nodeid != NULL) + { + get_nodetext(nodeid, element_text, sizeof(element_text)); Theme[i].themetitle = new char[strlen(element_text)+2]; snprintf(Theme[i].themetitle,strlen(element_text)+1, "%s", element_text); - GetTextFromNode(nodeid, nodedata, (char *) "creator", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); + GetTextFromNode(nodeid, nodedata, (char *) "creator", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); Theme[i].author = new char[strlen(element_text)+2]; snprintf(Theme[i].author,strlen(element_text)+1, "%s", element_text); - GetTextFromNode(nodeid, nodedata, (char *) "thumbpath", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); + GetTextFromNode(nodeid, nodedata, (char *) "thumbpath", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); Theme[i].imagelink = new char[strlen(element_text)+2]; snprintf(Theme[i].imagelink,strlen(element_text)+1, "%s", element_text); - GetTextFromNode(nodeid, nodedata, (char *) "downloadpath", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); + GetTextFromNode(nodeid, nodedata, (char *) "downloadpath", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); Theme[i].downloadlink = new char[strlen(element_text)+2]; snprintf(Theme[i].downloadlink,strlen(element_text)+1, "%s", element_text); - GetTextFromNode(nodeid, nodedata, (char *) "averagerating", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); + GetTextFromNode(nodeid, nodedata, (char *) "averagerating", NULL, NULL, MXML_NO_DESCEND, element_text,sizeof(element_text)); Theme[i].rating = atoi(element_text); - } - } + } + } mxmlIndexDelete(nodeindex); - free(nodetree); - free(nodedata); - free(nodeid); - nodetree=NULL; - nodedata=NULL; - nodeid=NULL; - nodeindex=NULL; + free(nodetree); + free(nodedata); + free(nodeid); + nodetree=NULL; + nodedata=NULL; + nodeid=NULL; + nodeindex=NULL; return true; } -const char * Theme_List::GetThemeTitle(int ind) { +const char * Theme_List::GetThemeTitle(int ind) +{ if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; else return Theme[ind].themetitle; } -const char * Theme_List::GetThemeAuthor(int ind) { +const char * Theme_List::GetThemeAuthor(int ind) +{ if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; else return Theme[ind].author; } -const char * Theme_List::GetImageLink(int ind) { +const char * Theme_List::GetImageLink(int ind) +{ if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; else return Theme[ind].imagelink; } -const char * Theme_List::GetDownloadLink(int ind) { +const char * Theme_List::GetDownloadLink(int ind) +{ if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; else return Theme[ind].downloadlink; } -int Theme_List::GetThemeCount() { +int Theme_List::GetThemeCount() +{ return themescount; } -static int ListCompare(const void *a, const void *b) { +static int ListCompare(const void *a, const void *b) +{ Theme_Info *ab = (Theme_Info*) a; Theme_Info *bb = (Theme_Info*) b; return stricmp((char *) ab->themetitle, (char *) bb->themetitle); } -void Theme_List::SortList() { +void Theme_List::SortList() +{ qsort(Theme, themescount, sizeof(Theme_Info), ListCompare); } diff --git a/source/themes/Theme_List.h b/source/themes/Theme_List.h index be01a303..85a8b713 100644 --- a/source/themes/Theme_List.h +++ b/source/themes/Theme_List.h @@ -9,7 +9,8 @@ #include "network/networkops.h" #include "network/http.h" -typedef struct _theme_info { +typedef struct _theme_info +{ char *themetitle; char *author; char *imagelink; @@ -18,36 +19,37 @@ typedef struct _theme_info { } Theme_Info; -class Theme_List { -public: - //!Constructor - //!\param url from where to get the list of links - Theme_List(const char *url); - //!Destructor - ~Theme_List(); - //!Get Themes into a struct from the XML file amount - bool ParseXML(const u8 * xmlfile); - //!Get Theme amount - int CountThemes(const u8 * xmlfile); - //! Get the a theme title - //!\param list index - const char * GetThemeTitle(int index); - //! Get the author of the theme - //!\param list index - const char * GetThemeAuthor(int index); - //! Get the author of the theme - //!\param list index - const char * GetImageLink(int index); - //! Get the download link of the theme - //!\param list index - const char * GetDownloadLink(int index); - //! Get the number of links counted - int GetThemeCount(); - //! Sort list - void SortList(); -protected: - int themescount; - Theme_Info *Theme; +class Theme_List +{ + public: + //!Constructor + //!\param url from where to get the list of links + Theme_List(const char *url); + //!Destructor + ~Theme_List(); + //!Get Themes into a struct from the XML file amount + bool ParseXML(const u8 * xmlfile); + //!Get Theme amount + int CountThemes(const u8 * xmlfile); + //! Get the a theme title + //!\param list index + const char * GetThemeTitle(int index); + //! Get the author of the theme + //!\param list index + const char * GetThemeAuthor(int index); + //! Get the author of the theme + //!\param list index + const char * GetImageLink(int index); + //! Get the download link of the theme + //!\param list index + const char * GetDownloadLink(int index); + //! Get the number of links counted + int GetThemeCount(); + //! Sort list + void SortList(); + protected: + int themescount; + Theme_Info *Theme; }; #endif diff --git a/source/unzip/inflate.c b/source/unzip/inflate.c index db556a85..3e97d934 100644 --- a/source/unzip/inflate.c +++ b/source/unzip/inflate.c @@ -3,7 +3,8 @@ #define CHUNK 1024 -int inflateFile(FILE *source, FILE *dest) { +int inflateFile(FILE *source, FILE *dest) +{ int ret; unsigned have; z_stream strm; @@ -30,7 +31,7 @@ int inflateFile(FILE *source, FILE *dest) { if (strm.avail_in == 0) break; strm.next_in = in; - + /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNK; diff --git a/source/unzip/inflate.h b/source/unzip/inflate.h index fa5ec50b..f8556da3 100644 --- a/source/unzip/inflate.h +++ b/source/unzip/inflate.h @@ -9,7 +9,7 @@ extern "C" { #endif - int inflateFile(FILE *source, FILE *dest); +int inflateFile(FILE *source, FILE *dest); #ifdef __cplusplus } diff --git a/source/unzip/miniunz.c b/source/unzip/miniunz.c index e3985730..2bf8f26d 100644 --- a/source/unzip/miniunz.c +++ b/source/unzip/miniunz.c @@ -68,23 +68,23 @@ int makedir (char *newdir) { } static char *fullfilename(const char *basedir, char *filename) { - char *file = (char *) malloc(strlen(basedir) + strlen(filename) + 1); - if (basedir == NULL) { - strcpy(file, filename); - } else { - if (basedir[strlen(basedir) - 1] == '/') { - sprintf(file, "%s%s", basedir, filename); - } else { - sprintf(file, "%s/%s", basedir, filename); - } - } - return file; + char *file = (char *) malloc(strlen(basedir) + strlen(filename) + 1); + if (basedir == NULL) { + strcpy(file, filename); + } else { + if (basedir[strlen(basedir) - 1] == '/') { + sprintf(file, "%s%s", basedir, filename); + } else { + sprintf(file, "%s/%s", basedir, filename); + } + } + return file; } static int do_extract_currentfile(unzFile uf,const int* popt_extract_without_path,int* popt_overwrite,const char* password, const char *basedir) { char filename_inzip[256]; char* filename_withoutpath; - char* filename_withpath; + char* filename_withpath; char* p; int err=UNZ_OK; FILE *fout=NULL; @@ -107,7 +107,7 @@ static int do_extract_currentfile(unzFile uf,const int* popt_extract_without_pat } p = filename_withoutpath = filename_inzip; - filename_withpath = fullfilename(basedir, filename_inzip); + filename_withpath = fullfilename(basedir, filename_inzip); while ((*p) != '\0') { if (((*p)=='/') || ((*p)=='\\')) filename_withoutpath = p+1; @@ -117,16 +117,16 @@ static int do_extract_currentfile(unzFile uf,const int* popt_extract_without_pat if ((*filename_withoutpath)=='\0') { if ((*popt_extract_without_path)==0) { - // Fix the path, this will fail if the directoryname is the same as the first filename in the zip - char *path = (char *) malloc(strlen(filename_withpath)); - strcpy(path, filename_withpath); - char *ptr = strstr(path, filename_withoutpath); - *ptr = '\0'; + // Fix the path, this will fail if the directoryname is the same as the first filename in the zip + char *path = (char *) malloc(strlen(filename_withpath)); + strcpy(path, filename_withpath); + char *ptr = strstr(path, filename_withoutpath); + *ptr = '\0'; // printf("creating directory: %s\n",path); mymkdir(path); - free(path); + free(path); } } else { char* write_filename; @@ -179,14 +179,14 @@ static int do_extract_currentfile(unzFile uf,const int* popt_extract_without_pat char c=*(filename_withoutpath-1); *(filename_withoutpath-1)='\0'; - // Fix the path, this will fail if the directoryname is the same as the first filename in the zip - char *path = (char *) malloc(strlen(write_filename)); - strcpy(path, write_filename); - char *ptr = strstr(path, filename_withoutpath); - *ptr = '\0'; + // Fix the path, this will fail if the directoryname is the same as the first filename in the zip + char *path = (char *) malloc(strlen(write_filename)); + strcpy(path, write_filename); + char *ptr = strstr(path, filename_withoutpath); + *ptr = '\0'; makedir(path); - free(path); - + free(path); + *(filename_withoutpath-1)=c; fout=fopen(write_filename,"wb"); } @@ -225,7 +225,7 @@ static int do_extract_currentfile(unzFile uf,const int* popt_extract_without_pat } else unzCloseCurrentFile(uf); /* don't lose the error */ } - free(filename_withpath); + free(filename_withpath); free(buf); return err; } @@ -240,20 +240,20 @@ int extractZip(unzFile uf,int opt_extract_without_path,int opt_overwrite,const c if (err!=UNZ_OK) // printf("error %d with zipfile in unzGetGlobalInfo \n",err); - for (i=0;i=0 && dvddone==0); - } - + + else{ + dvddone = 0; + ret = bwDVD_LowRead(dol_header, sizeof(dolheader), doloffset, __dvd_readidcb); + while(ret>=0 && dvddone==0); + } + entrypoint = load_dol_start(dol_header); if (entrypoint == 0) { @@ -215,7 +216,7 @@ u32 Load_Dol_from_disc(u32 doloffset, u8 videoSelected, u8 patchcountrystring, u void *offset; u32 pos; u32 len; - + while (load_dol_image_modified(&offset, &pos, &len)) { if (len != 0) { ret = WDVD_Read(offset, len, (doloffset<<2) + pos); diff --git a/source/usbloader/apploader.c b/source/usbloader/apploader.c index 1e97d9ed..58d6f93e 100644 --- a/source/usbloader/apploader.c +++ b/source/usbloader/apploader.c @@ -237,62 +237,72 @@ void Anti_002_fix(void *Address, int Size) { void PretendThereIsADiscInTheDrive(void *buffer, u32 len) { - const u8 oldcode[] = { 0x54, 0x60, 0xF7, 0xFF, 0x40, 0x82, 0x00, 0x0C, 0x54, 0x60, 0x07, 0xFF, 0x41, 0x82, 0x00, 0x0C }; - const u8 newcode[] = { 0x54, 0x60, 0xF7, 0xFF, 0x40, 0x82, 0x00, 0x0C, 0x54, 0x60, 0x07, 0xFF, 0x48, 0x00, 0x00, 0x0C }; + const u8 oldcode[] = { 0x54, 0x60, 0xF7, 0xFF, 0x40, 0x82, 0x00, 0x0C, 0x54, 0x60, 0x07, 0xFF, 0x41, 0x82, 0x00, 0x0C }; + const u8 newcode[] = { 0x54, 0x60, 0xF7, 0xFF, 0x40, 0x82, 0x00, 0x0C, 0x54, 0x60, 0x07, 0xFF, 0x48, 0x00, 0x00, 0x0C }; - int n; + int n; - /* Patch cover register */ + /* Patch cover register */ - for (n=0;n<(len-sizeof(oldcode));n+=4) { - if (memcmp(buffer+n, (void *) oldcode, sizeof(oldcode)) == 0) { - memcpy(buffer+n, (void *) newcode, sizeof(newcode)); - } + for(n=0;n<(len-sizeof(oldcode));n+=4) + { + if (memcmp(buffer+n, (void *) oldcode, sizeof(oldcode)) == 0) + { + memcpy(buffer+n, (void *) newcode, sizeof(newcode)); } + } } /** Thanks to WiiPower **/ -bool NewSuperMarioBrosPatch(void *Address, int Size) { - if (IOS_GetVersion() == 222 || IOS_GetVersion() == 223) return false; // Don't use this when using Hermes, it'll use the BCA fix instead... +bool NewSuperMarioBrosPatch(void *Address, int Size) +{ + if (IOS_GetVersion() == 222 || IOS_GetVersion() == 223) return false; // Don't use this when using Hermes, it'll use the BCA fix instead... - if (memcmp("SMNE", (char *)0x80000000, 4) == 0) { - u8 SearchPattern[32] = { 0x94, 0x21, 0xFF, 0xD0, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD7, 0x89, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; - u8 PatchData[32] = { 0x4E, 0x80, 0x00, 0x20, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD7, 0x89, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; + if (memcmp("SMNE", (char *)0x80000000, 4) == 0) + { + u8 SearchPattern[32] = { 0x94, 0x21, 0xFF, 0xD0, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD7, 0x89, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; + u8 PatchData[32] = { 0x4E, 0x80, 0x00, 0x20, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD7, 0x89, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; - void *Addr = Address; - void *Addr_end = Address+Size; + void *Addr = Address; + void *Addr_end = Address+Size; - while (Addr <= Addr_end-sizeof(SearchPattern)) { - if (memcmp(Addr, SearchPattern, sizeof(SearchPattern))==0) { - memcpy(Addr,PatchData,sizeof(PatchData)); - return true; - } - Addr += 4; - } - } else if (memcmp("SMN", (char *)0x80000000, 3) == 0) { - u8 SearchPattern[32] = { 0x94, 0x21, 0xFF, 0xD0, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD9, 0x39, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; - u8 PatchData[32] = { 0x4E, 0x80, 0x00, 0x20, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD9, 0x39, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; + while(Addr <= Addr_end-sizeof(SearchPattern)) + { + if(memcmp(Addr, SearchPattern, sizeof(SearchPattern))==0) + { + memcpy(Addr,PatchData,sizeof(PatchData)); + return true; + } + Addr += 4; + } + } + else if (memcmp("SMN", (char *)0x80000000, 3) == 0) + { + u8 SearchPattern[32] = { 0x94, 0x21, 0xFF, 0xD0, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD9, 0x39, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; + u8 PatchData[32] = { 0x4E, 0x80, 0x00, 0x20, 0x7C, 0x08, 0x02, 0xA6, 0x90, 0x01, 0x00, 0x34, 0x39, 0x61, 0x00, 0x30, 0x48, 0x12, 0xD9, 0x39, 0x7C, 0x7B, 0x1B, 0x78, 0x7C, 0x9C, 0x23, 0x78, 0x7C, 0xBD, 0x2B, 0x78 }; - void *Addr = Address; - void *Addr_end = Address+Size; + void *Addr = Address; + void *Addr_end = Address+Size; - while (Addr <= Addr_end-sizeof(SearchPattern)) { - if (memcmp(Addr, SearchPattern, sizeof(SearchPattern))==0) { - memcpy(Addr,PatchData,sizeof(PatchData)); - return true; - } - Addr += 4; - } - } - return false; + while(Addr <= Addr_end-sizeof(SearchPattern)) + { + if(memcmp(Addr, SearchPattern, sizeof(SearchPattern))==0) + { + memcpy(Addr,PatchData,sizeof(PatchData)); + return true; + } + Addr += 4; + } + } + return false; } void gamepatches(void * dst, int len, u8 videoSelected, u8 patchcountrystring, u8 vipatch) { - PretendThereIsADiscInTheDrive(dst, len); + PretendThereIsADiscInTheDrive(dst, len); - GXRModeObj** table = NULL; + GXRModeObj** table = NULL; if (videoSelected == 5) // patch { @@ -335,15 +345,15 @@ void gamepatches(void * dst, int len, u8 videoSelected, u8 patchcountrystring, u PatchCountryStrings(dst, len); NewSuperMarioBrosPatch(dst, len); - - do_wip_code((u8 *)0x80000000); + + do_wip_code((u8 *)0x80000000); //if(Settings.anti002fix == on) if (fix002 == 2) Anti_002_fix(dst, len); - - //patchdebug(dst, len); + + //patchdebug(dst, len); } @@ -355,11 +365,11 @@ s32 Apploader_Run(entry_point *entry, u8 cheat, u8 videoSelected, u8 vipatch, u8 u32 appldr_len; s32 ret; - gprintf("\nApploader_Run() started"); + gprintf("\nApploader_Run() started"); - //u32 geckoattached = usb_isgeckoalive(EXI_CHANNEL_1); - //if (geckoattached)usb_flush(EXI_CHANNEL_1); - geckoinit = InitGecko(); + //u32 geckoattached = usb_isgeckoalive(EXI_CHANNEL_1); + //if (geckoattached)usb_flush(EXI_CHANNEL_1); + geckoinit = InitGecko(); /* Read apploader header */ ret = WDVD_Read(buffer, 0x20, APPLDR_OFFSET); @@ -374,7 +384,7 @@ s32 Apploader_Run(entry_point *entry, u8 cheat, u8 videoSelected, u8 vipatch, u8 if (ret < 0) return ret; - /* Set apploader entry function */ + /* Set apploader entry function */ appldr_entry = (app_entry)buffer[4]; /* Call apploader entry */ @@ -385,7 +395,7 @@ s32 Apploader_Run(entry_point *entry, u8 cheat, u8 videoSelected, u8 vipatch, u8 if (error002fix!=0) { /* ERROR 002 fix (thanks to WiiPower for sharing this)*/ - *(u32 *)0x80003188 = *(u32 *)0x80003140; + *(u32 *)0x80003188 = *(u32 *)0x80003140; // *(u32 *)0x80003140 = *(u32 *)0x80003188; } @@ -398,7 +408,7 @@ s32 Apploader_Run(entry_point *entry, u8 cheat, u8 videoSelected, u8 vipatch, u8 hooktype = 1; memcpy((void*)0x80001800, (char*)0x80000000, 6); // For WiiRD /*HOOKS STUFF - FISHEARS*/ - printf("\n\tcode handler loaded"); + printf("\n\tcode handler loaded"); } for (;;) { @@ -440,7 +450,7 @@ s32 Apploader_Run(entry_point *entry, u8 cheat, u8 videoSelected, u8 vipatch, u8 *entry = (entry_point) load_dol_image(dolbuffer); } - if (dolbuffer) + if(dolbuffer) free(dolbuffer); } else if (alternatedol == 2) { diff --git a/source/usbloader/disc.c b/source/usbloader/disc.c index 087f8d89..c97632c8 100644 --- a/source/usbloader/disc.c +++ b/source/usbloader/disc.c @@ -15,7 +15,7 @@ #include "wbfs.h" #include "../gecko.h" #include "../fatmounter.h" - + /* Constants */ #define PTABLE_OFFSET 0x40000 #define WII_MAGIC 0x5D1C9EA3 @@ -44,7 +44,8 @@ void __Disc_SetLowMem(void) { memset(gameid, 0, 8); memcpy(gameid, (char*)Disc_ID, 6); - if ((strcmp(gameid,"R3XE6U")==0) || (strcmp(gameid,"R3XP6V")==0)) { + if ((strcmp(gameid,"R3XE6U")==0) || (strcmp(gameid,"R3XP6V")==0)) + { *GameID_Address = 0x80000000; // Game ID Address } @@ -84,13 +85,13 @@ void __Disc_SetVMode(u8 videoselected) { /* Select video mode */ switch (diskid[3]) { - /* PAL */ + /* PAL */ case 'P': - case 'D': + case 'D': case 'F': - case 'I': - case 'S': - case 'H': + case 'I': + case 'S': + case 'H': case 'X': case 'Y': case 'Z': @@ -150,8 +151,8 @@ void __Disc_SetVMode(u8 videoselected) { if (vmode->viTVMode & VI_NON_INTERLACE) VIDEO_WaitVSync(); } - gprintf("\nVideo mode - %s",((progressive)?"progressive":"interlaced")); - + gprintf("\nVideo mode - %s",((progressive)?"progressive":"interlaced")); + } void __Disc_SetTime(void) { @@ -235,12 +236,12 @@ s32 Disc_Wait(void) { } s32 Disc_SetUSB(const u8 *id) { - u32 part = 0; - if (wbfs_part_fs) { - part = wbfs_part_lba; - } else { - part = wbfs_part_idx ? wbfs_part_idx - 1 : 0; - } + u32 part = 0; + if (wbfs_part_fs) { + part = wbfs_part_lba; + } else { + part = wbfs_part_idx ? wbfs_part_idx - 1 : 0; + } /* Set USB mode */ return WDVD_SetUSBMode(id, part); @@ -278,9 +279,9 @@ s32 Disc_BootPartition(u64 offset, u8 videoselected, u8 cheat, u8 vipatch, u8 pa if (ret < 0) return ret; - char gameid[8]; - memset(gameid, 0, 8); - memcpy(gameid, (char*)Disc_ID, 6); + char gameid[8]; + memset(gameid, 0, 8); + memcpy(gameid, (char*)Disc_ID, 6); /* Setup low memory */ __Disc_SetLowMem(); @@ -295,8 +296,8 @@ s32 Disc_BootPartition(u64 offset, u8 videoselected, u8 cheat, u8 vipatch, u8 pa do_sd_code(gameid); } - //kill the USB and SD - USBDevice_deInit(); + //kill the USB and SD + USBDevice_deInit(); SDCard_deInit(); /* Set an appropiate video mode */ @@ -312,18 +313,18 @@ s32 Disc_BootPartition(u64 offset, u8 videoselected, u8 cheat, u8 vipatch, u8 pa WPAD_Disconnect(0); WPAD_Shutdown(); - // Anti-green screen fix - VIDEO_SetBlack(TRUE); - VIDEO_Flush(); - VIDEO_WaitVSync(); - gprintf("\n\nUSB Loader GX is done.\n\n"); + // Anti-green screen fix + VIDEO_SetBlack(TRUE); + VIDEO_Flush(); + VIDEO_WaitVSync(); + gprintf("\n\nUSB Loader GX is done.\n\n"); /* Shutdown IOS subsystems */ - // fix for PeppaPig (from NeoGamma) - extern void __exception_closeall(); - IRQ_Disable(); - __IOS_ShutdownSubsystems(); - __exception_closeall(); + // fix for PeppaPig (from NeoGamma) + extern void __exception_closeall(); + IRQ_Disable(); + __IOS_ShutdownSubsystems(); + __exception_closeall(); /* Jump to entry point */ p_entry(); diff --git a/source/usbloader/frag.c b/source/usbloader/frag.c index 618e9cd3..f85f7abc 100644 --- a/source/usbloader/frag.c +++ b/source/usbloader/frag.c @@ -17,243 +17,256 @@ int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void * FragList *frag_list = NULL; -void frag_init(FragList *ff, int maxnum) { - memset(ff, 0, sizeof(Fragment) * (maxnum+1)); - ff->maxnum = maxnum; +void frag_init(FragList *ff, int maxnum) +{ + memset(ff, 0, sizeof(Fragment) * (maxnum+1)); + ff->maxnum = maxnum; } -int frag_append(FragList *ff, u32 offset, u32 sector, u32 count) { - int n; - if (count) { - n = ff->num - 1; - if (ff->num > 0 - && ff->frag[n].offset + ff->frag[n].count == offset - && ff->frag[n].sector + ff->frag[n].count == sector) { - // merge - ff->frag[n].count += count; - } else { - // add - if (ff->num >= ff->maxnum) { - // too many fragments - return -500; - } - n = ff->num; - ff->frag[n].offset = offset; - ff->frag[n].sector = sector; - ff->frag[n].count = count; - ff->num++; - } - } - ff->size = offset + count; - return 0; +int frag_append(FragList *ff, u32 offset, u32 sector, u32 count) +{ + int n; + if (count) { + n = ff->num - 1; + if (ff->num > 0 + && ff->frag[n].offset + ff->frag[n].count == offset + && ff->frag[n].sector + ff->frag[n].count == sector) + { + // merge + ff->frag[n].count += count; + } + else + { + // add + if (ff->num >= ff->maxnum) { + // too many fragments + return -500; + } + n = ff->num; + ff->frag[n].offset = offset; + ff->frag[n].sector = sector; + ff->frag[n].count = count; + ff->num++; + } + } + ff->size = offset + count; + return 0; } -int _frag_append(void *ff, u32 offset, u32 sector, u32 count) { - return frag_append(ff, offset, sector, count); +int _frag_append(void *ff, u32 offset, u32 sector, u32 count) +{ + return frag_append(ff, offset, sector, count); } -int frag_concat(FragList *ff, FragList *src) { - int i, ret; - u32 size = ff->size; - //printf("concat: %d %d <- %d %d\n", ff->num, ff->size, src->num, src->size); - for (i=0; inum; i++) { - ret = frag_append(ff, size + src->frag[i].offset, - src->frag[i].sector, src->frag[i].count); - if (ret) return ret; - } - ff->size = size + src->size; - //printf("concat: -> %d %d\n", ff->num, ff->size); - return 0; +int frag_concat(FragList *ff, FragList *src) +{ + int i, ret; + u32 size = ff->size; + //printf("concat: %d %d <- %d %d\n", ff->num, ff->size, src->num, src->size); + for (i=0; inum; i++) { + ret = frag_append(ff, size + src->frag[i].offset, + src->frag[i].sector, src->frag[i].count); + if (ret) return ret; + } + ff->size = size + src->size; + //printf("concat: -> %d %d\n", ff->num, ff->size); + return 0; } // in case a sparse block is requested, // the returned poffset might not be equal to requested offset // the difference should be filled with 0 int frag_get(FragList *ff, u32 offset, u32 count, - u32 *poffset, u32 *psector, u32 *pcount) { - int i; - u32 delta; - //printf("frag_get(%u %u)\n", offset, count); - for (i=0; inum; i++) { - if (ff->frag[i].offset <= offset - && ff->frag[i].offset + ff->frag[i].count > offset) { - delta = offset - ff->frag[i].offset; - *poffset = offset; - *psector = ff->frag[i].sector + delta; - *pcount = ff->frag[i].count - delta; - if (*pcount > count) *pcount = count; - goto out; - } - if (ff->frag[i].offset > offset - && ff->frag[i].offset < offset + count) { - delta = ff->frag[i].offset - offset; - *poffset = ff->frag[i].offset; - *psector = ff->frag[i].sector; - *pcount = ff->frag[i].count; - count -= delta; - if (*pcount > count) *pcount = count; - goto out; - } - } - // not found - if (offset + count > ff->size) { - // error: out of range! - return -1; - } - // if inside range, then it must be just sparse, zero filled - // return empty block at the end of requested - *poffset = offset + count; - *psector = 0; - *pcount = 0; -out: - //printf("=>(%u %u %u)\n", *poffset, *psector, *pcount); - return 0; + u32 *poffset, u32 *psector, u32 *pcount) +{ + int i; + u32 delta; + //printf("frag_get(%u %u)\n", offset, count); + for (i=0; inum; i++) { + if (ff->frag[i].offset <= offset + && ff->frag[i].offset + ff->frag[i].count > offset) + { + delta = offset - ff->frag[i].offset; + *poffset = offset; + *psector = ff->frag[i].sector + delta; + *pcount = ff->frag[i].count - delta; + if (*pcount > count) *pcount = count; + goto out; + } + if (ff->frag[i].offset > offset + && ff->frag[i].offset < offset + count) + { + delta = ff->frag[i].offset - offset; + *poffset = ff->frag[i].offset; + *psector = ff->frag[i].sector; + *pcount = ff->frag[i].count; + count -= delta; + if (*pcount > count) *pcount = count; + goto out; + } + } + // not found + if (offset + count > ff->size) { + // error: out of range! + return -1; + } + // if inside range, then it must be just sparse, zero filled + // return empty block at the end of requested + *poffset = offset + count; + *psector = 0; + *pcount = 0; + out: + //printf("=>(%u %u %u)\n", *poffset, *psector, *pcount); + return 0; } -int frag_remap(FragList *ff, FragList *log, FragList *phy) { - int i; - int ret; - u32 offset; - u32 sector; - u32 count; - u32 delta; - for (i=0; inum; i++) { - delta = 0; - count = 0; - do { - ret = frag_get(phy, - log->frag[i].sector + delta + count, - log->frag[i].count - delta - count, - &offset, §or, &count); - if (ret) return ret; // error - delta = offset - log->frag[i].sector; - ret = frag_append(ff, log->frag[i].offset + delta, sector, count); - if (ret) return ret; // error - } while (count + delta < log->frag[i].count); - } - return 0; +int frag_remap(FragList *ff, FragList *log, FragList *phy) +{ + int i; + int ret; + u32 offset; + u32 sector; + u32 count; + u32 delta; + for (i=0; inum; i++) { + delta = 0; + count = 0; + do { + ret = frag_get(phy, + log->frag[i].sector + delta + count, + log->frag[i].count - delta - count, + &offset, §or, &count); + if (ret) return ret; // error + delta = offset - log->frag[i].sector; + ret = frag_append(ff, log->frag[i].offset + delta, sector, count); + if (ret) return ret; // error + } while (count + delta < log->frag[i].count); + } + return 0; } -int get_frag_list(u8 *id) { - char fname[1024]; - char fname1[1024]; - struct stat st; - FragList *fs = NULL; - FragList *fa = NULL; - FragList *fw = NULL; - int ret; - int i, j; - int is_wbfs = 0; - int ret_val = -1; +int get_frag_list(u8 *id) +{ + char fname[1024]; + char fname1[1024]; + struct stat st; + FragList *fs = NULL; + FragList *fa = NULL; + FragList *fw = NULL; + int ret; + int i, j; + int is_wbfs = 0; + int ret_val = -1; - if (wbfs_part_fs == PART_FS_WBFS) return 0; + if (wbfs_part_fs == PART_FS_WBFS) return 0; - ret = WBFS_FAT_find_fname(id, fname, sizeof(fname)); - if (!ret) return -1; + ret = WBFS_FAT_find_fname(id, fname, sizeof(fname)); + if (!ret) return -1; - if (strcasecmp(strrchr(fname,'.'), ".wbfs") == 0) { - is_wbfs = 1; - } + if (strcasecmp(strrchr(fname,'.'), ".wbfs") == 0) { + is_wbfs = 1; + } - fs = malloc(sizeof(FragList)); - fa = malloc(sizeof(FragList)); - fw = malloc(sizeof(FragList)); + fs = malloc(sizeof(FragList)); + fa = malloc(sizeof(FragList)); + fw = malloc(sizeof(FragList)); - frag_init(fa, MAX_FRAG); + frag_init(fa, MAX_FRAG); - for (i=0; i<10; i++) { - frag_init(fs, MAX_FRAG); - if (i > 0) { - fname[strlen(fname)-1] = '0' + i; - if (stat(fname, &st) == -1) break; - } - strcpy(fname1, fname); - //printf("::*%s\n", strrchr(fname,'/')); - if (wbfs_part_fs == PART_FS_FAT) { - ret = _FAT_get_fragments(fname, &_frag_append, fs); - if (ret) { - printf("fat getf: %d\n", ret); - // don't return failure, let it fallback to old method - //ret_val = ret; - ret_val = 0; - goto out; - } - } else if (wbfs_part_fs == PART_FS_NTFS) { - ret = _NTFS_get_fragments(fname, &_frag_append, fs); - if (ret) { - printf("ntfs getf: %d\n", ret); - if (ret == -50 || ret == -500) { - printf("Too many fragments! %d\n", fs->num); - } - ret_val = ret; - goto out; - } - // offset to start of partition - for (j=0; jnum; j++) { - fs->frag[j].sector += fs_ntfs_sec; - } - } - frag_concat(fa, fs); - } + for (i=0; i<10; i++) { + frag_init(fs, MAX_FRAG); + if (i > 0) { + fname[strlen(fname)-1] = '0' + i; + if (stat(fname, &st) == -1) break; + } + strcpy(fname1, fname); + //printf("::*%s\n", strrchr(fname,'/')); + if (wbfs_part_fs == PART_FS_FAT) { + ret = _FAT_get_fragments(fname, &_frag_append, fs); + if (ret) { + printf("fat getf: %d\n", ret); + // don't return failure, let it fallback to old method + //ret_val = ret; + ret_val = 0; + goto out; + } + } else if (wbfs_part_fs == PART_FS_NTFS) { + ret = _NTFS_get_fragments(fname, &_frag_append, fs); + if (ret) { + printf("ntfs getf: %d\n", ret); + if (ret == -50 || ret == -500) { + printf("Too many fragments! %d\n", fs->num); + } + ret_val = ret; + goto out; + } + // offset to start of partition + for (j=0; jnum; j++) { + fs->frag[j].sector += fs_ntfs_sec; + } + } + frag_concat(fa, fs); + } - frag_list = malloc(sizeof(FragList)); - frag_init(frag_list, MAX_FRAG); - if (is_wbfs) { - // if wbfs file format, remap. - //printf("=====\n"); - wbfs_disc_t *d = WBFS_OpenDisc(id); - if (!d) goto out; - frag_init(fw, MAX_FRAG); - ret = wbfs_get_fragments(d, &_frag_append, fw); - if (ret) goto out; - WBFS_CloseDisc(d); - // DEBUG: frag_list->num = MAX_FRAG-10; // stress test - ret = frag_remap(frag_list, fw, fa); - if (ret) goto out; - } else { - // .iso does not need remap just copy - //printf("fa:\n"); - memcpy(frag_list, fa, sizeof(FragList)); - } + frag_list = malloc(sizeof(FragList)); + frag_init(frag_list, MAX_FRAG); + if (is_wbfs) { + // if wbfs file format, remap. + //printf("=====\n"); + wbfs_disc_t *d = WBFS_OpenDisc(id); + if (!d) goto out; + frag_init(fw, MAX_FRAG); + ret = wbfs_get_fragments(d, &_frag_append, fw); + if (ret) goto out; + WBFS_CloseDisc(d); + // DEBUG: frag_list->num = MAX_FRAG-10; // stress test + ret = frag_remap(frag_list, fw, fa); + if (ret) goto out; + } else { + // .iso does not need remap just copy + //printf("fa:\n"); + memcpy(frag_list, fa, sizeof(FragList)); + } - ret_val = 0; + ret_val = 0; out: - if (ret_val) { - // error - SAFE_FREE(frag_list); - } - SAFE_FREE(fs); - SAFE_FREE(fa); - SAFE_FREE(fw); - return ret_val; + if (ret_val) { + // error + SAFE_FREE(frag_list); + } + SAFE_FREE(fs); + SAFE_FREE(fa); + SAFE_FREE(fw); + return ret_val; } -int set_frag_list(u8 *id) { - if (wbfs_part_fs == PART_FS_WBFS) return 0; - if (frag_list == NULL) { - if (wbfs_part_fs == PART_FS_FAT) { - // fall back to old fat method - printf("FAT: fallback to old method\n"); - return 0; - } - // ntfs has no fallback, return error - return -1; - } +int set_frag_list(u8 *id) +{ + if (wbfs_part_fs == PART_FS_WBFS) return 0; + if (frag_list == NULL) { + if (wbfs_part_fs == PART_FS_FAT) { + // fall back to old fat method + printf("FAT: fallback to old method\n"); + return 0; + } + // ntfs has no fallback, return error + return -1; + } - // (+1 for header which is same size as fragment) - int size = sizeof(Fragment) * (frag_list->num + 1); - int ret = USBStorage_WBFS_SetFragList(frag_list, size); - if (ret) { - printf("set_frag: %d\n", ret); - return ret; - } + // (+1 for header which is same size as fragment) + int size = sizeof(Fragment) * (frag_list->num + 1); + int ret = USBStorage_WBFS_SetFragList(frag_list, size); + if (ret) { + printf("set_frag: %d\n", ret); + return ret; + } - // verify id matches - char discid[8]; - memset(discid, 0, sizeof(discid)); - ret = USBStorage_WBFS_Read(0, 6, discid); - return 0; + // verify id matches + char discid[8]; + memset(discid, 0, sizeof(discid)); + ret = USBStorage_WBFS_Read(0, 6, discid); + return 0; } diff --git a/source/usbloader/frag.h b/source/usbloader/frag.h index 0c01e490..1d83ff61 100644 --- a/source/usbloader/frag.h +++ b/source/usbloader/frag.h @@ -11,38 +11,40 @@ extern "C" { #include "libwbfs/libwbfs.h" - typedef struct { - u32 offset; // file offset, in sectors unit - u32 sector; - u32 count; - } Fragment; +typedef struct +{ + u32 offset; // file offset, in sectors unit + u32 sector; + u32 count; +} Fragment; - typedef struct { - u32 size; // num sectors - u32 num; // num fragments - u32 maxnum; - Fragment frag[MAX_FRAG]; - } FragList; +typedef struct +{ + u32 size; // num sectors + u32 num; // num fragments + u32 maxnum; + Fragment frag[MAX_FRAG]; +} FragList; - typedef int (*frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); +typedef int (*frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); - int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void *callback_data); +int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void *callback_data); - void frag_init(FragList *ff, int maxnum); - int frag_append(FragList *ff, u32 offset, u32 sector, u32 count); - int _frag_append(void *ff, u32 offset, u32 sector, u32 count); - int frag_concat(FragList *ff, FragList *src); +void frag_init(FragList *ff, int maxnum); +int frag_append(FragList *ff, u32 offset, u32 sector, u32 count); +int _frag_append(void *ff, u32 offset, u32 sector, u32 count); +int frag_concat(FragList *ff, FragList *src); // in case a sparse block is requested, // the returned poffset might not be equal to requested offset // the difference should be filled with 0 - int frag_get(FragList *ff, u32 offset, u32 count, - u32 *poffset, u32 *psector, u32 *pcount); +int frag_get(FragList *ff, u32 offset, u32 count, + u32 *poffset, u32 *psector, u32 *pcount); - int frag_remap(FragList *ff, FragList *log, FragList *phy); +int frag_remap(FragList *ff, FragList *log, FragList *phy); - int get_frag_list(u8 *id); - int set_frag_list(u8 *id); +int get_frag_list(u8 *id); +int set_frag_list(u8 *id); #ifdef __cplusplus } diff --git a/source/usbloader/getentries.cpp b/source/usbloader/getentries.cpp index c21eb552..afd54079 100644 --- a/source/usbloader/getentries.cpp +++ b/source/usbloader/getentries.cpp @@ -32,24 +32,27 @@ extern u8 mountMethod; /**************************************************************************** * wcsdup_new based on new wchar_t [...] ***************************************************************************/ -static wchar_t *wcsdup_new(const wchar_t *src) { - int len = wcslen(src)+1; - wchar_t *dst = new wchar_t[len]; - if (dst) wcscpy(dst, src); - return dst; +static wchar_t *wcsdup_new(const wchar_t *src) +{ + int len = wcslen(src)+1; + wchar_t *dst = new wchar_t[len]; + if(dst) wcscpy(dst, src); + return dst; } -static inline int wcsnicmp(const wchar_t *s1, const wchar_t *s2, int len) { - if (len <= 0) - return (0); - do { - int r = towupper(*s1) - towupper(*s2++); - if (r) return r; - if (*s1++ == 0) - break; +static inline int wcsnicmp(const wchar_t *s1, const wchar_t *s2, int len) +{ + if (len <= 0) + return (0); + do + { + int r = towupper(*s1) - towupper(*s2++); + if (r) return r; + if (*s1++ == 0) + break; } while (--len != 0); - - return (0); -} + + return (0); +} /**************************************************************************** @@ -120,167 +123,176 @@ s32 __Menu_EntryCmpFavorite(const void *a, const void *b) { * Get PrevFilter ***************************************************************************/ -int __Menu_GetPrevFilter(int t, wchar_t* gameFilter, u32 gameFiltered, wchar_t **PgameFilterPrev) { +int __Menu_GetPrevFilter(int t, wchar_t* gameFilter, u32 gameFiltered, wchar_t **PgameFilterPrev) +{ - std::vector nameList; + std::vector nameList; - struct discHdr *buffer = NULL; - u32 cnt, len, i; - s32 ret; - - wchar_t *new_gameFilterPrev = wcsdup_new(gameFilter); + struct discHdr *buffer = NULL; + u32 cnt, len, i; + s32 ret; + + wchar_t *new_gameFilterPrev = wcsdup_new(gameFilter); - /* Get list length */ - ret = WBFS_GetCount(&cnt); - if (ret < 0) - return ret; + /* Get list length */ + ret = WBFS_GetCount(&cnt); + if (ret < 0) + return ret; - /* Buffer length */ - len = sizeof(struct discHdr) * cnt; + /* Buffer length */ + len = sizeof(struct discHdr) * cnt; - /* Allocate memory */ - buffer = (struct discHdr *)memalign(32, len); - if (!buffer) - return -1; + /* Allocate memory */ + buffer = (struct discHdr *)memalign(32, len); + if (!buffer) + return -1; - /* Clear buffer */ - memset(buffer, 0, len); + /* Clear buffer */ + memset(buffer, 0, len); - /* Get header list */ - ret = WBFS_GetHeaders(buffer, cnt, sizeof(struct discHdr)); - if (ret < 0) { - if (buffer) free(buffer); - return ret; - } - /* Fill nameList */ - for (i = 0; i < cnt; i++) { - struct discHdr *header = &buffer[i]; + /* Get header list */ + ret = WBFS_GetHeaders(buffer, cnt, sizeof(struct discHdr)); + if (ret < 0) { + if (buffer) free(buffer); + return ret; + } + /* Fill nameList */ + for (i = 0; i < cnt; i++) + { + struct discHdr *header = &buffer[i]; - /* Register game */ - NewTitles::Instance()->CheckGame(header->id); + /* Register game */ + NewTitles::Instance()->CheckGame(header->id); - /* Filter Favorite */ - if (Settings.fave && t==0) { - struct Game_NUM* game_num = CFG_get_game_num(header->id); - if (!game_num || game_num->favorite==0) - continue; - } - /* Filter Pparental */ - if (Settings.parentalcontrol && !Settings.godmode && t==0) - if (get_block(header) >= Settings.parentalcontrol) - continue; + /* Filter Favorite */ + if (Settings.fave && t==0) + { + struct Game_NUM* game_num = CFG_get_game_num(header->id); + if (!game_num || game_num->favorite==0) + continue; + } + /* Filter Pparental */ + if (Settings.parentalcontrol && !Settings.godmode && t==0) + if(get_block(header) >= Settings.parentalcontrol) + continue; - /* Other parental control method */ - if (Settings.parentalcontrol == 0 && Settings.godmode == 0 && Settings.parental.enabled == 1) { - // Check game rating in WiiTDB, since the default Wii parental control setting is enabled - s32 rating = GetRatingForGame((char *) header->id); + /* Other parental control method */ + if (Settings.parentalcontrol == 0 && Settings.godmode == 0 && Settings.parental.enabled == 1) + { + // Check game rating in WiiTDB, since the default Wii parental control setting is enabled + s32 rating = GetRatingForGame((char *) header->id); + + if ((rating != -1 && rating > Settings.parental.rating) || + (rating == -1 && get_pegi_block(header) > Settings.parental.rating)) + { + continue; + } + } - if ((rating != -1 && rating > Settings.parental.rating) || - (rating == -1 && get_pegi_block(header) > Settings.parental.rating)) { - continue; - } - } + wchar_t *wname = FreeTypeGX::charToWideChar(get_title(header)); + if(wname) nameList.push_back(wname); + } + + NewTitles::Instance()->Save(); - wchar_t *wname = FreeTypeGX::charToWideChar(get_title(header)); - if (wname) nameList.push_back(wname); - } + /* delete buffer */ + if(buffer) free(buffer); - NewTitles::Instance()->Save(); + /* Find Prev-Filter */ + len = wcslen(new_gameFilterPrev); + while(len) + { + cnt = 0; + new_gameFilterPrev[--len] = 0; + for(std::vector::iterator iter = nameList.begin(); iter < nameList.end(); iter++) + { + if(!wcsncmp(*iter, new_gameFilterPrev, len)) + cnt++; + } + if(cnt > gameFiltered) + break; + } + /* Clean name List */ + for(std::vector::iterator iter = nameList.begin(); iter < nameList.end(); iter++) + delete [] *iter; - /* delete buffer */ - if (buffer) free(buffer); + if(PgameFilterPrev) + *PgameFilterPrev = new_gameFilterPrev; - /* Find Prev-Filter */ - len = wcslen(new_gameFilterPrev); - while (len) { - cnt = 0; - new_gameFilterPrev[--len] = 0; - for (std::vector::iterator iter = nameList.begin(); iter < nameList.end(); iter++) { - if (!wcsncmp(*iter, new_gameFilterPrev, len)) - cnt++; - } - if (cnt > gameFiltered) - break; - } - /* Clean name List */ - for (std::vector::iterator iter = nameList.begin(); iter < nameList.end(); iter++) - delete [] *iter; - - if (PgameFilterPrev) - *PgameFilterPrev = new_gameFilterPrev; - - return 0; + return 0; } /**************************************************************************** * Get GameFilter NextList ***************************************************************************/ + +int int_cmp(const void *a, const void *b) { return *((u32*)a)-*((u32*)b); } -int int_cmp(const void *a, const void *b) { - return *((u32*)a)-*((u32*)b); -} +int __Menu_GetGameFilter_NextList(discHdr *gameList, u32 gameCnt, wchar_t **PgameFilter, wchar_t **PgameFilterNextList) +{ + u32 filter_len = wcslen(*PgameFilter); + u32 i, lastChar=0; + bool autofill = filter_len > 0; // autofill only when gameFilter is not empty + wchar_t *p; + u32 *nextList = new u32[gameCnt]; if(nextList==NULL) return -1; + for(i=0; i 0; // autofill only when gameFilter is not empty - wchar_t *p; - u32 *nextList = new u32[gameCnt]; - if (nextList==NULL) return -1; - for (i=0; i filter_len) { - if ((filter_len == 0 || !wcsnicmp(*PgameFilter, gameName, filter_len))) - nextFilterChar = towupper(gameName[filter_len]); - } else if (wcslen(gameName) == filter_len) - autofill = false; // no autofill when gameNameLen == filterLen - - nextList[i] = nextFilterChar; - } - qsort(nextList, gameCnt, sizeof(u32), int_cmp); - - *PgameFilterNextList = new wchar_t[gameCnt+1]; - if (*PgameFilterNextList == NULL) goto error; - - - p = *PgameFilterNextList; - lastChar = 0; - for (i=0; i filter_len) + { + if((filter_len == 0 || !wcsnicmp(*PgameFilter, gameName, filter_len))) + nextFilterChar = towupper(gameName[filter_len]); + } + else if(wcslen(gameName) == filter_len) + autofill = false; // no autofill when gameNameLen == filterLen + + nextList[i] = nextFilterChar; + } + qsort(nextList, gameCnt, sizeof(u32), int_cmp); + + *PgameFilterNextList = new wchar_t[gameCnt+1]; + if(*PgameFilterNextList == NULL) goto error; + + + p = *PgameFilterNextList; + lastChar = 0; + for(i=0; ititle,sizeof(header->title),"%s",tmp); + //break; + } + } + } + if (!found) { + if (getName00(header->title, TITLE_ID(i=0) + found=2; - struct discHdr *header = &buffer[i]; - if (f) { - while (fgets(line, sizeof(line), f)) { - if (line[0]== text[0]&& - line[1]== text[1]&& - line[2]== text[2]) { - int j=0; - found=1; - for (j=0;(line[j+4]!='\0' || j<51);j++) - - tmp[j]=line[j+4]; - snprintf(header->title,sizeof(header->title),"%s",tmp); - //break; - } - } - } - if (!found) { - if (getName00(header->title, TITLE_ID(i=0) - found=2; - - if (!found) { - if (getNameBN(header->title, TITLE_ID(i=0) - found=3; - - if (!found) - snprintf(header->title,sizeof(header->title),"%s (%08x)",text,iid[0]=text[0]; - header->id[1]=text[1]; - header->id[2]=text[2]; - header->id[3]=text[3]; - header->id[4]='1'; - header->id[5]=(i + if (!found) { + if (getNameBN(header->title, TITLE_ID(i=0) + found=3; + if (!found) + snprintf(header->title,sizeof(header->title),"%s (%08x)",text,iid[0]=text[0]; + header->id[1]=text[1]; + header->id[2]=text[2]; + header->id[3]=text[3]; + header->id[4]='1'; + header->id[5]=(i + //not using these filters right now, but i left them in just in case - // Filters - /*if (Settings.fave) { - struct Game_NUM* game_num = CFG_get_game_num(header->id); - if (!game_num || game_num->favorite==0) - continue; - } - - if (Settings.parentalcontrol && !Settings.godmode) { - if (get_block(header) >= Settings.parentalcontrol) - continue; - }*/ - - if (gameFilter && *gameFilter) { - u32 filter_len = wcslen(gameFilter); - wchar_t *gameName = FreeTypeGX::charToWideChar(get_title(header)); - if (!gameName || wcsnicmp(gameName, gameFilter, filter_len)) { - delete [] gameName; - continue; - } - } - if (i != cnt2) - buffer[cnt2] = buffer[i]; - cnt2++; - } + // Filters + /*if (Settings.fave) { + struct Game_NUM* game_num = CFG_get_game_num(header->id); + if (!game_num || game_num->favorite==0) + continue; + } + + if (Settings.parentalcontrol && !Settings.godmode) { + if (get_block(header) >= Settings.parentalcontrol) + continue; + }*/ + + if(gameFilter && *gameFilter) { + u32 filter_len = wcslen(gameFilter); + wchar_t *gameName = FreeTypeGX::charToWideChar(get_title(header)); + if (!gameName || wcsnicmp(gameName, gameFilter, filter_len)) { + delete [] gameName; + continue; + } + } + if(i != cnt2) + buffer[cnt2] = buffer[i]; + cnt2++; + } i++; } - - if (f)fclose(f); + + if (f)fclose(f); Uninstall_FromTitle(TITLE_ID(1, 0)); ISFS_Deinitialize(); - - if (cnt > cnt2) { - cnt = cnt2; - buffer = (struct discHdr *)realloc(buffer, sizeof(struct discHdr) * cnt); - } - if (!buffer) - return -1; - - if (Settings.sort==pcount) { - qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpCount); - } else if (Settings.fave) { - qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpFavorite); - } else { - qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmp); - } - /*PgameList = buffer; - buffer = NULL; - PgameCnt = cnt;*/ - - if (PgameList) *PgameList = buffer; - else free(buffer); - if (PgameCnt) *PgameCnt = cnt; - + + if(cnt > cnt2) + { + cnt = cnt2; + buffer = (struct discHdr *)realloc(buffer, sizeof(struct discHdr) * cnt); + } + if (!buffer) + return -1; + + if (Settings.sort==pcount) { + qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpCount); + } else if (Settings.fave) { + qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpFavorite); + } else { + qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmp); + } + /*PgameList = buffer; + buffer = NULL; + PgameCnt = cnt;*/ + + if(PgameList) *PgameList = buffer; else free(buffer); + if(PgameCnt) *PgameCnt = cnt; + return 0; - + return cnt; } @@ -474,139 +487,140 @@ int __Menu_GetGameList(int t, wchar_t* gameFilter, discHdr ** PgameList, u32 *Pg if (buffer) free(buffer); return ret; } - + for (u32 i = 0; i < cnt; i++) { - struct discHdr *header = &buffer[i]; + struct discHdr *header = &buffer[i]; - /* Register game */ - NewTitles::Instance()->CheckGame(header->id); + /* Register game */ + NewTitles::Instance()->CheckGame(header->id); - /* Filters */ - if (Settings.fave && t==0) { - struct Game_NUM* game_num = CFG_get_game_num(header->id); - if (!game_num || game_num->favorite==0) - continue; - } + /* Filters */ + if (Settings.fave && t==0) { + struct Game_NUM* game_num = CFG_get_game_num(header->id); + if (!game_num || game_num->favorite==0) + continue; + } - //ignore uLoader cfg "iso". i was told it is "__CFG_" but not confirmed - if (header->id[0]=='_'&&header->id[1]=='_'&& - header->id[2]=='C'&&header->id[3]=='F'&& - header->id[4]=='G'&&header->id[5]=='_') - continue; + //ignore uLoader cfg "iso". i was told it is "__CFG_" but not confirmed + if (header->id[0]=='_'&&header->id[1]=='_'&& + header->id[2]=='C'&&header->id[3]=='F'&& + header->id[4]=='G'&&header->id[5]=='_') + continue; + + if (Settings.parentalcontrol && !Settings.godmode && t==0) { + if (get_block(header) >= Settings.parentalcontrol) + continue; + } - if (Settings.parentalcontrol && !Settings.godmode && t==0) { - if (get_block(header) >= Settings.parentalcontrol) - continue; - } - - /* Other parental control method */ - if (Settings.parentalcontrol == 0 && Settings.godmode == 0 && Settings.parental.enabled == 1 && t==0) { - // Check game rating in WiiTDB, since the default Wii parental control setting is enabled - s32 rating = GetRatingForGame((char *) header->id); - if ((rating != -1 && rating > Settings.parental.rating) || - (rating == -1 && get_pegi_block(header) > Settings.parental.rating)) { - continue; - } - } - - if (gameFilter && *gameFilter && t==0) { - u32 filter_len = wcslen(gameFilter); - wchar_t *gameName = FreeTypeGX::charToWideChar(get_title(header)); - if (!gameName || wcsnicmp(gameName, gameFilter, filter_len)) { - delete [] gameName; - continue; - } - } - if (i != cnt2) - buffer[cnt2] = buffer[i]; - cnt2++; - } - NewTitles::Instance()->Save(); - - if (cnt > cnt2) { - cnt = cnt2; - buffer = (struct discHdr *)realloc(buffer, sizeof(struct discHdr) * cnt); - } - if (!buffer) - return -1; - - if (Settings.sort==pcount) { - qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpCount); - } else if (Settings.fave) { - qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpFavorite); - } else { - qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmp); - } - - /* Set values */ - if (PgameList) *PgameList = buffer; - else free(buffer); - if (PgameCnt) *PgameCnt = cnt; + /* Other parental control method */ + if (Settings.parentalcontrol == 0 && Settings.godmode == 0 && Settings.parental.enabled == 1 && t==0) + { + // Check game rating in WiiTDB, since the default Wii parental control setting is enabled + s32 rating = GetRatingForGame((char *) header->id); + if ((rating != -1 && rating > Settings.parental.rating) || + (rating == -1 && get_pegi_block(header) > Settings.parental.rating)) + { + continue; + } + } + + if(gameFilter && *gameFilter && t==0) { + u32 filter_len = wcslen(gameFilter); + wchar_t *gameName = FreeTypeGX::charToWideChar(get_title(header)); + if (!gameName || wcsnicmp(gameName, gameFilter, filter_len)) { + delete [] gameName; + continue; + } + } + if(i != cnt2) + buffer[cnt2] = buffer[i]; + cnt2++; + } + NewTitles::Instance()->Save(); + + if(cnt > cnt2) + { + cnt = cnt2; + buffer = (struct discHdr *)realloc(buffer, sizeof(struct discHdr) * cnt); + } + if (!buffer) + return -1; + + if (Settings.sort==pcount) { + qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpCount); + } else if (Settings.fave) { + qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmpFavorite); + } else { + qsort(buffer, cnt, sizeof(struct discHdr), __Menu_EntryCmp); + } + /* Set values */ + if(PgameList) *PgameList = buffer; else free(buffer); + if(PgameCnt) *PgameCnt = cnt; + return 0; } int __Menu_GetEntries(int t, const wchar_t* Filter) { - /*if (mountMethod==3) - { - return buildTitleList(); - }*/ + /*if (mountMethod==3) + { + return buildTitleList(); + }*/ + + + u32 new_gameCnt = 0; + struct discHdr *new_gameList = NULL; + wchar_t *new_gameFilter = NULL; + wchar_t *new_gameFilterNextList = NULL; + wchar_t *new_gameFilterPrev = NULL; + new_gameFilter = wcsdup_new(Filter ? Filter : (gameFilter ? gameFilter : L"") ); + if(new_gameFilter == NULL) return -1; + + for(;;) + { + if (mountMethod==3) + {if(buildTitleList(t, new_gameFilter, &new_gameList, &new_gameCnt) < 0) + return -1;} + + else + {if(__Menu_GetGameList(t, new_gameFilter, &new_gameList, &new_gameCnt) < 0) + return -1;} + + + if(new_gameCnt > 0 || new_gameFilter[0] == 0) + break; + new_gameFilter[wcslen(new_gameFilter)-1] = 0; + } - u32 new_gameCnt = 0; - struct discHdr *new_gameList = NULL; - wchar_t *new_gameFilter = NULL; - wchar_t *new_gameFilterNextList = NULL; - wchar_t *new_gameFilterPrev = NULL; + /* init GameFilterNextList */ + if(__Menu_GetGameFilter_NextList(new_gameList, new_gameCnt, &new_gameFilter, &new_gameFilterNextList) < 0) + goto error; + + /* init GameFilterPrev */ + if(__Menu_GetPrevFilter(t, new_gameFilter, new_gameCnt, &new_gameFilterPrev) < 0) + goto error; + + /* Set values */ + if(gameList) free(gameList); + if(gameFilter) delete [] gameFilter; + if(gameFilterNextList) delete [] gameFilterNextList; + if(gameFilterPrev) delete [] gameFilterPrev; - new_gameFilter = wcsdup_new(Filter ? Filter : (gameFilter ? gameFilter : L"") ); - if (new_gameFilter == NULL) return -1; + gameList = new_gameList; + gameCnt = new_gameCnt; + gameFilter = new_gameFilter; + gameFilterNextList = new_gameFilterNextList; + gameFilterPrev = new_gameFilterPrev; - for (;;) { - if (mountMethod==3) { - if (buildTitleList(t, new_gameFilter, &new_gameList, &new_gameCnt) < 0) - return -1; - } - - else { - if (__Menu_GetGameList(t, new_gameFilter, &new_gameList, &new_gameCnt) < 0) - return -1; - } - - - if (new_gameCnt > 0 || new_gameFilter[0] == 0) - break; - new_gameFilter[wcslen(new_gameFilter)-1] = 0; - } - - /* init GameFilterNextList */ - if (__Menu_GetGameFilter_NextList(new_gameList, new_gameCnt, &new_gameFilter, &new_gameFilterNextList) < 0) - goto error; - - /* init GameFilterPrev */ - if (__Menu_GetPrevFilter(t, new_gameFilter, new_gameCnt, &new_gameFilterPrev) < 0) - goto error; - - /* Set values */ - if (gameList) free(gameList); - if (gameFilter) delete [] gameFilter; - if (gameFilterNextList) delete [] gameFilterNextList; - if (gameFilterPrev) delete [] gameFilterPrev; - - gameList = new_gameList; - gameCnt = new_gameCnt; - gameFilter = new_gameFilter; - gameFilterNextList = new_gameFilterNextList; - gameFilterPrev = new_gameFilterPrev; - - /* Reset variables */ - gameSelected = gameStart = 0; - return 0; + /* Reset variables */ + gameSelected = gameStart = 0; + return 0; error: // clean up - if (new_gameList) free(new_gameList); - if (new_gameFilter) delete [] new_gameFilter; - if (new_gameFilterNextList) delete [] new_gameFilterNextList; - if (new_gameFilterPrev) delete [] new_gameFilterPrev; - return -1; + if(new_gameList) free(new_gameList); + if(new_gameFilter) delete [] new_gameFilter; + if(new_gameFilterNextList) delete [] new_gameFilterNextList; + if(new_gameFilterPrev) delete [] new_gameFilterPrev; + return -1; } diff --git a/source/usbloader/partition_usbloader.c b/source/usbloader/partition_usbloader.c index 0a589ea5..adc28c53 100644 --- a/source/usbloader/partition_usbloader.c +++ b/source/usbloader/partition_usbloader.c @@ -14,367 +14,360 @@ /* 'partition table' structure */ typedef struct { - /* Zero bytes */ - u8 padding[446]; + /* Zero bytes */ + u8 padding[446]; - /* Partition table entries */ - partitionEntry entries[MAX_PARTITIONS]; + /* Partition table entries */ + partitionEntry entries[MAX_PARTITIONS]; } ATTRIBUTE_PACKED partitionTable; -s32 Partition_GetEntries(u32 device, partitionEntry *outbuf, u32 *outval) { - static partitionTable table ATTRIBUTE_ALIGN(32); +s32 Partition_GetEntries(u32 device, partitionEntry *outbuf, u32 *outval) +{ + static partitionTable table ATTRIBUTE_ALIGN(32); - u32 cnt, sector_size; - s32 ret; + u32 cnt, sector_size; + s32 ret; - /* Read from specified device */ - switch (device) { - case WBFS_DEVICE_USB: { - /* Get sector size */ - ret = USBStorage_GetCapacity(§or_size); - if (ret == 0) - return -1; + /* Read from specified device */ + switch (device) { + case WBFS_DEVICE_USB: { + /* Get sector size */ + ret = USBStorage_GetCapacity(§or_size); + if (ret == 0) + return -1; - /* Read partition table */ - ret = USBStorage_ReadSectors(0, 1, &table); - if (ret < 0) - return ret; + /* Read partition table */ + ret = USBStorage_ReadSectors(0, 1, &table); + if (ret < 0) + return ret; - break; - } + break; + } - case WBFS_DEVICE_SDHC: { - /* SDHC sector size */ - sector_size = SDHC_SECTOR_SIZE; + case WBFS_DEVICE_SDHC: { + /* SDHC sector size */ + sector_size = SDHC_SECTOR_SIZE; - /* Read partition table */ - ret = SDHC_ReadSectors(0, 1, &table); - if (!ret) - return -1; + /* Read partition table */ + ret = SDHC_ReadSectors(0, 1, &table); + if (!ret) + return -1; - break; - } + break; + } - default: - return -1; - } + default: + return -1; + } - /* Swap endianess */ - for (cnt = 0; cnt < 4; cnt++) { - partitionEntry *entry = &table.entries[cnt]; + /* Swap endianess */ + for (cnt = 0; cnt < 4; cnt++) { + partitionEntry *entry = &table.entries[cnt]; - entry->sector = swap32(entry->sector); - entry->size = swap32(entry->size); - } + entry->sector = swap32(entry->sector); + entry->size = swap32(entry->size); + } - /* Set partition entries */ - memcpy(outbuf, table.entries, sizeof(table.entries)); + /* Set partition entries */ + memcpy(outbuf, table.entries, sizeof(table.entries)); - /* Set sector size */ - *outval = sector_size; + /* Set sector size */ + *outval = sector_size; - return 0; + return 0; } -bool Device_ReadSectors(u32 device, u32 sector, u32 count, void *buffer) { - s32 ret; +bool Device_ReadSectors(u32 device, u32 sector, u32 count, void *buffer) +{ + s32 ret; - /* Read from specified device */ - switch (device) { - case WBFS_DEVICE_USB: - ret = USBStorage_ReadSectors(sector, count, buffer); - if (ret < 0) - return false; - return true; + /* Read from specified device */ + switch (device) { + case WBFS_DEVICE_USB: + ret = USBStorage_ReadSectors(sector, count, buffer); + if (ret < 0) + return false; + return true; - case WBFS_DEVICE_SDHC: - return SDHC_ReadSectors(sector, count, buffer); - } + case WBFS_DEVICE_SDHC: + return SDHC_ReadSectors(sector, count, buffer); + } - return false; + return false; } -bool Device_WriteSectors(u32 device, u32 sector, u32 count, void *buffer) { - s32 ret; +bool Device_WriteSectors(u32 device, u32 sector, u32 count, void *buffer) +{ + s32 ret; - /* Read from specified device */ - switch (device) { - case WBFS_DEVICE_USB: - ret = USBStorage_WriteSectors(sector, count, buffer); - if (ret < 0) - return false; - return true; + /* Read from specified device */ + switch (device) { + case WBFS_DEVICE_USB: + ret = USBStorage_WriteSectors(sector, count, buffer); + if (ret < 0) + return false; + return true; - case WBFS_DEVICE_SDHC: - return SDHC_WriteSectors(sector, count, buffer); - } + case WBFS_DEVICE_SDHC: + return SDHC_WriteSectors(sector, count, buffer); + } - return false; + return false; } -s32 Partition_GetEntriesEx(u32 device, partitionEntry *outbuf, u32 *psect_size, int *num) { - static partitionTable table ATTRIBUTE_ALIGN(32); - partitionEntry *entry; +s32 Partition_GetEntriesEx(u32 device, partitionEntry *outbuf, u32 *psect_size, int *num) +{ + static partitionTable table ATTRIBUTE_ALIGN(32); + partitionEntry *entry; - u32 i, sector_size; - s32 ret; - int maxpart = *num; + u32 i, sector_size; + s32 ret; + int maxpart = *num; - // Get sector size - switch (device) { - case WBFS_DEVICE_USB: - ret = USBStorage_GetCapacity(§or_size); - if (ret == 0) return -1; - break; - case WBFS_DEVICE_SDHC: - sector_size = SDHC_SECTOR_SIZE; - break; - default: - return -1; - } - /* Set sector size */ - *psect_size = sector_size; + // Get sector size + switch (device) { + case WBFS_DEVICE_USB: + ret = USBStorage_GetCapacity(§or_size); + if (ret == 0) return -1; + break; + case WBFS_DEVICE_SDHC: + sector_size = SDHC_SECTOR_SIZE; + break; + default: + return -1; + } + /* Set sector size */ + *psect_size = sector_size; - u32 ext = 0; - u32 next = 0; + u32 ext = 0; + u32 next = 0; - // Read partition table - ret = Device_ReadSectors(device, 0, 1, &table); - if (!ret) return -1; - // Check if it's a RAW WBFS disc, without partition table - if (get_fs_type(&table) == FS_TYPE_WBFS) { - memset(outbuf, 0, sizeof(table.entries)); - wbfs_head_t *head = (wbfs_head_t*)&table; - outbuf->size = wbfs_ntohl(head->n_hd_sec); - *num = 1; - return 0; - } - /* Swap endianess */ - for (i = 0; i < 4; i++) { - entry = &table.entries[i]; - entry->sector = swap32(entry->sector); - entry->size = swap32(entry->size); - if (!ext && part_is_extended(entry->type)) { - ext = entry->sector; - } - } - /* Set partition entries */ - memcpy(outbuf, table.entries, sizeof(table.entries)); - // num primary - *num = 4; + // Read partition table + ret = Device_ReadSectors(device, 0, 1, &table); + if (!ret) return -1; + // Check if it's a RAW WBFS disc, without partition table + if (get_fs_type(&table) == FS_TYPE_WBFS) { + memset(outbuf, 0, sizeof(table.entries)); + wbfs_head_t *head = (wbfs_head_t*)&table; + outbuf->size = wbfs_ntohl(head->n_hd_sec); + *num = 1; + return 0; + } + /* Swap endianess */ + for (i = 0; i < 4; i++) { + entry = &table.entries[i]; + entry->sector = swap32(entry->sector); + entry->size = swap32(entry->size); + if (!ext && part_is_extended(entry->type)) { + ext = entry->sector; + } + } + /* Set partition entries */ + memcpy(outbuf, table.entries, sizeof(table.entries)); + // num primary + *num = 4; - if (!ext) return 0; + if (!ext) return 0; - next = ext; - // scan extended partition for logical - for (i=0; isector = swap32(entry->sector); - entry->size = swap32(entry->size); - if (entry->type && entry->size && entry->sector) { - // rebase to abolute address - entry->sector += next; - // add logical - memcpy(&outbuf[*num], entry, sizeof(*entry)); - (*num)++; - // get next - entry++; - if (entry->type && entry->size && entry->sector) { - next = ext + swap32(entry->sector); - } else { - break; - } - } - } + next = ext; + // scan extended partition for logical + for(i=0; isector = swap32(entry->sector); + entry->size = swap32(entry->size); + if (entry->type && entry->size && entry->sector) { + // rebase to abolute address + entry->sector += next; + // add logical + memcpy(&outbuf[*num], entry, sizeof(*entry)); + (*num)++; + // get next + entry++; + if (entry->type && entry->size && entry->sector) { + next = ext + swap32(entry->sector); + } else { + break; + } + } + } - return 0; + return 0; } -bool part_is_extended(int type) { - if (type == 0x05) return true; - if (type == 0x0f) return true; - return false; +bool part_is_extended(int type) +{ + if (type == 0x05) return true; + if (type == 0x0f) return true; + return false; } -bool part_is_data(int type) { - if (type && !part_is_extended(type)) return true; - return false; +bool part_is_data(int type) +{ + if (type && !part_is_extended(type)) return true; + return false; } -bool part_valid_data(partitionEntry *entry) { - if (entry->size && entry->type && entry->sector) { - return part_is_data(entry->type); - } - return false; +bool part_valid_data(partitionEntry *entry) +{ + if (entry->size && entry->type && entry->sector) { + return part_is_data(entry->type); + } + return false; } -char* part_type_data(int type) { - switch (type) { - case 0x01: - return "FAT12"; - case 0x04: - return "FAT16"; - case 0x06: - return "FAT16"; //+ - case 0x07: - return "NTFS"; - case 0x0b: - return "FAT32"; - case 0x0c: - return "FAT32"; - case 0x0e: - return "FAT16"; - case 0x82: - return "LxSWP"; - case 0x83: - return "LINUX"; - case 0x8e: - return "LxLVM"; - case 0xa8: - return "OSX"; - case 0xab: - return "OSXBT"; - case 0xaf: - return "OSXHF"; - case 0xe8: - return "LUKS"; - } - return NULL; +char* part_type_data(int type) +{ + switch (type) { + case 0x01: return "FAT12"; + case 0x04: return "FAT16"; + case 0x06: return "FAT16"; //+ + case 0x07: return "NTFS"; + case 0x0b: return "FAT32"; + case 0x0c: return "FAT32"; + case 0x0e: return "FAT16"; + case 0x82: return "LxSWP"; + case 0x83: return "LINUX"; + case 0x8e: return "LxLVM"; + case 0xa8: return "OSX"; + case 0xab: return "OSXBT"; + case 0xaf: return "OSXHF"; + case 0xe8: return "LUKS"; + } + return NULL; } -char *part_type_name(int type) { - static char unk[8]; - if (type == 0) return "UNUSED"; - if (part_is_extended(type)) return "EXTEND"; - char *p = part_type_data(type); - if (p) return p; - sprintf(unk, "UNK-%02x", type); - return unk; +char *part_type_name(int type) +{ + static char unk[8]; + if (type == 0) return "UNUSED"; + if (part_is_extended(type)) return "EXTEND"; + char *p = part_type_data(type); + if (p) return p; + sprintf(unk, "UNK-%02x", type); + return unk; } -int get_fs_type(void *buff) { - char *buf = buff; - // WBFS - wbfs_head_t *head = (wbfs_head_t *)buf; - if (head->magic == wbfs_htonl(WBFS_MAGIC)) return FS_TYPE_WBFS; - // 55AA - if (buf[0x1FE] == 0x55 && buf[0x1FF] == 0xAA) { - // FAT - if (memcmp(buf+0x36,"FAT",3) == 0) return FS_TYPE_FAT16; - if (memcmp(buf+0x52,"FAT",3) == 0) return FS_TYPE_FAT32; - // NTFS - if (memcmp(buf+0x03,"NTFS",4) == 0) return FS_TYPE_NTFS; - } - return FS_TYPE_UNK; +int get_fs_type(void *buff) +{ + char *buf = buff; + // WBFS + wbfs_head_t *head = (wbfs_head_t *)buf; + if (head->magic == wbfs_htonl(WBFS_MAGIC)) return FS_TYPE_WBFS; + // 55AA + if (buf[0x1FE] == 0x55 && buf[0x1FF] == 0xAA) { + // FAT + if (memcmp(buf+0x36,"FAT",3) == 0) return FS_TYPE_FAT16; + if (memcmp(buf+0x52,"FAT",3) == 0) return FS_TYPE_FAT32; + // NTFS + if (memcmp(buf+0x03,"NTFS",4) == 0) return FS_TYPE_NTFS; + } + return FS_TYPE_UNK; } -int get_part_fs(int fs_type) { - switch (fs_type) { - case FS_TYPE_FAT32: - return PART_FS_FAT; - case FS_TYPE_NTFS: - return PART_FS_NTFS; - case FS_TYPE_WBFS: - return PART_FS_WBFS; - default: - return -1; - } +int get_part_fs(int fs_type) +{ + switch(fs_type) { + case FS_TYPE_FAT32: return PART_FS_FAT; + case FS_TYPE_NTFS: return PART_FS_NTFS; + case FS_TYPE_WBFS: return PART_FS_WBFS; + default: return -1; + } } -bool is_type_fat(int type) { - return (type == FS_TYPE_FAT16 || type == FS_TYPE_FAT32); +bool is_type_fat(int type) +{ + return (type == FS_TYPE_FAT16 || type == FS_TYPE_FAT32); } -char *get_fs_name(int i) { - switch (i) { - case FS_TYPE_FAT16: - return "FAT16"; - case FS_TYPE_FAT32: - return "FAT32"; - case FS_TYPE_NTFS: - return "NTFS"; - case FS_TYPE_WBFS: - return "WBFS"; - } - return ""; +char *get_fs_name(int i) +{ + switch (i) { + case FS_TYPE_FAT16: return "FAT16"; + case FS_TYPE_FAT32: return "FAT32"; + case FS_TYPE_NTFS: return "NTFS"; + case FS_TYPE_WBFS: return "WBFS"; + } + return ""; } -s32 Partition_GetList(u32 device, PartList *plist) { - partitionEntry *entry = NULL; - PartInfo *pinfo = NULL; - int i, ret; +s32 Partition_GetList(u32 device, PartList *plist) +{ + partitionEntry *entry = NULL; + PartInfo *pinfo = NULL; + int i, ret; - memset(plist, 0, sizeof(PartList)); + memset(plist, 0, sizeof(PartList)); - // Get partition entries - plist->num = MAX_PARTITIONS_EX; - ret = Partition_GetEntriesEx(device, plist->pentry, &plist->sector_size, &plist->num); - if (ret < 0) { - return -1; - } - // check for RAW WBFS disc - if (plist->num == 1) { - pinfo = &plist->pinfo[0]; - entry = &plist->pentry[0]; - plist->wbfs_n = 1; - pinfo->wbfs_i = pinfo->index = 1; - return 0; - } + // Get partition entries + plist->num = MAX_PARTITIONS_EX; + ret = Partition_GetEntriesEx(device, plist->pentry, &plist->sector_size, &plist->num); + if (ret < 0) { + return -1; + } + // check for RAW WBFS disc + if (plist->num == 1) { + pinfo = &plist->pinfo[0]; + entry = &plist->pentry[0]; + plist->wbfs_n = 1; + pinfo->wbfs_i = pinfo->index = 1; + return 0; + } - char buf[plist->sector_size]; + char buf[plist->sector_size]; - // scan partitions for filesystem type - for (i = 0; i < plist->num; i++) { - pinfo = &plist->pinfo[i]; - entry = &plist->pentry[i]; - if (!entry->size) continue; - if (!entry->type) continue; - if (!entry->sector) continue; - // even though wrong, it's possible WBFS is on an extended part. - //if (!part_is_data(entry->type)) continue; - if (!Device_ReadSectors(device, entry->sector, 1, buf)) continue; - pinfo->fs_type = get_fs_type(buf); - if (pinfo->fs_type == FS_TYPE_WBFS) { - // multiple wbfs on sdhc not supported - if (device == WBFS_DEVICE_SDHC && (plist->wbfs_n > 1 || i > 4)) continue; - plist->wbfs_n++; - pinfo->wbfs_i = pinfo->index = plist->wbfs_n; - } else if (is_type_fat(pinfo->fs_type)) { - plist->fat_n++; - pinfo->fat_i = pinfo->index = plist->fat_n; - } else if (pinfo->fs_type == FS_TYPE_NTFS) { - plist->ntfs_n++; - pinfo->ntfs_i = pinfo->index = plist->ntfs_n; - } - pinfo->part_fs = get_part_fs(pinfo->fs_type); - } - return 0; + // scan partitions for filesystem type + for (i = 0; i < plist->num; i++) { + pinfo = &plist->pinfo[i]; + entry = &plist->pentry[i]; + if (!entry->size) continue; + if (!entry->type) continue; + if (!entry->sector) continue; + // even though wrong, it's possible WBFS is on an extended part. + //if (!part_is_data(entry->type)) continue; + if (!Device_ReadSectors(device, entry->sector, 1, buf)) continue; + pinfo->fs_type = get_fs_type(buf); + if (pinfo->fs_type == FS_TYPE_WBFS) { + // multiple wbfs on sdhc not supported + if (device == WBFS_DEVICE_SDHC && (plist->wbfs_n > 1 || i > 4)) continue; + plist->wbfs_n++; + pinfo->wbfs_i = pinfo->index = plist->wbfs_n; + } else if (is_type_fat(pinfo->fs_type)) { + plist->fat_n++; + pinfo->fat_i = pinfo->index = plist->fat_n; + } else if (pinfo->fs_type == FS_TYPE_NTFS) { + plist->ntfs_n++; + pinfo->ntfs_i = pinfo->index = plist->ntfs_n; + } + pinfo->part_fs = get_part_fs(pinfo->fs_type); + } + return 0; } -int Partition_FixEXT(u32 device, int part) { - static partitionTable table ATTRIBUTE_ALIGN(32); - int ret; +int Partition_FixEXT(u32 device, int part) +{ + static partitionTable table ATTRIBUTE_ALIGN(32); + int ret; - if (part < 0 || part > 3) return -1; - // Read partition table - ret = Device_ReadSectors(device, 0, 1, &table); - if (!ret) return -1; - if (part_is_extended(table.entries[part].type)) { - table.entries[part].type = 0x0b; // FAT32 - ret = Device_WriteSectors(device, 0, 1, &table); - if (!ret) return -1; - return 0; - } - return -1; + if (part < 0 || part > 3) return -1; + // Read partition table + ret = Device_ReadSectors(device, 0, 1, &table); + if (!ret) return -1; + if (part_is_extended(table.entries[part].type)) { + table.entries[part].type = 0x0b; // FAT32 + ret = Device_WriteSectors(device, 0, 1, &table); + if (!ret) return -1; + return 0; + } + return -1; } diff --git a/source/usbloader/partition_usbloader.h b/source/usbloader/partition_usbloader.h index ddb8f6c6..b6f32697 100644 --- a/source/usbloader/partition_usbloader.h +++ b/source/usbloader/partition_usbloader.h @@ -5,28 +5,28 @@ extern "C" { #endif - /* 'partition entry' structure */ - typedef struct { - /* Boot indicator */ - u8 boot; +/* 'partition entry' structure */ +typedef struct { + /* Boot indicator */ + u8 boot; - /* Starting CHS */ - u8 start[3]; + /* Starting CHS */ + u8 start[3]; - /* Partition type */ - u8 type; + /* Partition type */ + u8 type; - /* Ending CHS */ - u8 end[3]; + /* Ending CHS */ + u8 end[3]; - /* Partition sector */ - u32 sector; + /* Partition sector */ + u32 sector; - /* Partition size */ - u32 size; - } ATTRIBUTE_PACKED partitionEntry; + /* Partition size */ + u32 size; +} ATTRIBUTE_PACKED partitionEntry; - /* Constants */ +/* Constants */ #define MAX_PARTITIONS 4 #define MAX_PARTITIONS_EX 10 @@ -36,41 +36,43 @@ extern "C" { #define FS_TYPE_NTFS 3 #define FS_TYPE_WBFS 4 - typedef struct { - int fs_type; - int part_fs; - int wbfs_i; // seq wbfs part index - int fat_i; // seq fat part index - int ntfs_i; // seq ntfs part index - int index; - } PartInfo; +typedef struct +{ + int fs_type; + int part_fs; + int wbfs_i; // seq wbfs part index + int fat_i; // seq fat part index + int ntfs_i; // seq ntfs part index + int index; +} PartInfo; - typedef struct { - int num; - u32 sector_size; - partitionEntry pentry[MAX_PARTITIONS_EX]; - int wbfs_n; - int fat_n; - int ntfs_n; - PartInfo pinfo[MAX_PARTITIONS_EX]; - } PartList; +typedef struct +{ + int num; + u32 sector_size; + partitionEntry pentry[MAX_PARTITIONS_EX]; + int wbfs_n; + int fat_n; + int ntfs_n; + PartInfo pinfo[MAX_PARTITIONS_EX]; +} PartList; - /* Prototypes */ - s32 Partition_GetEntries(u32 device, partitionEntry *outbuf, u32 *outval); - s32 Partition_GetEntriesEx(u32 device, partitionEntry *outbuf, u32 *outval, int *num); - bool Device_ReadSectors(u32 device, u32 sector, u32 count, void *buffer); - bool Device_WriteSectors(u32 device, u32 sector, u32 count, void *buffer); - s32 Partition_GetList(u32 device, PartList *plist); - int Partition_FixEXT(u32 device, int part); +/* Prototypes */ +s32 Partition_GetEntries(u32 device, partitionEntry *outbuf, u32 *outval); +s32 Partition_GetEntriesEx(u32 device, partitionEntry *outbuf, u32 *outval, int *num); +bool Device_ReadSectors(u32 device, u32 sector, u32 count, void *buffer); +bool Device_WriteSectors(u32 device, u32 sector, u32 count, void *buffer); +s32 Partition_GetList(u32 device, PartList *plist); +int Partition_FixEXT(u32 device, int part); - bool part_is_extended(int type); - bool part_is_data(int type); - char* part_type_data(int type); - char* part_type_name(int type); - bool part_valid_data(partitionEntry *entry); - int get_fs_type(void *buf); - bool is_type_fat(int type); - char* get_fs_name(int i); +bool part_is_extended(int type); +bool part_is_data(int type); +char* part_type_data(int type); +char* part_type_name(int type); +bool part_valid_data(partitionEntry *entry); +int get_fs_type(void *buf); +bool is_type_fat(int type); +char* get_fs_name(int i); #ifdef __cplusplus } diff --git a/source/usbloader/sdhc.c b/source/usbloader/sdhc.c index ebff4ae0..33e343a6 100644 --- a/source/usbloader/sdhc.c +++ b/source/usbloader/sdhc.c @@ -25,190 +25,198 @@ static void *sdhc_buf2; extern void* SYS_AllocArena2MemLo(u32 size,u32 align); -bool SDHC_Init(void) { - s32 ret; +bool SDHC_Init(void) +{ + s32 ret; - if (sdhc_mode_sd) { - return __io_wiisd.startup(); - } + if (sdhc_mode_sd) { + return __io_wiisd.startup(); + } - /* Already open */ - if (fd >= 0) - return true; + /* Already open */ + if (fd >= 0) + return true; - /* Create heap */ - if (hid < 0) { - hid = iosCreateHeap(SDHC_HEAPSIZE); - if (hid < 0) - goto err; - } + /* Create heap */ + if (hid < 0) { + hid = iosCreateHeap(SDHC_HEAPSIZE); + if (hid < 0) + goto err; + } - // allocate buf2 - if (sdhc_buf2 == NULL) { - sdhc_buf2 = SYS_AllocArena2MemLo(SDHC_MEM2_SIZE, 32); - } + // allocate buf2 + if (sdhc_buf2 == NULL) { + sdhc_buf2 = SYS_AllocArena2MemLo(SDHC_MEM2_SIZE, 32); + } - /* Open SDHC device */ - fd = IOS_Open(fs, 0); - if (fd < 0) - goto err; + /* Open SDHC device */ + fd = IOS_Open(fs, 0); + if (fd < 0) + goto err; - /* Initialize SDHC */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_INIT, ":"); - if (ret) - goto err; + /* Initialize SDHC */ + ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_INIT, ":"); + if (ret) + goto err; - return true; + return true; err: - /* Close SDHC device */ - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } + /* Close SDHC device */ + if (fd >= 0) { + IOS_Close(fd); + fd = -1; + } - return false; + return false; } -bool SDHC_Close(void) { - if (sdhc_mode_sd) { - return __io_wiisd.shutdown(); - } +bool SDHC_Close(void) +{ + if (sdhc_mode_sd) { + return __io_wiisd.shutdown(); + } - /* Close SDHC device */ - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } + /* Close SDHC device */ + if (fd >= 0) { + IOS_Close(fd); + fd = -1; + } - /*if (hid > 0) { - iosDestroyHeap(hid); - hid = -1; - }*/ + /*if (hid > 0) { + iosDestroyHeap(hid); + hid = -1; + }*/ - return true; + return true; } -bool SDHC_IsInserted(void) { - s32 ret; - if (sdhc_mode_sd) { - return __io_wiisd.isInserted(); - } +bool SDHC_IsInserted(void) +{ + s32 ret; + if (sdhc_mode_sd) { + return __io_wiisd.isInserted(); + } - /* Check if SD card is inserted */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_ISINSERTED, ":"); + /* Check if SD card is inserted */ + ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_ISINSERTED, ":"); - return (!ret) ? true : false; + return (!ret) ? true : false; } -bool SDHC_ReadSectors(u32 sector, u32 count, void *buffer) { - //printf("SD-R(%u %u)\n", sector, count); - if (sdhc_mode_sd) { - return __io_wiisd.readSectors(sector, count, buffer); - } +bool SDHC_ReadSectors(u32 sector, u32 count, void *buffer) +{ + //printf("SD-R(%u %u)\n", sector, count); + if (sdhc_mode_sd) { + return __io_wiisd.readSectors(sector, count, buffer); + } - void *buf = (void *)buffer; - u32 len = (sector_size * count); + void *buf = (void *)buffer; + u32 len = (sector_size * count); - s32 ret; + s32 ret; - /* Device not opened */ - if (fd < 0) - return false; + /* Device not opened */ + if (fd < 0) + return false; - /* Buffer not aligned */ - if ((u32)buffer & 0x1F) { - /* Allocate memory */ - //buf = iosAlloc(hid, len); - buf = sdhc_buf2; - if (!buf) - return false; - } + /* Buffer not aligned */ + if ((u32)buffer & 0x1F) { + /* Allocate memory */ + //buf = iosAlloc(hid, len); + buf = sdhc_buf2; + if (!buf) + return false; + } - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_READ, "ii:d", sector, count, buf, len); + /* Read data */ + ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_READ, "ii:d", sector, count, buf, len); - /* Copy data */ - if (buf != buffer) { - memcpy(buffer, buf, len); - //iosFree(hid, buf); - } + /* Copy data */ + if (buf != buffer) { + memcpy(buffer, buf, len); + //iosFree(hid, buf); + } - return (!ret) ? true : false; + return (!ret) ? true : false; } -bool SDHC_WriteSectors(u32 sector, u32 count, void *buffer) { - if (sdhc_mode_sd) { - return __io_wiisd.writeSectors(sector, count, buffer); - } +bool SDHC_WriteSectors(u32 sector, u32 count, void *buffer) +{ + if (sdhc_mode_sd) { + return __io_wiisd.writeSectors(sector, count, buffer); + } - void *buf = (void *)buffer; - u32 len = (sector_size * count); + void *buf = (void *)buffer; + u32 len = (sector_size * count); - s32 ret; + s32 ret; - /* Device not opened */ - if (fd < 0) - return false; + /* Device not opened */ + if (fd < 0) + return false; - /* Buffer not aligned */ - if ((u32)buffer & 0x1F) { - /* Allocate memory */ - //buf = iosAlloc(hid, len); - buf = sdhc_buf2; - if (!buf) - return false; + /* Buffer not aligned */ + if ((u32)buffer & 0x1F) { + /* Allocate memory */ + //buf = iosAlloc(hid, len); + buf = sdhc_buf2; + if (!buf) + return false; - /* Copy data */ - memcpy(buf, buffer, len); - } + /* Copy data */ + memcpy(buf, buffer, len); + } - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_WRITE, "ii:d", sector, count, buf, len); + /* Read data */ + ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_WRITE, "ii:d", sector, count, buf, len); - /* Free memory */ - //if (buf != buffer) - // iosFree(hid, buf); + /* Free memory */ + //if (buf != buffer) + // iosFree(hid, buf); - return (!ret) ? true : false; + return (!ret) ? true : false; } -bool SDHC_ClearStatus(void) { - return true; +bool SDHC_ClearStatus(void) +{ + return true; } -bool __io_SDHC_Close(void) { - // do nothing. - return true; +bool __io_SDHC_Close(void) +{ + // do nothing. + return true; } -bool __io_SDHC_NOP(void) { - // do nothing. - return true; +bool __io_SDHC_NOP(void) +{ + // do nothing. + return true; } const DISC_INTERFACE __io_sdhc = { - DEVICE_TYPE_WII_SD, - FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE | FEATURE_WII_SD, - (FN_MEDIUM_STARTUP)&SDHC_Init, - (FN_MEDIUM_ISINSERTED)&SDHC_IsInserted, - (FN_MEDIUM_READSECTORS)&SDHC_ReadSectors, - (FN_MEDIUM_WRITESECTORS)&SDHC_WriteSectors, - (FN_MEDIUM_CLEARSTATUS)&SDHC_ClearStatus, - //(FN_MEDIUM_SHUTDOWN)&SDHC_Close - (FN_MEDIUM_SHUTDOWN)&__io_SDHC_Close + DEVICE_TYPE_WII_SD, + FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE | FEATURE_WII_SD, + (FN_MEDIUM_STARTUP)&SDHC_Init, + (FN_MEDIUM_ISINSERTED)&SDHC_IsInserted, + (FN_MEDIUM_READSECTORS)&SDHC_ReadSectors, + (FN_MEDIUM_WRITESECTORS)&SDHC_WriteSectors, + (FN_MEDIUM_CLEARSTATUS)&SDHC_ClearStatus, + //(FN_MEDIUM_SHUTDOWN)&SDHC_Close + (FN_MEDIUM_SHUTDOWN)&__io_SDHC_Close }; const DISC_INTERFACE __io_sdhc_ro = { - DEVICE_TYPE_WII_SD, - FEATURE_MEDIUM_CANREAD | FEATURE_WII_SD, - (FN_MEDIUM_STARTUP) &SDHC_Init, - (FN_MEDIUM_ISINSERTED) &SDHC_IsInserted, - (FN_MEDIUM_READSECTORS) &SDHC_ReadSectors, - (FN_MEDIUM_WRITESECTORS) &__io_SDHC_NOP, // &SDHC_WriteSectors, - (FN_MEDIUM_CLEARSTATUS) &SDHC_ClearStatus, - //(FN_MEDIUM_SHUTDOWN)&SDHC_Close - (FN_MEDIUM_SHUTDOWN) &__io_SDHC_Close + DEVICE_TYPE_WII_SD, + FEATURE_MEDIUM_CANREAD | FEATURE_WII_SD, + (FN_MEDIUM_STARTUP) &SDHC_Init, + (FN_MEDIUM_ISINSERTED) &SDHC_IsInserted, + (FN_MEDIUM_READSECTORS) &SDHC_ReadSectors, + (FN_MEDIUM_WRITESECTORS) &__io_SDHC_NOP, // &SDHC_WriteSectors, + (FN_MEDIUM_CLEARSTATUS) &SDHC_ClearStatus, + //(FN_MEDIUM_SHUTDOWN)&SDHC_Close + (FN_MEDIUM_SHUTDOWN) &__io_SDHC_Close }; diff --git a/source/usbloader/sdhc.h b/source/usbloader/sdhc.h index eb2bed01..aee41457 100644 --- a/source/usbloader/sdhc.h +++ b/source/usbloader/sdhc.h @@ -13,7 +13,7 @@ extern "C" { bool SDHC_Close(void); bool SDHC_ReadSectors(u32, u32, void *); bool SDHC_WriteSectors(u32, u32, void *); - extern int sdhc_mode_sd; + extern int sdhc_mode_sd; #ifdef __cplusplus } diff --git a/source/usbloader/splits.c b/source/usbloader/splits.c index 87390872..dc933400 100644 --- a/source/usbloader/splits.c +++ b/source/usbloader/splits.c @@ -26,279 +26,291 @@ u64 OPT_split_size = (u64)4LL * 1024 * 1024 * 1024 - 32 * 1024; //split_info_t split; -void split_get_fname(split_info_t *s, int idx, char *fname) { - strcpy(fname, s->fname); - if (idx == 0 && s->create_mode) { - strcat(fname, ".tmp"); - } else if (idx > 0) { - char *c = fname + strlen(fname) - 1; - *c = '0' + idx; - } +void split_get_fname(split_info_t *s, int idx, char *fname) +{ + strcpy(fname, s->fname); + if (idx == 0 && s->create_mode) { + strcat(fname, ".tmp"); + } else if (idx > 0) { + char *c = fname + strlen(fname) - 1; + *c = '0' + idx; + } } -int split_open_file(split_info_t *s, int idx) { - int fd = s->fd[idx]; - if (fd>=0) return fd; - char fname[1024]; - split_get_fname(s, idx, fname); - //char *mode = s->create_mode ? "wb+" : "rb+"; - int mode = s->create_mode ? (O_CREAT | O_RDWR) : O_RDWR ; - //printf("SPLIT OPEN %s %s %d\n", fname, mode, idx); //Wpad_WaitButtons(); - //f = fopen(fname, mode); - fd = open(fname, mode); - if (fd<0) return -1; - if (idx > 0 && s->create_mode) { - printf("%s Split: %d %s \n", - s->create_mode ? "Create" : "Read", - idx, fname); - } - s->fd[idx] = fd; - return fd; +int split_open_file(split_info_t *s, int idx) +{ + int fd = s->fd[idx]; + if (fd>=0) return fd; + char fname[1024]; + split_get_fname(s, idx, fname); + //char *mode = s->create_mode ? "wb+" : "rb+"; + int mode = s->create_mode ? (O_CREAT | O_RDWR) : O_RDWR ; + //printf("SPLIT OPEN %s %s %d\n", fname, mode, idx); //Wpad_WaitButtons(); + //f = fopen(fname, mode); + fd = open(fname, mode); + if (fd<0) return -1; + if (idx > 0 && s->create_mode) { + printf("%s Split: %d %s \n", + s->create_mode ? "Create" : "Read", + idx, fname); + } + s->fd[idx] = fd; + return fd; } // faster as it uses larger chunks than ftruncate internally -int write_zero(int fd, off_t size) { - int buf[0x4000]; //64kb - int chunk; - int ret; - memset(buf, 0, sizeof(buf)); - while (size) { - chunk = size; - if (chunk > sizeof(buf)) chunk = sizeof(buf); - ret = write(fd, buf, chunk); - //printf("WZ %d %d / %lld \n", ret, chunk, size); - size -= chunk; - if (ret < 0) return ret; - } - return 0; +int write_zero(int fd, off_t size) +{ + int buf[0x4000]; //64kb + int chunk; + int ret; + memset(buf, 0, sizeof(buf)); + while (size) { + chunk = size; + if (chunk > sizeof(buf)) chunk = sizeof(buf); + ret = write(fd, buf, chunk); + //printf("WZ %d %d / %lld \n", ret, chunk, size); + size -= chunk; + if (ret < 0) return ret; + } + return 0; } -int split_fill(split_info_t *s, int idx, u64 size) { - int fd = split_open_file(s, idx); - off64_t fsize = lseek(fd, 0, SEEK_END); - if (fsize < size) { - //printf("TRUNC %d "FMT_lld"\n", idx, size); Wpad_WaitButtons(); - //ftruncate(fd, size); - write_zero(fd, size - fsize); - return 1; - } - return 0; +int split_fill(split_info_t *s, int idx, u64 size) +{ + int fd = split_open_file(s, idx); + off64_t fsize = lseek(fd, 0, SEEK_END); + if (fsize < size) { + //printf("TRUNC %d "FMT_lld"\n", idx, size); Wpad_WaitButtons(); + //ftruncate(fd, size); + write_zero(fd, size - fsize); + return 1; + } + return 0; } -int split_get_file(split_info_t *s, u32 lba, u32 *sec_count, int fill) { - int fd; - if (lba >= s->total_sec) { - fprintf(stderr, "SPLIT: invalid sector %u / %u\n", lba, (u32)s->total_sec); - return -1; - } - int idx; - idx = lba / s->split_sec; - if (idx >= s->max_split) { - fprintf(stderr, "SPLIT: invalid split %d / %d\n", idx, s->max_split - 1); - return -1; - } - fd = s->fd[idx]; - if (fd<0) { - // opening new, make sure all previous are full - int i; - for (i=0; isplit_size)) { - printf("FILL %d\n", i); - } - } - fd = split_open_file(s, idx); - } - if (fd<0) { - fprintf(stderr, "SPLIT %d: no file\n", idx); - return -1; - } - u32 sec = lba % s->split_sec; // inside file - off64_t off = (off64_t)sec * 512; - // num sectors till end of file - u32 to_end = s->split_sec - sec; - if (*sec_count > to_end) *sec_count = to_end; - if (s->create_mode) { - if (fill) { - // extend, so that read will be succesfull - split_fill(s, idx, off + 512 * (*sec_count)); - } else { - // fill up so that write continues from end of file - // shouldn't be necessary, but libfat looks buggy - // and this is faster - split_fill(s, idx, off); - } - } - lseek(fd, off, SEEK_SET); - return fd; +int split_get_file(split_info_t *s, u32 lba, u32 *sec_count, int fill) +{ + int fd; + if (lba >= s->total_sec) { + fprintf(stderr, "SPLIT: invalid sector %u / %u\n", lba, (u32)s->total_sec); + return -1; + } + int idx; + idx = lba / s->split_sec; + if (idx >= s->max_split) { + fprintf(stderr, "SPLIT: invalid split %d / %d\n", idx, s->max_split - 1); + return -1; + } + fd = s->fd[idx]; + if (fd<0) { + // opening new, make sure all previous are full + int i; + for (i=0; isplit_size)) { + printf("FILL %d\n", i); + } + } + fd = split_open_file(s, idx); + } + if (fd<0) { + fprintf(stderr, "SPLIT %d: no file\n", idx); + return -1; + } + u32 sec = lba % s->split_sec; // inside file + off64_t off = (off64_t)sec * 512; + // num sectors till end of file + u32 to_end = s->split_sec - sec; + if (*sec_count > to_end) *sec_count = to_end; + if (s->create_mode) { + if (fill) { + // extend, so that read will be succesfull + split_fill(s, idx, off + 512 * (*sec_count)); + } else { + // fill up so that write continues from end of file + // shouldn't be necessary, but libfat looks buggy + // and this is faster + split_fill(s, idx, off); + } + } + lseek(fd, off, SEEK_SET); + return fd; } -int split_read_sector(void *_fp,u32 lba,u32 count,void*buf) { - split_info_t *s = _fp; - int fd; - u64 off = lba; - off *= 512ULL; - int i; - u32 chunk; - size_t ret; - //fprintf(stderr,"READ %d %d\n", lba, count); - for (i=0; i<(int)count; i+=chunk) { - chunk = count - i; - fd = split_get_file(s, lba+i, &chunk, 1); - if (fd<0) { - fprintf(stderr,"\n\n"FMT_lld" %d %p\n",off,count,_fp); - split_error("error seeking in disc partition"); - return 1; - } - //ret = fread(buf+i*512, 512ULL, chunk, f); - ret = read(fd, buf+i*512, chunk * 512); - if (ret != chunk * 512) { - fprintf(stderr, "error reading %u %u [%u] %u = %u\n", - lba, count, i, chunk, ret); - split_error("error reading disc"); - return 1; - } - } - return 0; +int split_read_sector(void *_fp,u32 lba,u32 count,void*buf) +{ + split_info_t *s = _fp; + int fd; + u64 off = lba; + off *= 512ULL; + int i; + u32 chunk; + size_t ret; + //fprintf(stderr,"READ %d %d\n", lba, count); + for (i=0; i<(int)count; i+=chunk) { + chunk = count - i; + fd = split_get_file(s, lba+i, &chunk, 1); + if (fd<0) { + fprintf(stderr,"\n\n"FMT_lld" %d %p\n",off,count,_fp); + split_error("error seeking in disc partition"); + return 1; + } + //ret = fread(buf+i*512, 512ULL, chunk, f); + ret = read(fd, buf+i*512, chunk * 512); + if (ret != chunk * 512) { + fprintf(stderr, "error reading %u %u [%u] %u = %u\n", + lba, count, i, chunk, ret); + split_error("error reading disc"); + return 1; + } + } + return 0; } -int split_write_sector(void *_fp,u32 lba,u32 count,void*buf) { - split_info_t *s = _fp; - int fd; - u64 off = lba; - off*=512ULL; - int i; - u32 chunk; - size_t ret; - //printf("WRITE %d %d %p \n", lba, count, buf); - for (i=0; i<(int)count; i+=chunk) { - chunk = count - i; - fd = split_get_file(s, lba+i, &chunk, 0); - //if (chunk != count) - // fprintf(stderr, "WRITE CHUNK %d %d/%d\n", lba+i, chunk, count); - if (fd<0 || !chunk) { - fprintf(stderr,"\n\n"FMT_lld" %d %p\n",off,count,_fp); - split_error("error seeking in disc partition"); - return 1; - } - //if (fwrite(buf+i*512, 512ULL, chunk, f) != chunk) { - //printf("write %d %p %d \n", fd, buf+i*512, chunk * 512); - ret = write(fd, buf+i*512, chunk * 512); - //printf("write ret = %d \n", ret); - if (ret != chunk * 512) { - split_error("error writing disc"); - return 1; - } - } - return 0; +int split_write_sector(void *_fp,u32 lba,u32 count,void*buf) +{ + split_info_t *s = _fp; + int fd; + u64 off = lba; + off*=512ULL; + int i; + u32 chunk; + size_t ret; + //printf("WRITE %d %d %p \n", lba, count, buf); + for (i=0; i<(int)count; i+=chunk) { + chunk = count - i; + fd = split_get_file(s, lba+i, &chunk, 0); + //if (chunk != count) + // fprintf(stderr, "WRITE CHUNK %d %d/%d\n", lba+i, chunk, count); + if (fd<0 || !chunk) { + fprintf(stderr,"\n\n"FMT_lld" %d %p\n",off,count,_fp); + split_error("error seeking in disc partition"); + return 1; + } + //if (fwrite(buf+i*512, 512ULL, chunk, f) != chunk) { + //printf("write %d %p %d \n", fd, buf+i*512, chunk * 512); + ret = write(fd, buf+i*512, chunk * 512); + //printf("write ret = %d \n", ret); + if (ret != chunk * 512) { + split_error("error writing disc"); + return 1; + } + } + return 0; } -void split_init(split_info_t *s, char *fname) { - int i; - char *p; - //fprintf(stderr, "SPLIT_INIT %s\n", fname); - memset(s, 0, sizeof(*s)); - for (i=0; ifd[i] = -1; - } - strcpy(s->fname, fname); - s->max_split = 1; - p = strrchr(fname, '.'); - if (p && (strcasecmp(p, ".wbfs") == 0)) { - s->max_split = MAX_SPLIT; - } +void split_init(split_info_t *s, char *fname) +{ + int i; + char *p; + //fprintf(stderr, "SPLIT_INIT %s\n", fname); + memset(s, 0, sizeof(*s)); + for (i=0; ifd[i] = -1; + } + strcpy(s->fname, fname); + s->max_split = 1; + p = strrchr(fname, '.'); + if (p && (strcasecmp(p, ".wbfs") == 0)) { + s->max_split = MAX_SPLIT; + } } -void split_set_size(split_info_t *s, u64 split_size, u64 total_size) { - s->total_size = total_size; - s->split_size = split_size; - s->total_sec = total_size / 512; - s->split_sec = split_size / 512; +void split_set_size(split_info_t *s, u64 split_size, u64 total_size) +{ + s->total_size = total_size; + s->split_size = split_size; + s->total_sec = total_size / 512; + s->split_sec = split_size / 512; } -void split_close(split_info_t *s) { - int i; - char fname[1024]; - char tmpname[1024]; - for (i=0; imax_split; i++) { - if (s->fd[i] >= 0) { - close(s->fd[i]); - } - } - if (s->create_mode) { - split_get_fname(s, -1, fname); - split_get_fname(s, 0, tmpname); - rename(tmpname, fname); - } - memset(s, 0, sizeof(*s)); +void split_close(split_info_t *s) +{ + int i; + char fname[1024]; + char tmpname[1024]; + for (i=0; imax_split; i++) { + if (s->fd[i] >= 0) { + close(s->fd[i]); + } + } + if (s->create_mode) { + split_get_fname(s, -1, fname); + split_get_fname(s, 0, tmpname); + rename(tmpname, fname); + } + memset(s, 0, sizeof(*s)); } int split_create(split_info_t *s, char *fname, - u64 split_size, u64 total_size, bool overwrite) { - int i; - int fd; - char sname[1024]; - int error = 0; - split_init(s, fname); - s->create_mode = 1; - // check if any file already exists - for (i=-1; imax_split; i++) { - split_get_fname(s, i, sname); - if (overwrite) { - remove(sname); - } else { - fd = open(sname, O_RDONLY); - if (fd >= 0) { - fprintf(stderr, "Error: file already exists: %s\n", sname); - close(fd); - error = 1; - } - } - } - if (error) { - split_init(s, ""); - return -1; - } - split_set_size(s, split_size, total_size); - return 0; + u64 split_size, u64 total_size, bool overwrite) +{ + int i; + int fd; + char sname[1024]; + int error = 0; + split_init(s, fname); + s->create_mode = 1; + // check if any file already exists + for (i=-1; imax_split; i++) { + split_get_fname(s, i, sname); + if (overwrite) { + remove(sname); + } else { + fd = open(sname, O_RDONLY); + if (fd >= 0) { + fprintf(stderr, "Error: file already exists: %s\n", sname); + close(fd); + error = 1; + } + } + } + if (error) { + split_init(s, ""); + return -1; + } + split_set_size(s, split_size, total_size); + return 0; } -int split_open(split_info_t *s, char *fname) { - int i; - u64 size = 0; - u64 total_size = 0; - u64 split_size = 0; - int fd; - split_init(s, fname); - for (i=0; imax_split; i++) { - fd = split_open_file(s, i); - if (fd<0) { - if (i==0) goto err; - break; - } - // check previous size - all splits except last must be same size - if (i > 0 && size != split_size) { - fprintf(stderr, "split %d: invalid size "FMT_lld"", i, size); - goto err; - } - // get size - //fseeko(f, 0, SEEK_END); - //size = ftello(f); - size = lseek(fd, 0, SEEK_END); - // check sector alignment - if (size % 512) { - fprintf(stderr, "split %d: size ("FMT_lld") not sector (512) aligned!", - i, size); - } - // first sets split size - if (i==0) { - split_size = size; - } - total_size += size; - } - split_set_size(s, split_size, total_size); - return 0; +int split_open(split_info_t *s, char *fname) +{ + int i; + u64 size = 0; + u64 total_size = 0; + u64 split_size = 0; + int fd; + split_init(s, fname); + for (i=0; imax_split; i++) { + fd = split_open_file(s, i); + if (fd<0) { + if (i==0) goto err; + break; + } + // check previous size - all splits except last must be same size + if (i > 0 && size != split_size) { + fprintf(stderr, "split %d: invalid size "FMT_lld"", i, size); + goto err; + } + // get size + //fseeko(f, 0, SEEK_END); + //size = ftello(f); + size = lseek(fd, 0, SEEK_END); + // check sector alignment + if (size % 512) { + fprintf(stderr, "split %d: size ("FMT_lld") not sector (512) aligned!", + i, size); + } + // first sets split size + if (i==0) { + split_size = size; + } + total_size += size; + } + split_set_size(s, split_size, total_size); + return 0; err: - split_close(s); - return -1; + split_close(s); + return -1; } diff --git a/source/usbloader/splits.h b/source/usbloader/splits.h index b09bc0e0..fe9da4a8 100644 --- a/source/usbloader/splits.h +++ b/source/usbloader/splits.h @@ -1,17 +1,18 @@ #define MAX_SPLIT 10 -typedef struct split_info { - char fname[1024]; - //FILE *f[MAX_SPLIT]; - int fd[MAX_SPLIT]; - //u64 fsize[MAX_SPLIT]; - u32 split_sec; - u32 total_sec; - u64 split_size; - u64 total_size; - int create_mode; - int max_split; +typedef struct split_info +{ + char fname[1024]; + //FILE *f[MAX_SPLIT]; + int fd[MAX_SPLIT]; + //u64 fsize[MAX_SPLIT]; + u32 split_sec; + u32 total_sec; + u64 split_size; + u64 total_size; + int create_mode; + int max_split; } split_info_t; // 1 sector less than 4gb @@ -30,5 +31,5 @@ void split_set_size(split_info_t *s, u64 split_size, u64 total_size); void split_close(split_info_t *s); int split_open(split_info_t *s, char *fname); int split_create(split_info_t *s, char *fname, - u64 split_size, u64 total_size, bool overwrite); + u64 split_size, u64 total_size, bool overwrite); diff --git a/source/usbloader/usbstorage.c b/source/usbloader/usbstorage.c index c15e9fa9..d89ff674 100644 --- a/source/usbloader/usbstorage.c +++ b/source/usbloader/usbstorage.c @@ -89,7 +89,7 @@ s32 USBStorage_Init(void) { /* Open USB device */ fd = IOS_Open(fs, 0); - if (fd < 0) + if (fd < 0) fd = IOS_Open(fs2, 0); if (fd < 0) return fd; @@ -149,151 +149,163 @@ void USBStorage_Deinit(void) { s32 USBStorage_ReadSectors(u32 sector, u32 numSectors, void *buffer) { // void *buf = (void *)buffer; - u32 len = (sector_size * numSectors); + u32 len = (sector_size * numSectors); - s32 ret; + s32 ret; - /* Device not opened */ - if (fd < 0) - return fd; + /* Device not opened */ + if (fd < 0) + return fd; - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_READ_SECTORS, "ii:d", sector, numSectors, buffer, len); - return ret; + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_READ_SECTORS, "ii:d", sector, numSectors, buffer, len); + return ret; } s32 USBStorage_WriteSectors(u32 sector, u32 numSectors, const void *buffer) { - u32 len = (sector_size * numSectors); + u32 len = (sector_size * numSectors); - s32 ret; + s32 ret; - /* Device not opened */ - if (fd < 0) - return fd; + /* Device not opened */ + if (fd < 0) + return fd; - /* Write data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_WRITE_SECTORS, "ii:d", sector, numSectors, buffer, len); + /* Write data */ + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_WRITE_SECTORS, "ii:d", sector, numSectors, buffer, len); - return ret; + return ret; } -static bool __io_usb_Startup(void) { - return USBStorage_Init() >= 0; +static bool __io_usb_Startup(void) +{ + return USBStorage_Init() >= 0; } -static bool __io_usb_IsInserted(void) { - s32 ret; - if (fd < 0) return false; - ret = USBStorage_GetCapacity(NULL); - if (ret == 0) return false; - return true; +static bool __io_usb_IsInserted(void) +{ + s32 ret; + if (fd < 0) return false; + ret = USBStorage_GetCapacity(NULL); + if (ret == 0) return false; + return true; } -bool __io_usb_ReadSectors(u32 sector, u32 count, void *buffer) { - s32 ret = USBStorage_ReadSectors(sector, count, buffer); - return ret > 0; +bool __io_usb_ReadSectors(u32 sector, u32 count, void *buffer) +{ + s32 ret = USBStorage_ReadSectors(sector, count, buffer); + return ret > 0; } -bool __io_usb_WriteSectors(u32 sector, u32 count, void *buffer) { - s32 ret = USBStorage_WriteSectors(sector, count, buffer); - return ret > 0; +bool __io_usb_WriteSectors(u32 sector, u32 count, void *buffer) +{ + s32 ret = USBStorage_WriteSectors(sector, count, buffer); + return ret > 0; } -static bool __io_usb_ClearStatus(void) { - return true; +static bool __io_usb_ClearStatus(void) +{ + return true; } -static bool __io_usb_Shutdown(void) { - // do nothing - return true; +static bool __io_usb_Shutdown(void) +{ + // do nothing + return true; } -static bool __io_usb_NOP(void) { - // do nothing - return true; +static bool __io_usb_NOP(void) +{ + // do nothing + return true; } const DISC_INTERFACE __io_usbstorage_ro = { - DEVICE_TYPE_WII_USB, - FEATURE_MEDIUM_CANREAD | FEATURE_WII_USB, - (FN_MEDIUM_STARTUP) &__io_usb_Startup, - (FN_MEDIUM_ISINSERTED) &__io_usb_IsInserted, - (FN_MEDIUM_READSECTORS) &__io_usb_ReadSectors, - (FN_MEDIUM_WRITESECTORS) &__io_usb_NOP, //&__io_usb_WriteSectors, - (FN_MEDIUM_CLEARSTATUS) &__io_usb_ClearStatus, - (FN_MEDIUM_SHUTDOWN) &__io_usb_Shutdown + DEVICE_TYPE_WII_USB, + FEATURE_MEDIUM_CANREAD | FEATURE_WII_USB, + (FN_MEDIUM_STARTUP) &__io_usb_Startup, + (FN_MEDIUM_ISINSERTED) &__io_usb_IsInserted, + (FN_MEDIUM_READSECTORS) &__io_usb_ReadSectors, + (FN_MEDIUM_WRITESECTORS) &__io_usb_NOP, //&__io_usb_WriteSectors, + (FN_MEDIUM_CLEARSTATUS) &__io_usb_ClearStatus, + (FN_MEDIUM_SHUTDOWN) &__io_usb_Shutdown }; -s32 USBStorage_WBFS_Open(char *buffer) { - u32 len = 8; +s32 USBStorage_WBFS_Open(char *buffer) +{ + u32 len = 8; - s32 ret; + s32 ret; - /* Device not opened */ - if (fd < 0) - return fd; + /* Device not opened */ + if (fd < 0) + return fd; - extern u32 wbfs_part_lba; - u32 part = wbfs_part_lba; + extern u32 wbfs_part_lba; + u32 part = wbfs_part_lba; - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_OPEN_DISC, "dd:", buffer, len, &part, 4); + /* Read data */ + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_OPEN_DISC, "dd:", buffer, len, &part, 4); - return ret; + return ret; } // woffset is in 32bit words, len is in bytes -s32 USBStorage_WBFS_Read(u32 woffset, u32 len, void *buffer) { - s32 ret; +s32 USBStorage_WBFS_Read(u32 woffset, u32 len, void *buffer) +{ + s32 ret; - USBStorage_Init(); - /* Device not opened */ - if (fd < 0) - return fd; + USBStorage_Init(); + /* Device not opened */ + if (fd < 0) + return fd; - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_READ_DISC, "ii:d", woffset, len, buffer, len); + /* Read data */ + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_READ_DISC, "ii:d", woffset, len, buffer, len); - return ret; + return ret; } -s32 USBStorage_WBFS_ReadDebug(u32 off, u32 size, void *buffer) { - s32 ret; +s32 USBStorage_WBFS_ReadDebug(u32 off, u32 size, void *buffer) +{ + s32 ret; - USBStorage_Init(); - /* Device not opened */ - if (fd < 0) - return fd; + USBStorage_Init(); + /* Device not opened */ + if (fd < 0) + return fd; - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_READ_DEBUG, "ii:d", off, size, buffer, size); + /* Read data */ + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_READ_DEBUG, "ii:d", off, size, buffer, size); - return ret; + return ret; } -s32 USBStorage_WBFS_SetDevice(int dev) { - s32 ret; - static s32 retval = 0; - retval = 0; - USBStorage_Init(); - // Device not opened - if (fd < 0) return fd; - // ioctl - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_SET_DEVICE, "i:i", dev, &retval); - if (retval) return retval; - return ret; +s32 USBStorage_WBFS_SetDevice(int dev) +{ + s32 ret; + static s32 retval = 0; + retval = 0; + USBStorage_Init(); + // Device not opened + if (fd < 0) return fd; + // ioctl + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_SET_DEVICE, "i:i", dev, &retval); + if (retval) return retval; + return ret; } -s32 USBStorage_WBFS_SetFragList(void *p, int size) { - s32 ret; - USBStorage_Init(); - // Device not opened - if (fd < 0) return fd; - // ioctl - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_SET_FRAGLIST, "d:", p, size); - return ret; +s32 USBStorage_WBFS_SetFragList(void *p, int size) +{ + s32 ret; + USBStorage_Init(); + // Device not opened + if (fd < 0) return fd; + // ioctl + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_SET_FRAGLIST, "d:", p, size); + return ret; } #define DEVICE_TYPE_WII_UMS (('W'<<24)|('U'<<16)|('M'<<8)|'S') diff --git a/source/usbloader/usbstorage.h b/source/usbloader/usbstorage.h index 26852e9c..47df60ad 100644 --- a/source/usbloader/usbstorage.h +++ b/source/usbloader/usbstorage.h @@ -1,27 +1,27 @@ #ifndef _USBSTORAGE_H_ -#define _USBSTORAGE_H_ +#define _USBSTORAGE_H_ #ifdef __cplusplus extern "C" { #endif - /* Prototypes */ - s32 USBStorage_GetCapacity(u32 *); - s32 USBStorage_Init(void); + /* Prototypes */ + s32 USBStorage_GetCapacity(u32 *); + s32 USBStorage_Init(void); void USBStorage_Deinit(void); s32 USBStorage_Watchdog(u32 on_off); s32 USBStorage_ReadSectors(u32, u32, void *); s32 USBStorage_WriteSectors(u32, u32, const void *); - - s32 USBStorage_WBFS_Open(char *buf_id); - s32 USBStorage_WBFS_Read(u32 woffset, u32 len, void *buffer); - s32 USBStorage_WBFS_ReadDebug(u32 off, u32 size, void *buffer); - s32 USBStorage_WBFS_SetDevice(int dev); - s32 USBStorage_WBFS_SetFragList(void *p, int size); - - extern const DISC_INTERFACE __io_wiiums; - extern const DISC_INTERFACE __io_wiiums_ro; + + s32 USBStorage_WBFS_Open(char *buf_id); + s32 USBStorage_WBFS_Read(u32 woffset, u32 len, void *buffer); + s32 USBStorage_WBFS_ReadDebug(u32 off, u32 size, void *buffer); + s32 USBStorage_WBFS_SetDevice(int dev); + s32 USBStorage_WBFS_SetFragList(void *p, int size); + + extern const DISC_INTERFACE __io_wiiums; + extern const DISC_INTERFACE __io_wiiums_ro; #ifdef __cplusplus } #endif - -#endif + +#endif diff --git a/source/usbloader/utils.h b/source/usbloader/utils.h index b1d75b75..95e6254d 100644 --- a/source/usbloader/utils.h +++ b/source/usbloader/utils.h @@ -5,18 +5,18 @@ extern "C" { #endif - /* Constants */ +/* Constants */ #define KB_SIZE 1024.0 #define MB_SIZE 1048576.0 #define GB_SIZE 1073741824.0 - /* Macros */ +/* Macros */ #define round_up(x,n) (-(-(x) & -(n))) #define SAFE_FREE(P) if(P){free(P);P=NULL;} - /* Prototypes */ - u32 swap32(u32); +/* Prototypes */ +u32 swap32(u32); #ifdef __cplusplus } diff --git a/source/usbloader/wbfs.c b/source/usbloader/wbfs.c index 9ad60739..accbbbae 100644 --- a/source/usbloader/wbfs.c +++ b/source/usbloader/wbfs.c @@ -44,29 +44,31 @@ void WBFS_Spinner(s32 x, s32 max) { total = max; } -wbfs_disc_t* WBFS_OpenDisc(u8 *discid) { - if (wbfs_part_fs) return WBFS_FAT_OpenDisc(discid); +wbfs_disc_t* WBFS_OpenDisc(u8 *discid) +{ + if (wbfs_part_fs) return WBFS_FAT_OpenDisc(discid); - /* No device open */ - if (!hdd) - return NULL; + /* No device open */ + if (!hdd) + return NULL; - /* Open disc */ - return wbfs_open_disc(hdd, discid); + /* Open disc */ + return wbfs_open_disc(hdd, discid); } -void WBFS_CloseDisc(wbfs_disc_t *disc) { - if (wbfs_part_fs) { - WBFS_FAT_CloseDisc(disc); - return; - } +void WBFS_CloseDisc(wbfs_disc_t *disc) +{ + if (wbfs_part_fs) { + WBFS_FAT_CloseDisc(disc); + return; + } - /* No device open */ - if (!hdd || !disc) - return; + /* No device open */ + if (!hdd || !disc) + return; - /* Close disc */ - wbfs_close_disc(disc); + /* Close disc */ + wbfs_close_disc(disc); } void GetProgressValue(s32 * d, s32 * m) { @@ -271,153 +273,159 @@ s32 WBFS_Open(void) { wbfs_close(hdd); /* Open hard disk */ - wbfs_part_fs = wbfs_part_idx = wbfs_part_lba = 0; + wbfs_part_fs = wbfs_part_idx = wbfs_part_lba = 0; hdd = wbfs_open_hd(readCallback, writeCallback, NULL, sector_size, nb_sectors, 0); if (!hdd) return -1; - // Save the new sector size, so it will be used in read and write calls - sector_size = 1 << hdd->head->hd_sec_sz_s; + // Save the new sector size, so it will be used in read and write calls + sector_size = 1 << hdd->head->hd_sec_sz_s; - wbfs_part_idx = 1; + wbfs_part_idx = 1; return 0; } -s32 WBFS_OpenPart(u32 part_fs, u32 part_idx, u32 part_lba, u32 part_size, char *partition) { - // close - WBFS_Close(); +s32 WBFS_OpenPart(u32 part_fs, u32 part_idx, u32 part_lba, u32 part_size, char *partition) +{ + // close + WBFS_Close(); - if (part_fs == PART_FS_FAT) { - if (wbfsDev == WBFS_DEVICE_USB && part_lba == fat_usb_sec) { - strcpy(wbfs_fs_drive, "USB:"); - } else if (wbfsDev == WBFS_DEVICE_SDHC && part_lba == fat_sd_sec) { - strcpy(wbfs_fs_drive, "SD:"); - } else { - if (WBFSDevice_Init(part_lba)) return -1; - strcpy(wbfs_fs_drive, "WBFS:"); - } - } else if (part_fs == PART_FS_NTFS) { - int ret = MountNTFS(part_lba); - if (ret) return ret; - strcpy(wbfs_fs_drive, "NTFS:"); - } else { - if (WBFS_OpenLBA(part_lba, part_size)) return -3; - } + if (part_fs == PART_FS_FAT) { + if (wbfsDev == WBFS_DEVICE_USB && part_lba == fat_usb_sec) { + strcpy(wbfs_fs_drive, "USB:"); + } else if (wbfsDev == WBFS_DEVICE_SDHC && part_lba == fat_sd_sec) { + strcpy(wbfs_fs_drive, "SD:"); + } else { + if (WBFSDevice_Init(part_lba)) return -1; + strcpy(wbfs_fs_drive, "WBFS:"); + } + } else if (part_fs == PART_FS_NTFS) { + int ret = MountNTFS(part_lba); + if (ret) return ret; + strcpy(wbfs_fs_drive, "NTFS:"); + } else { + if (WBFS_OpenLBA(part_lba, part_size)) return -3; + } - // success - wbfs_part_fs = part_fs; - wbfs_part_idx = part_idx; - wbfs_part_lba = part_lba; + // success + wbfs_part_fs = part_fs; + wbfs_part_idx = part_idx; + wbfs_part_lba = part_lba; - char *fs = "WBFS"; - if (wbfs_part_fs == PART_FS_FAT) fs = "FAT"; - if (wbfs_part_fs == PART_FS_NTFS) fs = "NTFS"; - sprintf(partition, "%s%d", fs, wbfs_part_idx); - return 0; + char *fs = "WBFS"; + if (wbfs_part_fs == PART_FS_FAT) fs = "FAT"; + if (wbfs_part_fs == PART_FS_NTFS) fs = "NTFS"; + sprintf(partition, "%s%d", fs, wbfs_part_idx); + return 0; } -s32 WBFS_OpenNamed(char *partition) { - int i; - u32 part_fs = PART_FS_WBFS; - u32 part_idx = 0; - u32 part_lba = 0; - s32 ret = 0; - PartList plist; +s32 WBFS_OpenNamed(char *partition) +{ + int i; + u32 part_fs = PART_FS_WBFS; + u32 part_idx = 0; + u32 part_lba = 0; + s32 ret = 0; + PartList plist; - // close - WBFS_Close(); + // close + WBFS_Close(); - // parse partition option - if (strncasecmp(partition, "WBFS", 4) == 0) { - i = atoi(partition+4); - if (i < 1 || i > 4) goto err; - part_fs = PART_FS_WBFS; - part_idx = i; - } else if (strncasecmp(partition, "FAT", 3) == 0) { - if (wbfsDev != WBFS_DEVICE_USB) goto err; - i = atoi(partition+3); - if (i < 1 || i > 9) goto err; - part_fs = PART_FS_FAT; - part_idx = i; - } else if (strncasecmp(partition, "NTFS", 4) == 0) { - i = atoi(partition+4); - if (i < 1 || i > 9) goto err; - part_fs = PART_FS_NTFS; - part_idx = i; - } else { - goto err; - } + // parse partition option + if (strncasecmp(partition, "WBFS", 4) == 0) { + i = atoi(partition+4); + if (i < 1 || i > 4) goto err; + part_fs = PART_FS_WBFS; + part_idx = i; + } else if (strncasecmp(partition, "FAT", 3) == 0) { + if (wbfsDev != WBFS_DEVICE_USB) goto err; + i = atoi(partition+3); + if (i < 1 || i > 9) goto err; + part_fs = PART_FS_FAT; + part_idx = i; + } else if (strncasecmp(partition, "NTFS", 4) == 0) { + i = atoi(partition+4); + if (i < 1 || i > 9) goto err; + part_fs = PART_FS_NTFS; + part_idx = i; + } else { + goto err; + } - // Get partition entries - ret = Partition_GetList(wbfsDev, &plist); - if (ret || plist.num == 0) return -1; + // Get partition entries + ret = Partition_GetList(wbfsDev, &plist); + if (ret || plist.num == 0) return -1; - if (part_fs == PART_FS_WBFS) { - if (part_idx > plist.wbfs_n) goto err; - for (i=0; i plist.fat_n) goto err; - for (i=0; i plist.ntfs_n) goto err; - for (i=0; i= plist.num) goto err; - // set partition lba sector - part_lba = plist.pentry[i].sector; + if (part_fs == PART_FS_WBFS) { + if (part_idx > plist.wbfs_n) goto err; + for (i=0; i plist.fat_n) goto err; + for (i=0; i plist.ntfs_n) goto err; + for (i=0; i= plist.num) goto err; + // set partition lba sector + part_lba = plist.pentry[i].sector; - if (WBFS_OpenPart(part_fs, part_idx, part_lba, plist.pentry[i].size, partition)) { - goto err; - } - // success - return 0; + if (WBFS_OpenPart(part_fs, part_idx, part_lba, plist.pentry[i].size, partition)) { + goto err; + } + // success + return 0; err: - return -1; + return -1; } -s32 WBFS_OpenLBA(u32 lba, u32 size) { - wbfs_t *part = NULL; +s32 WBFS_OpenLBA(u32 lba, u32 size) +{ + wbfs_t *part = NULL; - /* Open partition */ - part = wbfs_open_partition(readCallback, writeCallback, NULL, sector_size, size, lba, 0); - if (!part) return -1; + /* Open partition */ + part = wbfs_open_partition(readCallback, writeCallback, NULL, sector_size, size, lba, 0); + if (!part) return -1; - /* Close current hard disk */ - if (hdd) wbfs_close(hdd); - hdd = part; + /* Close current hard disk */ + if (hdd) wbfs_close(hdd); + hdd = part; - return 0; + return 0; } -bool WBFS_Close(void) { +bool WBFS_Close(void) +{ /* Close hard disk */ if (hdd) { wbfs_close(hdd); - hdd = NULL; - } + hdd = NULL; + } - WBFSDevice_deInit(); - wbfs_part_fs = 0; - wbfs_part_idx = 0; - wbfs_part_lba = 0; - wbfs_fs_drive[0] = '\0'; + WBFSDevice_deInit(); + wbfs_part_fs = 0; + wbfs_part_idx = 0; + wbfs_part_lba = 0; + wbfs_fs_drive[0] = '\0'; return 0; } -bool WBFS_Mounted() { - return (hdd != NULL); +bool WBFS_Mounted() +{ + return (hdd != NULL); } -bool WBFS_Selected() { - if (wbfs_part_fs && wbfs_part_lba && *wbfs_fs_drive) return true; - return WBFS_Mounted(); +bool WBFS_Selected() +{ + if (wbfs_part_fs && wbfs_part_lba && *wbfs_fs_drive) return true; + return WBFS_Mounted(); } s32 WBFS_Format(u32 lba, u32 size) { @@ -435,7 +443,7 @@ s32 WBFS_Format(u32 lba, u32 size) { } s32 WBFS_GetCount(u32 *count) { - if (wbfs_part_fs) return WBFS_FAT_GetCount(count); + if (wbfs_part_fs) return WBFS_FAT_GetCount(count); /* No device open */ if (!hdd) @@ -448,7 +456,7 @@ s32 WBFS_GetCount(u32 *count) { } s32 WBFS_GetHeaders(void *outbuf, u32 cnt, u32 len) { - if (wbfs_part_fs) return WBFS_FAT_GetHeaders(outbuf, cnt, len); + if (wbfs_part_fs) return WBFS_FAT_GetHeaders(outbuf, cnt, len); u32 idx, size; s32 ret; @@ -485,7 +493,7 @@ s32 WBFS_CheckGame(u8 *discid) { } s32 WBFS_AddGame(void) { - if (wbfs_part_fs) return WBFS_FAT_AddGame(); + if (wbfs_part_fs) return WBFS_FAT_AddGame(); s32 ret; @@ -494,15 +502,15 @@ s32 WBFS_AddGame(void) { return -1; /* Add game to device */ - partition_selector_t part_sel; - int copy_1_1 = 0; - - if (Settings.fullcopy) { - part_sel = ALL_PARTITIONS; - copy_1_1 = 1; - } else { - part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; - } + partition_selector_t part_sel; + int copy_1_1 = 0; + + if (Settings.fullcopy) { + part_sel = ALL_PARTITIONS; + copy_1_1 = 1; + } else { + part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; + } ret = wbfs_add_disc(hdd, __WBFS_ReadDVD, NULL, WBFS_Spinner, part_sel, copy_1_1); if (ret < 0) @@ -512,7 +520,7 @@ s32 WBFS_AddGame(void) { } s32 WBFS_RemoveGame(u8 *discid) { - if (wbfs_part_fs) return WBFS_FAT_RemoveGame(discid); + if (wbfs_part_fs) return WBFS_FAT_RemoveGame(discid); s32 ret; @@ -534,24 +542,24 @@ s32 WBFS_GameSize(u8 *discid, f32 *size) { u32 sectors; /* Open disc */ - disc = WBFS_OpenDisc(discid); + disc = WBFS_OpenDisc(discid); if (!disc) return -2; /* Get game size in sectors */ - sectors = wbfs_sector_used(disc->p, disc->header); + sectors = wbfs_sector_used(disc->p, disc->header); /* Copy value */ - *size = (disc->p->wbfs_sec_sz / GB_SIZE) * sectors; + *size = (disc->p->wbfs_sec_sz / GB_SIZE) * sectors; /* Close disc */ - WBFS_CloseDisc(disc); + WBFS_CloseDisc(disc); return 0; } s32 WBFS_DiskSpace(f32 *used, f32 *free) { - if (wbfs_part_fs) return WBFS_FAT_DiskSpace(used, free); + if (wbfs_part_fs) return WBFS_FAT_DiskSpace(used, free); f32 ssize; u32 cnt; @@ -573,8 +581,10 @@ s32 WBFS_DiskSpace(f32 *used, f32 *free) { return 0; } -s32 WBFS_RenameGame(u8 *discid, const void *newname) { - if (wbfs_part_fs) { +s32 WBFS_RenameGame(u8 *discid, const void *newname) +{ + if (wbfs_part_fs) + { return WBFS_FAT_RenameGame(discid, newname); } @@ -590,10 +600,12 @@ s32 WBFS_RenameGame(u8 *discid, const void *newname) { return 0; } -s32 WBFS_ReIDGame(u8 *discid, const void *newID) { - if (wbfs_part_fs) { - return WBFS_FAT_ReIDGame(discid, newID); - } +s32 WBFS_ReIDGame(u8 *discid, const void *newID) +{ + if (wbfs_part_fs) + { + return WBFS_FAT_ReIDGame(discid, newID); + } s32 ret; @@ -608,25 +620,26 @@ s32 WBFS_ReIDGame(u8 *discid, const void *newID) { } f32 WBFS_EstimeGameSize(void) { - if (wbfs_part_fs) { - return WBFS_FAT_EstimateGameSize(); - } + if (wbfs_part_fs) { + return WBFS_FAT_EstimateGameSize(); + } - partition_selector_t part_sel = ONLY_GAME_PARTITION; - if (Settings.fullcopy) { - part_sel = ALL_PARTITIONS; - } else { - switch (Settings.partitions_to_install) { - case install_game_only: - part_sel = ONLY_GAME_PARTITION; - break; - case install_all: - part_sel = ALL_PARTITIONS; - break; - case install_all_but_update: - part_sel = REMOVE_UPDATE_PARTITION; - break; - } - } + partition_selector_t part_sel = ONLY_GAME_PARTITION; + if (Settings.fullcopy) { + part_sel = ALL_PARTITIONS; + } else { + switch(Settings.partitions_to_install) + { + case install_game_only: + part_sel = ONLY_GAME_PARTITION; + break; + case install_all: + part_sel = ALL_PARTITIONS; + break; + case install_all_but_update: + part_sel = REMOVE_UPDATE_PARTITION; + break; + } + } return wbfs_estimate_disc(hdd, __WBFS_ReadDVD, NULL, part_sel); } diff --git a/source/usbloader/wbfs.h b/source/usbloader/wbfs.h index 46d44464..6b873b04 100644 --- a/source/usbloader/wbfs.h +++ b/source/usbloader/wbfs.h @@ -13,18 +13,18 @@ extern "C" { }; /* Macros */ -#define WBFS_MIN_DEVICE 1 -#define WBFS_MAX_DEVICE 2 + #define WBFS_MIN_DEVICE 1 + #define WBFS_MAX_DEVICE 2 -#define PART_FS_WBFS 0 -#define PART_FS_FAT 1 -#define PART_FS_NTFS 2 + #define PART_FS_WBFS 0 + #define PART_FS_FAT 1 + #define PART_FS_NTFS 2 - extern s32 wbfsDev; - extern int wbfs_part_fs; - extern u32 wbfs_part_idx; - extern u32 wbfs_part_lba; - extern char wbfs_fs_drive[16]; + extern s32 wbfsDev; + extern int wbfs_part_fs; + extern u32 wbfs_part_idx; + extern u32 wbfs_part_lba; + extern char wbfs_fs_drive[16]; /* Prototypes */ void GetProgressValue(s32 * d, s32 * m); @@ -41,20 +41,20 @@ extern "C" { s32 WBFS_GameSize(u8 *, f32 *); s32 WBFS_DiskSpace(f32 *, f32 *); s32 WBFS_RenameGame(u8 *, const void *); - s32 WBFS_ReIDGame(u8 *discid, const void *newID); + s32 WBFS_ReIDGame(u8 *discid, const void *newID); f32 WBFS_EstimeGameSize(void); s32 __WBFS_ReadUSB(void *fp, u32 lba, u32 count, void *iobuf); s32 __WBFS_WriteUSB(void *fp, u32 lba, u32 count, void *iobuf); - s32 WBFS_OpenPart(u32 part_fat, u32 part_idx, u32 part_lba, u32 part_size, char *partition); - s32 WBFS_OpenNamed(char *partition); - s32 WBFS_OpenLBA(u32 lba, u32 size); - wbfs_disc_t* WBFS_OpenDisc(u8 *discid); - void WBFS_CloseDisc(wbfs_disc_t *disc); - bool WBFS_Close(); - bool WBFS_Mounted(); - bool WBFS_Selected(); + s32 WBFS_OpenPart(u32 part_fat, u32 part_idx, u32 part_lba, u32 part_size, char *partition); + s32 WBFS_OpenNamed(char *partition); + s32 WBFS_OpenLBA(u32 lba, u32 size); + wbfs_disc_t* WBFS_OpenDisc(u8 *discid); + void WBFS_CloseDisc(wbfs_disc_t *disc); + bool WBFS_Close(); + bool WBFS_Mounted(); + bool WBFS_Selected(); #ifdef __cplusplus diff --git a/source/usbloader/wbfs_fat.c b/source/usbloader/wbfs_fat.c index 3ab51508..b432f4c5 100644 --- a/source/usbloader/wbfs_fat.c +++ b/source/usbloader/wbfs_fat.c @@ -45,670 +45,695 @@ static int fat_hdr_count = 0; void WBFS_Spinner(s32 x, s32 max); s32 __WBFS_ReadDVD(void *fp, u32 lba, u32 len, void *iobuf); -bool is_gameid(char *id) { - int i; - for (i=0; i<6; i++) { - if (!isalnum((u32) id[i])) return false; - } - return true; +bool is_gameid(char *id) +{ + int i; + for (i=0; i<6; i++) { + if (!isalnum((u32) id[i])) return false; + } + return true; } -s32 _WBFS_FAT_GetHeadersCount() { - DIR_ITER *dir_iter; - char path[MAX_FAT_PATH]; - char fname[MAX_FAT_PATH]; - char fpath[MAX_FAT_PATH]; - struct discHdr tmpHdr; - struct stat st; - wbfs_t *part = NULL; - u8 id[8]; - int ret; - char *p; - u32 size; - int is_dir; - int len; - char dir_title[65]; - char *title; +s32 _WBFS_FAT_GetHeadersCount() +{ + DIR_ITER *dir_iter; + char path[MAX_FAT_PATH]; + char fname[MAX_FAT_PATH]; + char fpath[MAX_FAT_PATH]; + struct discHdr tmpHdr; + struct stat st; + wbfs_t *part = NULL; + u8 id[8]; + int ret; + char *p; + u32 size; + int is_dir; + int len; + char dir_title[65]; + char *title; - //dbg_time1(); + //dbg_time1(); - SAFE_FREE(fat_hdr_list); - fat_hdr_count = 0; + SAFE_FREE(fat_hdr_list); + fat_hdr_count = 0; - strcpy(path, wbfs_fs_drive); - strcat(path, wbfs_fat_dir); - dir_iter = diropen(path); - if (!dir_iter) return 0; + strcpy(path, wbfs_fs_drive); + strcat(path, wbfs_fat_dir); + dir_iter = diropen(path); + if (!dir_iter) return 0; - while (dirnext(dir_iter, fname, &st) == 0) { - //printf("found: %s\n", fname); Wpad_WaitButtonsCommon(); - if ((char)fname[0] == '.') continue; - len = strlen(fname); - if (len < 8) continue; // "GAMEID_x" + while (dirnext(dir_iter, fname, &st) == 0) { + //printf("found: %s\n", fname); Wpad_WaitButtonsCommon(); + if ((char)fname[0] == '.') continue; + len = strlen(fname); + if (len < 8) continue; // "GAMEID_x" - memcpy(id, fname, 6); - id[6] = 0; + memcpy(id, fname, 6); + id[6] = 0; - is_dir = S_ISDIR(st.st_mode); - //printf("mode: %d %d %x\n", is_dir, st.st_mode, st.st_mode); - if (is_dir) { - int lay_a = 0; - int lay_b = 0; - if (fname[6] == '_' && is_gameid((char*)id)) { - // usb:/wbfs/GAMEID_TITLE/GAMEID.wbfs - lay_a = 1; - } - if (fname[len-8] == '[' && fname[len-1] == ']' && is_gameid(&fname[len-7])) { - // usb:/wbfs/TITLE[GAMEID]/GAMEID.wbfs - lay_b = 1; - } - if (!lay_a && !lay_b) continue; - if (lay_a) { - strncpy(dir_title, &fname[7], sizeof(dir_title)); - } else { -try_lay_b: - memcpy(id, &fname[len-7], 6); - id[6] = 0; - strncpy(dir_title, fname, sizeof(dir_title)); - dir_title[len-8] = 0; // cut at '[' - int n = strlen(dir_title); - if (n == 0) continue; - // cut trailing _ or ' ' - if (dir_title[n - 1] == ' ' || dir_title[n - 1] == '_' ) { - dir_title[n - 1] = 0; - } - if (strlen(dir_title) == 0) continue; - } - snprintf(fpath, sizeof(fpath), "%s/%s/%s.wbfs", path, fname, id); - //printf("path2: %s\n", fpath); - // if more than 50 games, skip second stat to improve speed - // but if ambiguous layout check anyway - if (fat_hdr_count < 50 || (lay_a && lay_b)) { - if (stat(fpath, &st) == -1) { - //printf("missing: %s\n", fpath); - // try .iso - strcpy(strrchr(fpath, '.'), ".iso"); // replace .wbfs with .iso - if (stat(fpath, &st) == -1) { - //printf("missing: %s\n", fpath); - if (lay_a && lay_b == 1) { - // mark lay_b so that the stat check is still done, - // but lay_b is not re-tried again - lay_b = 2; - // retry with layout b - goto try_lay_b; - } - continue; - } - } - } else { - st.st_size = 1024*1024; - } - } else { - // usb:/wbfs/GAMEID.wbfs - // or usb:/wbfs/GAMEID.iso - p = strrchr(fname, '.'); - if (!p) continue; - if ( (strcasecmp(p, ".wbfs") != 0) - && (strcasecmp(p, ".iso") != 0) ) continue; - if (p - fname != 6) continue; // GAMEID. - snprintf(fpath, sizeof(fpath), "%s/%s", path, fname); - } + is_dir = S_ISDIR(st.st_mode); + //printf("mode: %d %d %x\n", is_dir, st.st_mode, st.st_mode); + if (is_dir) { + int lay_a = 0; + int lay_b = 0; + if (fname[6] == '_' && is_gameid((char*)id)) { + // usb:/wbfs/GAMEID_TITLE/GAMEID.wbfs + lay_a = 1; + } + if (fname[len-8] == '[' && fname[len-1] == ']' && is_gameid(&fname[len-7])) { + // usb:/wbfs/TITLE[GAMEID]/GAMEID.wbfs + lay_b = 1; + } + if (!lay_a && !lay_b) continue; + if (lay_a) { + strncpy(dir_title, &fname[7], sizeof(dir_title)); + } else { + try_lay_b: + memcpy(id, &fname[len-7], 6); + id[6] = 0; + strncpy(dir_title, fname, sizeof(dir_title)); + dir_title[len-8] = 0; // cut at '[' + int n = strlen(dir_title); + if (n == 0) continue; + // cut trailing _ or ' ' + if (dir_title[n - 1] == ' ' || dir_title[n - 1] == '_' ) { + dir_title[n - 1] = 0; + } + if (strlen(dir_title) == 0) continue; + } + snprintf(fpath, sizeof(fpath), "%s/%s/%s.wbfs", path, fname, id); + //printf("path2: %s\n", fpath); + // if more than 50 games, skip second stat to improve speed + // but if ambiguous layout check anyway + if (fat_hdr_count < 50 || (lay_a && lay_b)) { + if (stat(fpath, &st) == -1) { + //printf("missing: %s\n", fpath); + // try .iso + strcpy(strrchr(fpath, '.'), ".iso"); // replace .wbfs with .iso + if (stat(fpath, &st) == -1) { + //printf("missing: %s\n", fpath); + if (lay_a && lay_b == 1) { + // mark lay_b so that the stat check is still done, + // but lay_b is not re-tried again + lay_b = 2; + // retry with layout b + goto try_lay_b; + } + continue; + } + } + } else { + st.st_size = 1024*1024; + } + } else { + // usb:/wbfs/GAMEID.wbfs + // or usb:/wbfs/GAMEID.iso + p = strrchr(fname, '.'); + if (!p) continue; + if ( (strcasecmp(p, ".wbfs") != 0) + && (strcasecmp(p, ".iso") != 0) ) continue; + if (p - fname != 6) continue; // GAMEID. + snprintf(fpath, sizeof(fpath), "%s/%s", path, fname); + } - //printf("found: %s %d MB\n", fpath, (int)(st.st_size/1024/1024)); - // size must be at least 1MB to be considered a valid wbfs file - if (st.st_size < 1024*1024) continue; - // if we have titles.txt entry use that - title = cfg_get_title(id); - // if directory, and no titles.txt get title from dir name - if (!title && is_dir) { - title = dir_title; - } - if (title) { - memset(&tmpHdr, 0, sizeof(tmpHdr)); - memcpy(tmpHdr.id, id, 6); - strncpy(tmpHdr.title, title, sizeof(tmpHdr.title)-1); - tmpHdr.magic = 0x5D1C9EA3; - goto add_hdr; - } + //printf("found: %s %d MB\n", fpath, (int)(st.st_size/1024/1024)); + // size must be at least 1MB to be considered a valid wbfs file + if (st.st_size < 1024*1024) continue; + // if we have titles.txt entry use that + title = cfg_get_title(id); + // if directory, and no titles.txt get title from dir name + if (!title && is_dir) { + title = dir_title; + } + if (title) { + memset(&tmpHdr, 0, sizeof(tmpHdr)); + memcpy(tmpHdr.id, id, 6); + strncpy(tmpHdr.title, title, sizeof(tmpHdr.title)-1); + tmpHdr.magic = 0x5D1C9EA3; + goto add_hdr; + } - // else read it from file directly - if (strcasecmp(strrchr(fpath,'.'), ".wbfs") == 0) { - // wbfs file directly - FILE *fp = fopen(fpath, "rb"); - if (fp != NULL) { - fseek(fp, 512, SEEK_SET); - fread(&tmpHdr, sizeof(struct discHdr), 1, fp); - fclose(fp); - if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { - goto add_hdr; - } - } - // no title found, read it from wbfs file - // but this is a little bit slower - // open 'partition' file - part = WBFS_FAT_OpenPart(fpath); - if (!part) { - printf("bad wbfs file: %s\n", fpath); - sleep(2); - continue; - } - /* Get header */ - ret = wbfs_get_disc_info(part, 0, (u8*)&tmpHdr, - sizeof(struct discHdr), &size); - WBFS_FAT_ClosePart(part); - if (ret == 0) { - goto add_hdr; - } - } else if (strcasecmp(strrchr(fpath,'.'), ".iso") == 0) { - // iso file - FILE *fp = fopen(fpath, "rb"); - if (fp != NULL) { - fseek(fp, 0, SEEK_SET); - fread(&tmpHdr, sizeof(struct discHdr), 1, fp); - fclose(fp); - if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { - goto add_hdr; - } - } - } - // fail: - continue; + // else read it from file directly + if (strcasecmp(strrchr(fpath,'.'), ".wbfs") == 0) { + // wbfs file directly + FILE *fp = fopen(fpath, "rb"); + if (fp != NULL) { + fseek(fp, 512, SEEK_SET); + fread(&tmpHdr, sizeof(struct discHdr), 1, fp); + fclose(fp); + if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { + goto add_hdr; + } + } + // no title found, read it from wbfs file + // but this is a little bit slower + // open 'partition' file + part = WBFS_FAT_OpenPart(fpath); + if (!part) { + printf("bad wbfs file: %s\n", fpath); + sleep(2); + continue; + } + /* Get header */ + ret = wbfs_get_disc_info(part, 0, (u8*)&tmpHdr, + sizeof(struct discHdr), &size); + WBFS_FAT_ClosePart(part); + if (ret == 0) { + goto add_hdr; + } + } else if (strcasecmp(strrchr(fpath,'.'), ".iso") == 0) { + // iso file + FILE *fp = fopen(fpath, "rb"); + if (fp != NULL) { + fseek(fp, 0, SEEK_SET); + fread(&tmpHdr, sizeof(struct discHdr), 1, fp); + fclose(fp); + if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { + goto add_hdr; + } + } + } + // fail: + continue; - // succes: add tmpHdr to list: -add_hdr: - memset(&st, 0, sizeof(st)); - //printf("added: %.6s %.20s\n", tmpHdr.id, tmpHdr.title); Wpad_WaitButtons(); - fat_hdr_count++; - fat_hdr_list = realloc(fat_hdr_list, fat_hdr_count * sizeof(struct discHdr)); - memcpy(&fat_hdr_list[fat_hdr_count-1], &tmpHdr, sizeof(struct discHdr)); - } - dirclose(dir_iter); - //dbg_time2("\nFAT_GetCount"); Wpad_WaitButtonsCommon(); - return 0; + // succes: add tmpHdr to list: + add_hdr: + memset(&st, 0, sizeof(st)); + //printf("added: %.6s %.20s\n", tmpHdr.id, tmpHdr.title); Wpad_WaitButtons(); + fat_hdr_count++; + fat_hdr_list = realloc(fat_hdr_list, fat_hdr_count * sizeof(struct discHdr)); + memcpy(&fat_hdr_list[fat_hdr_count-1], &tmpHdr, sizeof(struct discHdr)); + } + dirclose(dir_iter); + //dbg_time2("\nFAT_GetCount"); Wpad_WaitButtonsCommon(); + return 0; } -s32 WBFS_FAT_GetCount(u32 *count) { - *count = 0; - _WBFS_FAT_GetHeadersCount(); - if (fat_hdr_count && fat_hdr_list) { - // for compacter mem - move up as it will be freed later - int size = fat_hdr_count * sizeof(struct discHdr); - struct discHdr *buf = malloc(size); - if (buf) { - memcpy(buf, fat_hdr_list, size); - SAFE_FREE(fat_hdr_list); - fat_hdr_list = buf; - } - } - *count = fat_hdr_count; - return 0; +s32 WBFS_FAT_GetCount(u32 *count) +{ + *count = 0; + _WBFS_FAT_GetHeadersCount(); + if (fat_hdr_count && fat_hdr_list) { + // for compacter mem - move up as it will be freed later + int size = fat_hdr_count * sizeof(struct discHdr); + struct discHdr *buf = malloc(size); + if (buf) { + memcpy(buf, fat_hdr_list, size); + SAFE_FREE(fat_hdr_list); + fat_hdr_list = buf; + } + } + *count = fat_hdr_count; + return 0; } -s32 WBFS_FAT_GetHeaders(void *outbuf, u32 cnt, u32 len) { - int i; - int slen = len; - if (slen > sizeof(struct discHdr)) { - slen = sizeof(struct discHdr); - } - for (i=0; i sizeof(struct discHdr)) { + slen = sizeof(struct discHdr); + } + for (i=0; ip = &wbfs_iso_file; - iso_file->header = (void*)fd; - return iso_file; - } + if (strcasecmp(strrchr(fname,'.'), ".iso") == 0) { + // .iso file + // create a fake wbfs_disc + int fd; + fd = open(fname, O_RDONLY); + if (fd == -1) return NULL; + wbfs_disc_t *iso_file = calloc(sizeof(wbfs_disc_t),1); + if (iso_file == NULL) return NULL; + // mark with a special wbfs_part + wbfs_iso_file.wbfs_sec_sz = 512; + iso_file->p = &wbfs_iso_file; + iso_file->header = (void*)fd; + return iso_file; + } - wbfs_t *part = WBFS_FAT_OpenPart(fname); - if (!part) return NULL; - return wbfs_open_disc(part, discid); + wbfs_t *part = WBFS_FAT_OpenPart(fname); + if (!part) return NULL; + return wbfs_open_disc(part, discid); } -void WBFS_FAT_CloseDisc(wbfs_disc_t* disc) { - if (!disc) return; - wbfs_t *part = disc->p; +void WBFS_FAT_CloseDisc(wbfs_disc_t* disc) +{ + if (!disc) return; + wbfs_t *part = disc->p; - // is this really a .iso file? - if (part == &wbfs_iso_file) { - close((int)disc->header); - free(disc); - return; - } + // is this really a .iso file? + if (part == &wbfs_iso_file) { + close((int)disc->header); + free(disc); + return; + } - wbfs_close_disc(disc); - WBFS_FAT_ClosePart(part); - return; + wbfs_close_disc(disc); + WBFS_FAT_ClosePart(part); + return; } -s32 WBFS_FAT_DiskSpace(f32 *used, f32 *free) { - f32 size; - int ret; - struct statvfs wbfs_fat_vfs; +s32 WBFS_FAT_DiskSpace(f32 *used, f32 *free) +{ + f32 size; + int ret; + struct statvfs wbfs_fat_vfs; - *used = 0; - *free = 0; - ret = statvfs(wbfs_fs_drive, &wbfs_fat_vfs); - if (ret) return -1; + *used = 0; + *free = 0; + ret = statvfs(wbfs_fs_drive, &wbfs_fat_vfs); + if (ret) return -1; - /* FS size in GB */ - size = (f32)wbfs_fat_vfs.f_frsize * (f32)wbfs_fat_vfs.f_blocks / GB_SIZE; - *free = (f32)wbfs_fat_vfs.f_frsize * (f32)wbfs_fat_vfs.f_bfree / GB_SIZE; - *used = size - *free; + /* FS size in GB */ + size = (f32)wbfs_fat_vfs.f_frsize * (f32)wbfs_fat_vfs.f_blocks / GB_SIZE; + *free = (f32)wbfs_fat_vfs.f_frsize * (f32)wbfs_fat_vfs.f_bfree / GB_SIZE; + *used = size - *free; - return 0; + return 0; } -static int nop_read_sector(void *_fp,u32 lba,u32 count,void*buf) { - //printf("read %d %d\n", lba, count); //Wpad_WaitButtons(); - return 0; +static int nop_read_sector(void *_fp,u32 lba,u32 count,void*buf) +{ + //printf("read %d %d\n", lba, count); //Wpad_WaitButtons(); + return 0; } -static int nop_write_sector(void *_fp,u32 lba,u32 count,void*buf) { - //printf("write %d %d\n", lba, count); //Wpad_WaitButtons(); - return 0; +static int nop_write_sector(void *_fp,u32 lba,u32 count,void*buf) +{ + //printf("write %d %d\n", lba, count); //Wpad_WaitButtons(); + return 0; } -void WBFS_FAT_fname(u8 *id, char *fname, int len, char *path) { - if (path == NULL) { - snprintf(fname, len, "%s%s/%.6s.wbfs", wbfs_fs_drive, wbfs_fat_dir, id); - } else { - snprintf(fname, len, "%s/%.6s.wbfs", path, id); - } +void WBFS_FAT_fname(u8 *id, char *fname, int len, char *path) +{ + if (path == NULL) { + snprintf(fname, len, "%s%s/%.6s.wbfs", wbfs_fs_drive, wbfs_fat_dir, id); + } else { + snprintf(fname, len, "%s/%.6s.wbfs", path, id); + } } // format title so that it is usable in a filename -void title_filename(char *title) { +void title_filename(char *title) +{ int i, len; // trim leading space - len = strlen(title); - while (*title == ' ') { - memmove(title, title+1, len); - len--; - } + len = strlen(title); + while (*title == ' ') { + memmove(title, title+1, len); + len--; + } // trim trailing space - not allowed on windows directories while (len && title[len-1] == ' ') { - title[len-1] = 0; - len--; + title[len-1] = 0; + len--; } // replace silly chars with '_' for (i=0; iid, 6); - name[6] = 0; - strncpy(title, get_title(header), sizeof(title)); - title_filename(title); + memcpy(name, header->id, 6); + name[6] = 0; + strncpy(title, get_title(header), sizeof(title)); + title_filename(title); - if (layout == 0) { - sprintf(name, "%s_%s", id, title); - } else { - sprintf(name, "%s [%s]", title, id); - } + if (layout == 0) { + sprintf(name, "%s_%s", id, title); + } else { + sprintf(name, "%s [%s]", title, id); + } - // replace space with '_' - if (re_space) { - len = strlen(name); - for (i = 0; i < len; i++) { - if (name[i]==' ') name[i] = '_'; - } - } + // replace space with '_' + if (re_space) { + len = strlen(name); + for (i = 0; i < len; i++) { + if(name[i]==' ') name[i] = '_'; + } + } } -void WBFS_FAT_get_dir(struct discHdr *header, char *path) { - strcpy(path, wbfs_fs_drive); - strcat(path, wbfs_fat_dir); - if (Settings.FatInstallToDir) { - strcat(path, "/"); - int layout = 0; - if (Settings.FatInstallToDir == 2) layout = 1; - mk_gameid_title(header, path + strlen(path), 0, layout); - } +void WBFS_FAT_get_dir(struct discHdr *header, char *path) +{ + strcpy(path, wbfs_fs_drive); + strcat(path, wbfs_fat_dir); + if (Settings.FatInstallToDir) { + strcat(path, "/"); + int layout = 0; + if (Settings.FatInstallToDir == 2) layout = 1; + mk_gameid_title(header, path + strlen(path), 0, layout); + } } -void mk_title_txt(struct discHdr *header, char *path) { - char fname[MAX_FAT_PATH]; - FILE *f; +void mk_title_txt(struct discHdr *header, char *path) +{ + char fname[MAX_FAT_PATH]; + FILE *f; - strcpy(fname, path); - strcat(fname, "/"); - mk_gameid_title(header, fname+strlen(fname), 1, 0); - strcat(fname, ".txt"); + strcpy(fname, path); + strcat(fname, "/"); + mk_gameid_title(header, fname+strlen(fname), 1, 0); + strcat(fname, ".txt"); - f = fopen(fname, "wb"); - if (!f) return; - fprintf(f, "%.6s = %.64s\n", header->id, get_title(header)); - fclose(f); - printf("Info file: %s\n", fname); + f = fopen(fname, "wb"); + if (!f) return; + fprintf(f, "%.6s = %.64s\n", header->id, get_title(header)); + fclose(f); + printf("Info file: %s\n", fname); } -int WBFS_FAT_find_fname(u8 *id, char *fname, int len) { - struct stat st; - // look for direct .wbfs file - WBFS_FAT_fname(id, fname, len, NULL); - if (stat(fname, &st) == 0) return 1; - // look for direct .iso file - strcpy(strrchr(fname, '.'), ".iso"); // replace .wbfs with .iso - if (stat(fname, &st) == 0) return 1; - // direct file not found, check subdirs - *fname = 0; - DIR_ITER *dir_iter; - char path[MAX_FAT_PATH]; - char name[MAX_FAT_PATH]; - strcpy(path, wbfs_fs_drive); - strcat(path, wbfs_fat_dir); - dir_iter = diropen(path); - //printf("dir: %s %p\n", path, dir); Wpad_WaitButtons(); - if (!dir_iter) { - return 0; - } - while (dirnext(dir_iter, name, &st) == 0) { - if (name[0] == '.') continue; - int n = strlen(name); - if (n < 8) continue; - if (name[6] == '_') { - // GAMEID_TITLE - if (strncmp(name, (char*)id, 6) != 0) goto try_alter; - } else { -try_alter: - // TITLE [GAMEID] - if (name[n-8] != '[' || name[n-1] != ']') continue; - if (strncmp(&name[n-7], (char*)id, 6) != 0) continue; - } - // look for .wbfs file - snprintf(fname, len, "%s/%s/%.6s.wbfs", path, name, id); - if (stat(fname, &st) == 0) { - break; - } - // look for .iso file - snprintf(fname, len, "%s/%s/%.6s.iso", path, name, id); - if (stat(fname, &st) == 0) { - break; - } - *fname = 0; - } - dirclose(dir_iter); - if (*fname) { - // found - //printf("found:%s\n", fname); - return 2; - } - // not found - return 0; +int WBFS_FAT_find_fname(u8 *id, char *fname, int len) +{ + struct stat st; + // look for direct .wbfs file + WBFS_FAT_fname(id, fname, len, NULL); + if (stat(fname, &st) == 0) return 1; + // look for direct .iso file + strcpy(strrchr(fname, '.'), ".iso"); // replace .wbfs with .iso + if (stat(fname, &st) == 0) return 1; + // direct file not found, check subdirs + *fname = 0; + DIR_ITER *dir_iter; + char path[MAX_FAT_PATH]; + char name[MAX_FAT_PATH]; + strcpy(path, wbfs_fs_drive); + strcat(path, wbfs_fat_dir); + dir_iter = diropen(path); + //printf("dir: %s %p\n", path, dir); Wpad_WaitButtons(); + if (!dir_iter) { + return 0; + } + while (dirnext(dir_iter, name, &st) == 0) { + if (name[0] == '.') continue; + int n = strlen(name); + if (n < 8) continue; + if (name[6] == '_') { + // GAMEID_TITLE + if (strncmp(name, (char*)id, 6) != 0) goto try_alter; + } else { + try_alter: + // TITLE [GAMEID] + if (name[n-8] != '[' || name[n-1] != ']') continue; + if (strncmp(&name[n-7], (char*)id, 6) != 0) continue; + } + // look for .wbfs file + snprintf(fname, len, "%s/%s/%.6s.wbfs", path, name, id); + if (stat(fname, &st) == 0) { + break; + } + // look for .iso file + snprintf(fname, len, "%s/%s/%.6s.iso", path, name, id); + if (stat(fname, &st) == 0) { + break; + } + *fname = 0; + } + dirclose(dir_iter); + if (*fname) { + // found + //printf("found:%s\n", fname); + return 2; + } + // not found + return 0; } -wbfs_t* WBFS_FAT_OpenPart(char *fname) { - wbfs_t *part = NULL; - int ret; +wbfs_t* WBFS_FAT_OpenPart(char *fname) +{ + wbfs_t *part = NULL; + int ret; - // wbfs 'partition' file - ret = split_open(&split, fname); - if (ret) return NULL; - part = wbfs_open_partition( - split_read_sector, - nop_write_sector, //readonly //split_write_sector, - &split, fat_sector_size, split.total_sec, 0, 0); - if (!part) { - split_close(&split); - } - return part; + // wbfs 'partition' file + ret = split_open(&split, fname); + if (ret) return NULL; + part = wbfs_open_partition( + split_read_sector, + nop_write_sector, //readonly //split_write_sector, + &split, fat_sector_size, split.total_sec, 0, 0); + if (!part) { + split_close(&split); + } + return part; } -wbfs_t* WBFS_FAT_CreatePart(u8 *id, char *path) { - char fname[MAX_FAT_PATH]; - wbfs_t *part = NULL; - u64 size = (u64)143432*2*0x8000ULL; - u32 n_sector = size / 512; - int ret; +wbfs_t* WBFS_FAT_CreatePart(u8 *id, char *path) +{ + char fname[MAX_FAT_PATH]; + wbfs_t *part = NULL; + u64 size = (u64)143432*2*0x8000ULL; + u32 n_sector = size / 512; + int ret; - //printf("CREATE PART %s %lld %d\n", id, size, n_sector); - snprintf(fname, sizeof(fname), "%s%s", wbfs_fs_drive, wbfs_fat_dir); - mkdir(fname, 0777); // base usb:/wbfs - mkdir(path, 0777); // game subdir - WBFS_FAT_fname(id, fname, sizeof(fname), path); - printf("Writing to %s\n", fname); - ret = split_create(&split, fname, OPT_split_size, size, true); - if (ret) return NULL; + //printf("CREATE PART %s %lld %d\n", id, size, n_sector); + snprintf(fname, sizeof(fname), "%s%s", wbfs_fs_drive, wbfs_fat_dir); + mkdir(fname, 0777); // base usb:/wbfs + mkdir(path, 0777); // game subdir + WBFS_FAT_fname(id, fname, sizeof(fname), path); + printf("Writing to %s\n", fname); + ret = split_create(&split, fname, OPT_split_size, size, true); + if (ret) return NULL; - // force create first file - u32 scnt = 0; - int fd = split_get_file(&split, 0, &scnt, 0); - if (fd<0) { - printf("ERROR creating file\n"); - sleep(2); - split_close(&split); - return NULL; - } + // force create first file + u32 scnt = 0; + int fd = split_get_file(&split, 0, &scnt, 0); + if (fd<0) { + printf("ERROR creating file\n"); + sleep(2); + split_close(&split); + return NULL; + } - part = wbfs_open_partition( - split_read_sector, - split_write_sector, - &split, fat_sector_size, n_sector, 0, 1); - if (!part) { - split_close(&split); - } - return part; + part = wbfs_open_partition( + split_read_sector, + split_write_sector, + &split, fat_sector_size, n_sector, 0, 1); + if (!part) { + split_close(&split); + } + return part; } -void WBFS_FAT_ClosePart(wbfs_t* part) { - if (!part) return; - split_info_t *s = (split_info_t*)part->callback_data; - wbfs_close(part); - if (s) split_close(s); +void WBFS_FAT_ClosePart(wbfs_t* part) +{ + if (!part) return; + split_info_t *s = (split_info_t*)part->callback_data; + wbfs_close(part); + if (s) split_close(s); } -s32 WBFS_FAT_RemoveGame(u8 *discid) { - char fname[MAX_FAT_PATH]; - int loc; - // wbfs 'partition' file - loc = WBFS_FAT_find_fname(discid, fname, sizeof(fname)); - if ( !loc ) return -1; - split_create(&split, fname, 0, 0, true); - split_close(&split); - if (loc == 1) return 0; +s32 WBFS_FAT_RemoveGame(u8 *discid) +{ + char fname[MAX_FAT_PATH]; + int loc; + // wbfs 'partition' file + loc = WBFS_FAT_find_fname(discid, fname, sizeof(fname)); + if ( !loc ) return -1; + split_create(&split, fname, 0, 0, true); + split_close(&split); + if (loc == 1) return 0; - // game is in subdir - // remove optional .txt file - DIR_ITER *dir_iter; - struct stat st; - char path[MAX_FAT_PATH]; - char name[MAX_FAT_PATH]; - strncpy(path, fname, sizeof(path)); - char *p = strrchr(path, '/'); - if (p) *p = 0; - dir_iter = diropen(path); - if (!dir_iter) return 0; - while (dirnext(dir_iter, name, &st) == 0) { - if (name[0] == '.') continue; - if (name[6] != '_') continue; - if (strncmp(name, (char*)discid, 6) != 0) continue; - p = strrchr(name, '.'); - if (!p) continue; - if (strcasecmp(p, ".txt") != 0) continue; - snprintf(fname, sizeof(fname), "%s/%s", path, name); - remove(fname); - break; - } - dirclose(dir_iter); - // remove game subdir - unlink(path); + // game is in subdir + // remove optional .txt file + DIR_ITER *dir_iter; + struct stat st; + char path[MAX_FAT_PATH]; + char name[MAX_FAT_PATH]; + strncpy(path, fname, sizeof(path)); + char *p = strrchr(path, '/'); + if (p) *p = 0; + dir_iter = diropen(path); + if (!dir_iter) return 0; + while (dirnext(dir_iter, name, &st) == 0) { + if (name[0] == '.') continue; + if (name[6] != '_') continue; + if (strncmp(name, (char*)discid, 6) != 0) continue; + p = strrchr(name, '.'); + if (!p) continue; + if (strcasecmp(p, ".txt") != 0) continue; + snprintf(fname, sizeof(fname), "%s/%s", path, name); + remove(fname); + break; + } + dirclose(dir_iter); + // remove game subdir + unlink(path); - return 0; + return 0; } -s32 WBFS_FAT_AddGame(void) { - static struct discHdr header ATTRIBUTE_ALIGN(32); - char path[MAX_FAT_PATH]; - wbfs_t *part = NULL; - s32 ret; +s32 WBFS_FAT_AddGame(void) +{ + static struct discHdr header ATTRIBUTE_ALIGN(32); + char path[MAX_FAT_PATH]; + wbfs_t *part = NULL; + s32 ret; - // read ID from DVD - Disc_ReadHeader(&header); - // path - WBFS_FAT_get_dir(&header, path); - // create wbfs 'partition' file - part = WBFS_FAT_CreatePart(header.id, path); - if (!part) return -1; - /* Add game to device */ - partition_selector_t part_sel = ALL_PARTITIONS; - int copy_1_1 = Settings.fullcopy; - switch (Settings.partitions_to_install) { - case install_game_only: - part_sel = ONLY_GAME_PARTITION; - break; - case install_all: - part_sel = ALL_PARTITIONS; - break; - case install_all_but_update: - part_sel = REMOVE_UPDATE_PARTITION; - break; - } - if (copy_1_1) { - part_sel = ALL_PARTITIONS; - } - extern wbfs_t *hdd; - wbfs_t *old_hdd = hdd; - hdd = part; // used by spinner - ret = wbfs_add_disc(part, __WBFS_ReadDVD, NULL, WBFS_Spinner, part_sel, copy_1_1); - hdd = old_hdd; - wbfs_trim(part); - WBFS_FAT_ClosePart(part); + // read ID from DVD + Disc_ReadHeader(&header); + // path + WBFS_FAT_get_dir(&header, path); + // create wbfs 'partition' file + part = WBFS_FAT_CreatePart(header.id, path); + if (!part) return -1; + /* Add game to device */ + partition_selector_t part_sel = ALL_PARTITIONS; + int copy_1_1 = Settings.fullcopy; + switch (Settings.partitions_to_install) { + case install_game_only: + part_sel = ONLY_GAME_PARTITION; + break; + case install_all: + part_sel = ALL_PARTITIONS; + break; + case install_all_but_update: + part_sel = REMOVE_UPDATE_PARTITION; + break; + } + if (copy_1_1) { + part_sel = ALL_PARTITIONS; + } + extern wbfs_t *hdd; + wbfs_t *old_hdd = hdd; + hdd = part; // used by spinner + ret = wbfs_add_disc(part, __WBFS_ReadDVD, NULL, WBFS_Spinner, part_sel, copy_1_1); + hdd = old_hdd; + wbfs_trim(part); + WBFS_FAT_ClosePart(part); - if (ret < 0) return ret; - mk_title_txt(&header, path); + if (ret < 0) return ret; + mk_title_txt(&header, path); - return 0; + return 0; } -s32 WBFS_FAT_DVD_Size(u64 *comp_size, u64 *real_size) { - s32 ret; - u32 comp_sec = 0, last_sec = 0; +s32 WBFS_FAT_DVD_Size(u64 *comp_size, u64 *real_size) +{ + s32 ret; + u32 comp_sec = 0, last_sec = 0; - wbfs_t *part = NULL; - u64 size = (u64)143432*2*0x8000ULL; - u32 n_sector = size / fat_sector_size; - u32 wii_sec_sz; + wbfs_t *part = NULL; + u64 size = (u64)143432*2*0x8000ULL; + u32 n_sector = size / fat_sector_size; + u32 wii_sec_sz; - // init a temporary dummy part - // as a placeholder for wbfs_size_disc - part = wbfs_open_partition( - nop_read_sector, nop_write_sector, - NULL, fat_sector_size, n_sector, 0, 1); - if (!part) return -1; - wii_sec_sz = part->wii_sec_sz; + // init a temporary dummy part + // as a placeholder for wbfs_size_disc + part = wbfs_open_partition( + nop_read_sector, nop_write_sector, + NULL, fat_sector_size, n_sector, 0, 1); + if (!part) return -1; + wii_sec_sz = part->wii_sec_sz; - /* Add game to device */ - partition_selector_t part_sel; - if (Settings.partitions_to_install) { - part_sel = ALL_PARTITIONS; - } else { - part_sel = ONLY_GAME_PARTITION; - } - ret = wbfs_size_disc(part, __WBFS_ReadDVD, NULL, part_sel, &comp_sec, &last_sec); - wbfs_close(part); - if (ret < 0) - return ret; + /* Add game to device */ + partition_selector_t part_sel; + if (Settings.partitions_to_install) { + part_sel = ALL_PARTITIONS; + } else { + part_sel = ONLY_GAME_PARTITION; + } + ret = wbfs_size_disc(part, __WBFS_ReadDVD, NULL, part_sel, &comp_sec, &last_sec); + wbfs_close(part); + if (ret < 0) + return ret; - *comp_size = (u64)wii_sec_sz * comp_sec; - *real_size = (u64)wii_sec_sz * last_sec; + *comp_size = (u64)wii_sec_sz * comp_sec; + *real_size = (u64)wii_sec_sz * last_sec; - return 0; + return 0; } -s32 WBFS_FAT_RenameGame(u8 *discid, const void *newname) { - wbfs_t *part = WBFS_FAT_OpenPart((char *) discid); - if (!part) - return -1; +s32 WBFS_FAT_RenameGame(u8 *discid, const void *newname) +{ + wbfs_t *part = WBFS_FAT_OpenPart((char *) discid); + if (!part) + return -1; s32 ret = wbfs_ren_disc(part, discid,(u8*)newname); - WBFS_FAT_ClosePart(part); + WBFS_FAT_ClosePart(part); - return ret; + return ret; } -s32 WBFS_FAT_ReIDGame(u8 *discid, const void *newID) { - wbfs_t *part = WBFS_FAT_OpenPart((char *) discid); - if (!part) - return -1; +s32 WBFS_FAT_ReIDGame(u8 *discid, const void *newID) +{ + wbfs_t *part = WBFS_FAT_OpenPart((char *) discid); + if (!part) + return -1; s32 ret = wbfs_rID_disc(part, discid,(u8*)newID); - WBFS_FAT_ClosePart(part); + WBFS_FAT_ClosePart(part); - if (ret == 0) { - char fname[100]; - char fnamenew[100]; - s32 cnt = 0x31; + if(ret == 0) + { + char fname[100]; + char fnamenew[100]; + s32 cnt = 0x31; - WBFS_FAT_fname(discid, fname, sizeof(fname), NULL); - WBFS_FAT_fname((u8*) newID, fnamenew, sizeof(fnamenew), NULL); + WBFS_FAT_fname(discid, fname, sizeof(fname), NULL); + WBFS_FAT_fname((u8*) newID, fnamenew, sizeof(fnamenew), NULL); - int stringlength = strlen(fname); + int stringlength = strlen(fname); - while (rename(fname, fnamenew) == 0) { - fname[stringlength] = cnt; - fname[stringlength+1] = 0; - fnamenew[stringlength] = cnt; - fnamenew[stringlength+1] = 0; - cnt++; - } - } + while(rename(fname, fnamenew) == 0) + { + fname[stringlength] = cnt; + fname[stringlength+1] = 0; + fnamenew[stringlength] = cnt; + fnamenew[stringlength+1] = 0; + cnt++; + } + } - return ret; + return ret; } s32 WBFS_FAT_EstimateGameSize(void) { - wbfs_t *part = NULL; - u64 size = (u64)143432*2*0x8000ULL; - u32 n_sector = size / fat_sector_size; - u32 wii_sec_sz; + wbfs_t *part = NULL; + u64 size = (u64)143432*2*0x8000ULL; + u32 n_sector = size / fat_sector_size; + u32 wii_sec_sz; - // init a temporary dummy part - // as a placeholder for wbfs_size_disc - part = wbfs_open_partition( - nop_read_sector, nop_write_sector, - NULL, fat_sector_size, n_sector, 0, 1); - if (!part) return -1; - wii_sec_sz = part->wii_sec_sz; + // init a temporary dummy part + // as a placeholder for wbfs_size_disc + part = wbfs_open_partition( + nop_read_sector, nop_write_sector, + NULL, fat_sector_size, n_sector, 0, 1); + if (!part) return -1; + wii_sec_sz = part->wii_sec_sz; - partition_selector_t part_sel; - if (Settings.fullcopy) { - part_sel = ALL_PARTITIONS; - } else { - part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; - } + partition_selector_t part_sel; + if (Settings.fullcopy) { + part_sel = ALL_PARTITIONS; + } else { + part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; + } return wbfs_estimate_disc(part, __WBFS_ReadDVD, NULL, part_sel); } diff --git a/source/usbloader/wdvd.c b/source/usbloader/wdvd.c index 619d93de..2143ad79 100644 --- a/source/usbloader/wdvd.c +++ b/source/usbloader/wdvd.c @@ -118,10 +118,7 @@ s32 WDVD_Seek(u64 offset) { s32 WDVD_Offset(u64 offset) { //u32 *off = (u32 *)((void *)&offset); - union { u64 off64; - u32 off32[2]; - } off; - off.off64 = offset; + union { u64 off64; u32 off32[2]; } off;off.off64 = offset; s32 ret; memset(inbuf, 0, sizeof(inbuf)); @@ -322,9 +319,9 @@ s32 WDVD_SetUSBMode(const u8 *id, s32 partition) { /* Copy ID */ if (id) { memcpy(&inbuf[2], id, 6); - if (IOS_GetVersion() != 249) { - inbuf[5] = partition; - } + if (IOS_GetVersion() != 249) { + inbuf[5] = partition; + } } ret = IOS_Ioctl(di_fd, IOCTL_DI_SETUSBMODE, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); @@ -341,18 +338,19 @@ s32 WDVD_SetUSBMode(const u8 *id, s32 partition) { return (ret == 1) ? 0 : -ret; } -s32 WDVD_Read_Disc_BCA(void *buf) { - s32 ret; +s32 WDVD_Read_Disc_BCA(void *buf) +{ + s32 ret; - memset(inbuf, 0, sizeof(inbuf)); + memset(inbuf, 0, sizeof(inbuf)); - /* Disc read */ - inbuf[0] = IOCTL_DI_DISC_BCA << 24; - //inbuf[1] = 64; + /* Disc read */ + inbuf[0] = IOCTL_DI_DISC_BCA << 24; + //inbuf[1] = 64; - ret = IOS_Ioctl(di_fd, IOCTL_DI_DISC_BCA, inbuf, sizeof(inbuf), buf, 64); - if (ret < 0) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_DISC_BCA, inbuf, sizeof(inbuf), buf, 64); + if (ret < 0) + return ret; - return (ret == 1) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } diff --git a/source/usbloader/wdvd.h b/source/usbloader/wdvd.h index 61588bce..0f7848ff 100644 --- a/source/usbloader/wdvd.h +++ b/source/usbloader/wdvd.h @@ -1,16 +1,16 @@ #ifndef _WDVD_H_ -#define _WDVD_H_ +#define _WDVD_H_ #ifdef __cplusplus extern "C" { #endif /* Prototypes */ - s32 WDVD_Init(void); - s32 WDVD_Close(void); - s32 WDVD_GetHandle(void); - s32 WDVD_Reset(void); - s32 WDVD_ReadDiskId(void *); + s32 WDVD_Init(void); + s32 WDVD_Close(void); + s32 WDVD_GetHandle(void); + s32 WDVD_Reset(void); + s32 WDVD_ReadDiskId(void *); s32 WDVD_Seek(u64); s32 WDVD_Offset(u64); s32 WDVD_StopLaser(void); @@ -22,8 +22,8 @@ extern "C" { s32 WDVD_WaitForDisc(void); s32 WDVD_GetCoverStatus(u32 *); s32 WDVD_DisableReset(u8); - s32 WDVD_SetUSBMode(const u8 *, s32 partition); - s32 WDVD_Read_Disc_BCA(void *buf); + s32 WDVD_SetUSBMode(const u8 *, s32 partition); + s32 WDVD_Read_Disc_BCA(void *buf); #ifdef __cplusplus } diff --git a/source/video.cpp b/source/video.cpp index c514c396..c82226cc 100644 --- a/source/video.cpp +++ b/source/video.cpp @@ -202,7 +202,7 @@ static unsigned int *xfbDB = NULL; void InitVideodebug () { VIDEO_Init(); - GXRModeObj *vmode = VIDEO_GetPreferredMode(NULL); // get default video mode + GXRModeObj *vmode = VIDEO_GetPreferredMode(NULL); // get default video mode // widescreen fix VIDEO_Configure (vmode); @@ -221,7 +221,7 @@ void InitVideodebug () { VIDEO_Flush (); VIDEO_WaitVSync (); if (vmode->viTVMode & VI_NON_INTERLACE) - VIDEO_WaitVSync (); + VIDEO_WaitVSync (); } /**************************************************************************** * StopGX @@ -490,11 +490,12 @@ void Menu_DrawTPLImg(f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, GXTexO * * Copies the current screen into a file "path" ***************************************************************************/ -s32 TakeScreenshot(const char *path) { +s32 TakeScreenshot(const char *path) +{ gprintf("\nTakeScreenshot(%s)", path); IMGCTX ctx = PNGU_SelectImageFromDevice (path); s32 ret = PNGU_EncodeFromYCbYCr(ctx,vmode->fbWidth, vmode->efbHeight,xfb[whichfb],0); PNGU_ReleaseImageContext (ctx); gprintf(":%d", ret); - return 1; + return 1; } diff --git a/source/wad/isfs.c b/source/wad/isfs.c index cde76ee8..1f676c00 100644 --- a/source/wad/isfs.c +++ b/source/wad/isfs.c @@ -153,9 +153,9 @@ static int _ISFS_open_r(struct _reent *r, void *fileStruct, const char *path, in omode |= ISFS_OPEN_RW; if (mode & O_CREAT) { - int user = 0; + int user = 0; int group = 0; - int other = 0; + int other = 0; if (flags & S_IRUSR) user |= ISFS_OPEN_READ; @@ -241,7 +241,7 @@ static int _ISFS_read_r(struct _reent *r, int fd, char *ptr, size_t len) { } else if (ret < len) { r->_errno = EOVERFLOW; } - + memcpy(ptr, rw_buffer, ret); return ret; } diff --git a/source/wad/isfs.h b/source/wad/isfs.h index a7bf982e..2a509197 100644 --- a/source/wad/isfs.h +++ b/source/wad/isfs.h @@ -34,4 +34,4 @@ bool ISFS_Mount(); bool ISFS_Unmount(); #endif /* _LIBISFS_H_ */ - + diff --git a/source/wad/title.c b/source/wad/title.c index a2eeb1d9..0d5de338 100644 --- a/source/wad/title.c +++ b/source/wad/title.c @@ -326,116 +326,121 @@ s32 Uninstall_DeleteTicket(u32 title_u, u32 title_l) { //////savegame shit, from waninkoko. modified for use in this project /* Savegame structure */ struct savegame { - /* Title name */ - char name[65]; + /* Title name */ + char name[65]; - /* Title ID */ - u64 tid; + /* Title ID */ + u64 tid; }; -s32 Savegame_CheckTitle(const char *path) { - FILE *fp = NULL; +s32 Savegame_CheckTitle(const char *path) +{ + FILE *fp = NULL; - char filepath[128]; + char filepath[128]; - /* Generate filepath */ - sprintf(filepath, "%s/banner.bin", path); + /* Generate filepath */ + sprintf(filepath, "%s/banner.bin", path); - /* Try to open banner */ - fp = fopen(filepath, "rb"); - if (!fp) - return -1; + /* Try to open banner */ + fp = fopen(filepath, "rb"); + if (!fp) + return -1; - /* Close file */ - fclose(fp); + /* Close file */ + fclose(fp); - return 0; + return 0; } -s32 Savegame_GetNandPath(u64 tid, char *outbuf) { - s32 ret; - char buffer[1024] ATTRIBUTE_ALIGN(32); +s32 Savegame_GetNandPath(u64 tid, char *outbuf) +{ + s32 ret; + char buffer[1024] ATTRIBUTE_ALIGN(32); - /* Get data directory */ - ret = ES_GetDataDir(tid, buffer); - if (ret < 0) - return ret; + /* Get data directory */ + ret = ES_GetDataDir(tid, buffer); + if (ret < 0) + return ret; - /* Generate NAND directory */ - sprintf(outbuf, "isfs:%s", buffer); + /* Generate NAND directory */ + sprintf(outbuf, "isfs:%s", buffer); - return 0; + return 0; } -s32 __Menu_GetNandSaves(struct savegame **outbuf, u32 *outlen) { - struct savegame *buffer = NULL; +s32 __Menu_GetNandSaves(struct savegame **outbuf, u32 *outlen) +{ + struct savegame *buffer = NULL; - u64 *titleList = NULL; - u32 titleCnt; + u64 *titleList = NULL; + u32 titleCnt; - u32 cnt, idx; - s32 ret; + u32 cnt, idx; + s32 ret; - /* Get title list */ - ret = Title_GetList(&titleList, &titleCnt); - if (ret < 0) - return ret; + /* Get title list */ + ret = Title_GetList(&titleList, &titleCnt); + if (ret < 0) + return ret; - /* Allocate memory */ - buffer = malloc(sizeof(struct savegame) * titleCnt); - if (!buffer) { - ret = -1; - goto out; - } + /* Allocate memory */ + buffer = malloc(sizeof(struct savegame) * titleCnt); + if (!buffer) { + ret = -1; + goto out; + } - /* Copy titles */ - for (cnt = idx = 0; idx < titleCnt; idx++) { - u64 tid = titleList[idx]; - char savepath[128]; + /* Copy titles */ + for (cnt = idx = 0; idx < titleCnt; idx++) { + u64 tid = titleList[idx]; + char savepath[128]; - /* Generate dirpath */ - Savegame_GetNandPath(tid, savepath); + /* Generate dirpath */ + Savegame_GetNandPath(tid, savepath); - /* Check for title savegame */ - ret = Savegame_CheckTitle(savepath); - if (!ret) { - struct savegame *save = &buffer[cnt++]; + /* Check for title savegame */ + ret = Savegame_CheckTitle(savepath); + if (!ret) { + struct savegame *save = &buffer[cnt++]; - /* Set title ID */ - save->tid = tid; - } - } + /* Set title ID */ + save->tid = tid; + } + } - /* Set values */ - *outbuf = buffer; - *outlen = cnt; + /* Set values */ + *outbuf = buffer; + *outlen = cnt; - /* Success */ - ret = 0; + /* Success */ + ret = 0; out: - /* Free memory */ - if (titleList) - free(titleList); + /* Free memory */ + if (titleList) + free(titleList); - return ret; + return ret; } -s32 __Menu_EntryCmp(const void *p1, const void *p2) { - struct savegame *s1 = (struct savegame *)p1; - struct savegame *s2 = (struct savegame *)p2; +s32 __Menu_EntryCmp(const void *p1, const void *p2) +{ + struct savegame *s1 = (struct savegame *)p1; + struct savegame *s2 = (struct savegame *)p2; - /* Compare entries */ - return strcmp(s1->name, s2->name); + /* Compare entries */ + return strcmp(s1->name, s2->name); } -s32 __Menu_RetrieveList(struct savegame **outbuf, u32 *outlen) { - s32 ret; - ret = __Menu_GetNandSaves(outbuf, outlen); - if (ret >= 0) - qsort(*outbuf, *outlen, sizeof(struct savegame), __Menu_EntryCmp); +s32 __Menu_RetrieveList(struct savegame **outbuf, u32 *outlen) +{ + s32 ret; + ret = __Menu_GetNandSaves(outbuf, outlen); + if (ret >= 0) + qsort(*outbuf, *outlen, sizeof(struct savegame), __Menu_EntryCmp); - return ret; + return ret; } //carefull when using this function @@ -709,31 +714,33 @@ char *titleText(u32 kind, u32 title) { //giantpune's magic function to check for game saves //give a ID4 of a game and returns 1 if the game has save data, 0 if not, or <0 for errors -int CheckForSave(const char *gameID) { +int CheckForSave(const char *gameID) +{ - if (ISFS_Initialize()<0) - return -1; + if (ISFS_Initialize()<0) + return -1; + + if (!ISFS_Mount()) + return -2; + + struct savegame *saveList = NULL; + u32 saveCnt; + u32 cnt; + + + if (__Menu_RetrieveList(&saveList, &saveCnt)<0) + return -3; - if (!ISFS_Mount()) - return -2; - - struct savegame *saveList = NULL; - u32 saveCnt; - u32 cnt; - - - if (__Menu_RetrieveList(&saveList, &saveCnt)<0) - return -3; - - for (cnt=0;cnttid >> 32),(u32)(save->tid & 0xFFFFFFFF)))==0) { - free(saveList); - return 1; - } - } - free(saveList); - return 0; + for (cnt=0;cnttid >> 32),(u32)(save->tid & 0xFFFFFFFF)))==0) { + free(saveList); + return 1; + } + } + free(saveList); + return 0; } @@ -817,118 +824,126 @@ s32 getTitles_Type(u32 type, u32 *titles, u32 count) { //this function expects initialize be called before it is called // if not, it will fail miserably and catch the wii on fire and kick you in the nuts #define TITLE_ID(x,y) (((u64)(x) << 32) | (y)) -s32 WII_BootHBC() { - u32 tmdsize; - u64 tid = 0; - u64 *list; - u32 titlecount; - s32 ret; - u32 i; +s32 WII_BootHBC() +{ + u32 tmdsize; + u64 tid = 0; + u64 *list; + u32 titlecount; + s32 ret; + u32 i; - ret = ES_GetNumTitles(&titlecount); - if (ret < 0) - return WII_EINTERNAL; + ret = ES_GetNumTitles(&titlecount); + if(ret < 0) + return WII_EINTERNAL; - list = memalign(32, titlecount * sizeof(u64) + 32); + list = memalign(32, titlecount * sizeof(u64) + 32); - ret = ES_GetTitles(list, titlecount); - if (ret < 0) { - free(list); - return WII_EINTERNAL; - } + ret = ES_GetTitles(list, titlecount); + if(ret < 0) { + free(list); + return WII_EINTERNAL; + } + + for(i=0; ititle_version<255) { - ret = tmd->title_version; - } + if(!tid) + { + ret = WII_EINSTALL; + goto out; + } + if(ES_GetStoredTMDSize(tid, &tmdsize) < 0) + { + ret = WII_EINSTALL; + goto out; + } + + tmd *tmd = getTMD(tid); + + if(tmd->title_version<255) + { + ret = tmd->title_version; + } + out: - gprintf(" = %d",ret); - return ret; + gprintf(" = %d",ret); + return ret; } diff --git a/source/wad/title.h b/source/wad/title.h index e47f1502..7086e34a 100644 --- a/source/wad/title.h +++ b/source/wad/title.h @@ -62,13 +62,13 @@ extern "C" { s32 Uninstall_FromTitle(const u64 tid); //check for a game save present on nand based on game ID - int CheckForSave(const char *gameID); +int CheckForSave(const char *gameID); //boot HBC in either HAXX or JODI locations - s32 WII_BootHBC(); +s32 WII_BootHBC(); //get the rev of a ISO and such without having to load it - s32 getIOSrev(u64 req); +s32 getIOSrev(u64 req); #ifdef __cplusplus } diff --git a/source/wad/wad.cpp b/source/wad/wad.cpp index a51e7ff2..56f353ed 100644 --- a/source/wad/wad.cpp +++ b/source/wad/wad.cpp @@ -26,627 +26,624 @@ extern GuiWindow * mainWindow; /* 'WAD Header' structure */ typedef struct { - /* Header length */ - u32 header_len; + /* Header length */ + u32 header_len; - /* WAD type */ - u16 type; + /* WAD type */ + u16 type; - u16 padding; + u16 padding; - /* Data length */ - u32 certs_len; - u32 crl_len; - u32 tik_len; - u32 tmd_len; - u32 data_len; - u32 footer_len; + /* Data length */ + u32 certs_len; + u32 crl_len; + u32 tik_len; + u32 tmd_len; + u32 data_len; + u32 footer_len; } ATTRIBUTE_PACKED wadHeader; /* Variables */ static u8 wadBuffer[BLOCK_SIZE] ATTRIBUTE_ALIGN(32); -s32 __Wad_ReadFile(FILE *fp, void *outbuf, u32 offset, u32 len) { - s32 ret; +s32 __Wad_ReadFile(FILE *fp, void *outbuf, u32 offset, u32 len) +{ + s32 ret; - /* Seek to offset */ - fseek(fp, offset, SEEK_SET); + /* Seek to offset */ + fseek(fp, offset, SEEK_SET); - /* Read data */ - ret = fread(outbuf, len, 1, fp); - if (ret < 0) - return ret; + /* Read data */ + ret = fread(outbuf, len, 1, fp); + if (ret < 0) + return ret; - return 0; + return 0; } -s32 __Wad_ReadAlloc(FILE *fp, void **outbuf, u32 offset, u32 len) { - void *buffer = NULL; - s32 ret; +s32 __Wad_ReadAlloc(FILE *fp, void **outbuf, u32 offset, u32 len) +{ + void *buffer = NULL; + s32 ret; - /* Allocate memory */ - buffer = memalign(32, len); - if (!buffer) - return -1; + /* Allocate memory */ + buffer = memalign(32, len); + if (!buffer) + return -1; - /* Read file */ - ret = __Wad_ReadFile(fp, buffer, offset, len); - if (ret < 0) { - free(buffer); - return ret; - } + /* Read file */ + ret = __Wad_ReadFile(fp, buffer, offset, len); + if (ret < 0) { + free(buffer); + return ret; + } - /* Set pointer */ - *outbuf = buffer; - return 0; + /* Set pointer */ + *outbuf = buffer; + return 0; } -s32 __Wad_GetTitleID(FILE *fp, wadHeader *header, u64 *tid) { - //signed_blob *p_tik = NULL; - void *p_tik = NULL; - tik *tik_data = NULL; +s32 __Wad_GetTitleID(FILE *fp, wadHeader *header, u64 *tid) +{ + //signed_blob *p_tik = NULL; + void *p_tik = NULL; + tik *tik_data = NULL; - u32 offset = 0; - s32 ret; + u32 offset = 0; + s32 ret; - /* Ticket offset */ - offset += round_up(header->header_len, 64); - offset += round_up(header->certs_len, 64); - offset += round_up(header->crl_len, 64); + /* Ticket offset */ + offset += round_up(header->header_len, 64); + offset += round_up(header->certs_len, 64); + offset += round_up(header->crl_len, 64); - /* Read ticket */ - ret = __Wad_ReadAlloc(fp, &p_tik, offset, header->tik_len); - if (ret < 0) - goto out; + /* Read ticket */ + ret = __Wad_ReadAlloc(fp, &p_tik, offset, header->tik_len); + if (ret < 0) + goto out; - /* Ticket data */ - tik_data = (tik *)SIGNATURE_PAYLOAD((signed_blob *)p_tik); + /* Ticket data */ + tik_data = (tik *)SIGNATURE_PAYLOAD((signed_blob *)p_tik); - /* Copy title ID */ - *tid = tik_data->titleid; + /* Copy title ID */ + *tid = tik_data->titleid; out: - /* Free memory */ - if (p_tik) - free(p_tik); + /* Free memory */ + if (p_tik) + free(p_tik); - return ret; + return ret; } -s32 Wad_Install(FILE *fp) { - //////start the gui shit - GuiWindow promptWindow(472,320); - promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - promptWindow.SetPosition(0, -10); +s32 Wad_Install(FILE *fp) +{ + //////start the gui shit + GuiWindow promptWindow(472,320); + promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + promptWindow.SetPosition(0, -10); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + char imgPath[100]; + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); + GuiTrigger trigA; + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); - } + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes){ + dialogBoxImg.SetWidescreen(CFG.widescreen);} - GuiText btn1Txt(tr("OK"), 22, THEME.prompttext); - GuiImage btn1Img(&btnOutline); - if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); - } - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -35, &trigA, &btnSoundOver, btnClick2,1); - btn1.SetLabel(&btn1Txt); - btn1.SetState(STATE_SELECTED); + GuiText btn1Txt(tr("OK"), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes){ + btn1Txt.SetWidescreen(CFG.widescreen); + btn1Img.SetWidescreen(CFG.widescreen);} + GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -35, &trigA, &btnSoundOver, btnClick2,1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path); - GuiImageData progressbarOutline(imgPath, progressbar_outline_png); - GuiImage progressbarOutlineImg(&progressbarOutline); - if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen(CFG.widescreen); - } - progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarOutlineImg.SetPosition(25, 50); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path); + GuiImageData progressbarOutline(imgPath, progressbar_outline_png); + GuiImage progressbarOutlineImg(&progressbarOutline); + if (Settings.wsprompt == yes){ + progressbarOutlineImg.SetWidescreen(CFG.widescreen);} + progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(25, 50); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", CFG.theme_path); - GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); - GuiImage progressbarEmptyImg(&progressbarEmpty); - progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarEmptyImg.SetPosition(25, 50); - progressbarEmptyImg.SetTile(100); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", CFG.theme_path); + GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); + GuiImage progressbarEmptyImg(&progressbarEmpty); + progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarEmptyImg.SetPosition(25, 50); + progressbarEmptyImg.SetTile(100); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", CFG.theme_path); - GuiImageData progressbar(imgPath, progressbar_png); - GuiImage progressbarImg(&progressbar); - progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarImg.SetPosition(25, 50); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", CFG.theme_path); + GuiImageData progressbar(imgPath, progressbar_png); + GuiImage progressbarImg(&progressbar); + progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarImg.SetPosition(25, 50); char title[50]; - sprintf(title, "%s", tr("Installing wad")); - GuiText titleTxt(title, 26, THEME.prompttext); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetPosition(0,40); + sprintf(title, "%s", tr("Installing wad")); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0,40); char msg[50]; sprintf(msg, " "); - // sprintf(msg, "%s", tr("Initializing Network")); - GuiText msg1Txt(NULL, 20, THEME.prompttext); - msg1Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg1Txt.SetPosition(50,75); + // sprintf(msg, "%s", tr("Initializing Network")); + GuiText msg1Txt(NULL, 20, THEME.prompttext); + msg1Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg1Txt.SetPosition(50,75); // char msg2[50] = " "; - GuiText msg2Txt(NULL, 20, THEME.prompttext); - msg2Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg2Txt.SetPosition(50, 98); + GuiText msg2Txt(NULL, 20, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg2Txt.SetPosition(50, 98); - GuiText msg3Txt(NULL, 20, THEME.prompttext); - msg3Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg3Txt.SetPosition(50, 121); + GuiText msg3Txt(NULL, 20, THEME.prompttext); + msg3Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg3Txt.SetPosition(50, 121); - GuiText msg4Txt(NULL, 20, THEME.prompttext); - msg4Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg4Txt.SetPosition(50, 144); + GuiText msg4Txt(NULL, 20, THEME.prompttext); + msg4Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg4Txt.SetPosition(50, 144); - GuiText msg5Txt(NULL, 20, THEME.prompttext); - msg5Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg5Txt.SetPosition(50, 167); + GuiText msg5Txt(NULL, 20, THEME.prompttext); + msg5Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg5Txt.SetPosition(50, 167); - GuiText prTxt(NULL, 26, THEME.prompttext); - prTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - prTxt.SetPosition(0, 50); + GuiText prTxt(NULL, 26, THEME.prompttext); + prTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + prTxt.SetPosition(0, 50); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) {/////////////adjust for widescreen - progressbarOutlineImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - progressbarOutlineImg.SetPosition(0, 50); - progressbarEmptyImg.SetPosition(80,50); - progressbarEmptyImg.SetTile(78); - progressbarImg.SetPosition(80, 50); + if ((Settings.wsprompt == yes) && (CFG.widescreen)){/////////////adjust for widescreen + progressbarOutlineImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(0, 50); + progressbarEmptyImg.SetPosition(80,50); + progressbarEmptyImg.SetTile(78); + progressbarImg.SetPosition(80, 50); - msg1Txt.SetPosition(90,75); - msg2Txt.SetPosition(90, 98); - msg3Txt.SetPosition(90, 121); - msg4Txt.SetPosition(90, 144); - msg5Txt.SetPosition(90, 167); + msg1Txt.SetPosition(90,75); + msg2Txt.SetPosition(90, 98); + msg3Txt.SetPosition(90, 121); + msg4Txt.SetPosition(90, 144); + msg5Txt.SetPosition(90, 167); - } - promptWindow.Append(&dialogBoxImg); - promptWindow.Append(&titleTxt); - promptWindow.Append(&msg5Txt); - promptWindow.Append(&msg4Txt); - promptWindow.Append(&msg3Txt); - promptWindow.Append(&msg1Txt); - promptWindow.Append(&msg2Txt); + } + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msg5Txt); + promptWindow.Append(&msg4Txt); + promptWindow.Append(&msg3Txt); + promptWindow.Append(&msg1Txt); + promptWindow.Append(&msg2Txt); - //promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); + //promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); - HaltGui(); - mainWindow->SetState(STATE_DISABLED); - mainWindow->Append(&promptWindow); - mainWindow->ChangeFocus(&promptWindow); - //sleep(1); + HaltGui(); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); + //sleep(1); - ///start the wad shit - bool fail = false; - wadHeader *header = NULL; - void *pvoid; - signed_blob *p_certs = NULL, *p_crl = NULL, *p_tik = NULL, *p_tmd = NULL; + ///start the wad shit + bool fail = false; + wadHeader *header = NULL; + void *pvoid; + signed_blob *p_certs = NULL, *p_crl = NULL, *p_tik = NULL, *p_tmd = NULL; - tmd *tmd_data = NULL; + tmd *tmd_data = NULL; - u32 cnt, offset = 0; - s32 ret = 666; + u32 cnt, offset = 0; + s32 ret = 666; - ResumeGui(); - msg1Txt.SetText(tr(">> Reading WAD data...")); - HaltGui(); + ResumeGui(); + msg1Txt.SetText(tr(">> Reading WAD data...")); + HaltGui(); #define SetPointer(a, p) a=(typeof(a))p - // WAD header - //ret = __Wad_ReadAlloc(fp, (void *)header, offset, sizeof(wadHeader)); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, sizeof(wadHeader)); + // WAD header + //ret = __Wad_ReadAlloc(fp, (void *)header, offset, sizeof(wadHeader)); + ret = __Wad_ReadAlloc(fp, &pvoid, offset, sizeof(wadHeader)); - if (ret < 0) - goto err; - SetPointer(header, pvoid); - offset += round_up(header->header_len, 64); + if (ret < 0) + goto err; + SetPointer(header, pvoid); + offset += round_up(header->header_len, 64); - // WAD certificates - //ret = __Wad_ReadAlloc(fp, (void *)&p_certs, offset, header->certs_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->certs_len); - if (ret < 0) - goto err; - SetPointer(p_certs, pvoid); - offset += round_up(header->certs_len, 64); + // WAD certificates + //ret = __Wad_ReadAlloc(fp, (void *)&p_certs, offset, header->certs_len); + ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->certs_len); + if (ret < 0) + goto err; + SetPointer(p_certs, pvoid); + offset += round_up(header->certs_len, 64); - // WAD crl + // WAD crl - if (header->crl_len) { - //ret = __Wad_ReadAlloc(fp, (void *)&p_crl, offset, header->crl_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->crl_len); - if (ret < 0) - goto err; - SetPointer(p_crl, pvoid); - offset += round_up(header->crl_len, 64); - } + if (header->crl_len) { + //ret = __Wad_ReadAlloc(fp, (void *)&p_crl, offset, header->crl_len); + ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->crl_len); + if (ret < 0) + goto err; + SetPointer(p_crl, pvoid); + offset += round_up(header->crl_len, 64); + } - // WAD ticket - //ret = __Wad_ReadAlloc(fp, (void *)&p_tik, offset, header->tik_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tik_len); - if (ret < 0) - goto err; - SetPointer(p_tik, pvoid); - offset += round_up(header->tik_len, 64); + // WAD ticket + //ret = __Wad_ReadAlloc(fp, (void *)&p_tik, offset, header->tik_len); + ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tik_len); + if (ret < 0) + goto err; + SetPointer(p_tik, pvoid); + offset += round_up(header->tik_len, 64); - // WAD TMD - //ret = __Wad_ReadAlloc(fp, (void *)&p_tmd, offset, header->tmd_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tmd_len); - if (ret < 0) - goto err; - SetPointer(p_tmd, pvoid); - offset += round_up(header->tmd_len, 64); + // WAD TMD + //ret = __Wad_ReadAlloc(fp, (void *)&p_tmd, offset, header->tmd_len); + ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tmd_len); + if (ret < 0) + goto err; + SetPointer(p_tmd, pvoid); + offset += round_up(header->tmd_len, 64); - ResumeGui(); - msg1Txt.SetText(tr("Reading WAD data... Ok!")); - msg2Txt.SetText(tr(">> Installing ticket...")); - HaltGui(); - // Install ticket - ret = ES_AddTicket(p_tik, header->tik_len, p_certs, header->certs_len, p_crl, header->crl_len); - if (ret < 0) - goto err; + ResumeGui(); + msg1Txt.SetText(tr("Reading WAD data... Ok!")); + msg2Txt.SetText(tr(">> Installing ticket...")); + HaltGui(); + // Install ticket + ret = ES_AddTicket(p_tik, header->tik_len, p_certs, header->certs_len, p_crl, header->crl_len); + if (ret < 0) + goto err; - ResumeGui(); - msg2Txt.SetText(tr("Installing ticket... Ok!")); - msg3Txt.SetText(tr(">> Installing title...")); - //WindowPrompt(">> Installing title...",0,0,0,0,0,200); - HaltGui(); - // Install title - ret = ES_AddTitleStart(p_tmd, header->tmd_len, p_certs, header->certs_len, p_crl, header->crl_len); - if (ret < 0) - goto err; + ResumeGui(); + msg2Txt.SetText(tr("Installing ticket... Ok!")); + msg3Txt.SetText(tr(">> Installing title...")); + //WindowPrompt(">> Installing title...",0,0,0,0,0,200); + HaltGui(); + // Install title + ret = ES_AddTitleStart(p_tmd, header->tmd_len, p_certs, header->certs_len, p_crl, header->crl_len); + if (ret < 0) + goto err; - // Get TMD info - tmd_data = (tmd *)SIGNATURE_PAYLOAD(p_tmd); + // Get TMD info + tmd_data = (tmd *)SIGNATURE_PAYLOAD(p_tmd); - // Install contents - //ResumeGui(); - //HaltGui(); - promptWindow.Append(&progressbarEmptyImg); - promptWindow.Append(&progressbarImg); - promptWindow.Append(&progressbarOutlineImg); - promptWindow.Append(&prTxt); - ResumeGui(); - msg3Txt.SetText(tr("Installing title... Ok!")); - for (cnt = 0; cnt < tmd_data->num_contents; cnt++) { + // Install contents + //ResumeGui(); + //HaltGui(); + promptWindow.Append(&progressbarEmptyImg); + promptWindow.Append(&progressbarImg); + promptWindow.Append(&progressbarOutlineImg); + promptWindow.Append(&prTxt); + ResumeGui(); + msg3Txt.SetText(tr("Installing title... Ok!")); + for (cnt = 0; cnt < tmd_data->num_contents; cnt++) { - tmd_content *content = &tmd_data->contents[cnt]; + tmd_content *content = &tmd_data->contents[cnt]; - u32 idx = 0, len; - s32 cfd; - ResumeGui(); + u32 idx = 0, len; + s32 cfd; + ResumeGui(); - //printf("\r\t\t>> Installing content #%02d...", content->cid); - // Encrypted content size - len = round_up(content->size, 64); + //printf("\r\t\t>> Installing content #%02d...", content->cid); + // Encrypted content size + len = round_up(content->size, 64); - // Install content - cfd = ES_AddContentStart(tmd_data->title_id, content->cid); - if (cfd < 0) { - ret = cfd; - goto err; - } - snprintf(imgPath, sizeof(imgPath), "%s%d...",tr(">> Installing content #"),content->cid); - msg4Txt.SetText(imgPath); - // Install content data - while (idx < len) { + // Install content + cfd = ES_AddContentStart(tmd_data->title_id, content->cid); + if (cfd < 0) { + ret = cfd; + goto err; + } + snprintf(imgPath, sizeof(imgPath), "%s%d...",tr(">> Installing content #"),content->cid); + msg4Txt.SetText(imgPath); + // Install content data + while (idx < len) { + + //VIDEO_WaitVSync (); - //VIDEO_WaitVSync (); + u32 size; - u32 size; + // Data length + size = (len - idx); + if (size > BLOCK_SIZE) + size = BLOCK_SIZE; - // Data length - size = (len - idx); - if (size > BLOCK_SIZE) - size = BLOCK_SIZE; + // Read data + ret = __Wad_ReadFile(fp, &wadBuffer, offset, size); + if (ret < 0) + goto err; - // Read data - ret = __Wad_ReadFile(fp, &wadBuffer, offset, size); - if (ret < 0) - goto err; + // Install data + ret = ES_AddContentData(cfd, wadBuffer, size); + if (ret < 0) + goto err; - // Install data - ret = ES_AddContentData(cfd, wadBuffer, size); - if (ret < 0) - goto err; + // Increase variables + idx += size; + offset += size; + + //snprintf(imgPath, sizeof(imgPath), "%s%d (%d)...",tr(">> Installing content #"),content->cid,idx); - // Increase variables - idx += size; - offset += size; + //msg4Txt.SetText(imgPath); - //snprintf(imgPath, sizeof(imgPath), "%s%d (%d)...",tr(">> Installing content #"),content->cid,idx); + prTxt.SetTextf("%i%%", 100*(cnt*len+idx)/(tmd_data->num_contents*len)); + if ((Settings.wsprompt == yes) && (CFG.widescreen)) { + progressbarImg.SetTile(78*(cnt*len+idx)/(tmd_data->num_contents*len)); + } else { + progressbarImg.SetTile(100*(cnt*len+idx)/(tmd_data->num_contents*len)); + } - //msg4Txt.SetText(imgPath); + } - prTxt.SetTextf("%i%%", 100*(cnt*len+idx)/(tmd_data->num_contents*len)); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) { - progressbarImg.SetTile(78*(cnt*len+idx)/(tmd_data->num_contents*len)); - } else { - progressbarImg.SetTile(100*(cnt*len+idx)/(tmd_data->num_contents*len)); - } + // Finish content installation + ret = ES_AddContentFinish(cfd); + if (ret < 0) + goto err; + } - } - - // Finish content installation - ret = ES_AddContentFinish(cfd); - if (ret < 0) - goto err; - } - - msg4Txt.SetText(tr("Installing content... Ok!")); - msg5Txt.SetText(tr(">> Finishing installation...")); + msg4Txt.SetText(tr("Installing content... Ok!")); + msg5Txt.SetText(tr(">> Finishing installation...")); - // Finish title install - ret = ES_AddTitleFinish(); - if (ret >= 0) { + // Finish title install + ret = ES_AddTitleFinish(); + if (ret >= 0) { // printf(" OK!\n"); - goto out; - } + goto out; + } err: - //char titties[100]; - ResumeGui(); - prTxt.SetTextf("%s%d", tr("Error..."),ret); - promptWindow.Append(&prTxt); - fail = true; - //snprintf(titties, sizeof(titties), "%d", ret); - //printf(" ERROR! (ret = %d)\n", ret); - //WindowPrompt("ERROR!",titties,"Back",0,0); - // Cancel install - ES_AddTitleCancel(); - goto exit; - //return ret; + //char titties[100]; + ResumeGui(); + prTxt.SetTextf("%s%d", tr("Error..."),ret); + promptWindow.Append(&prTxt); + fail = true; + //snprintf(titties, sizeof(titties), "%d", ret); + //printf(" ERROR! (ret = %d)\n", ret); + //WindowPrompt("ERROR!",titties,"Back",0,0); + // Cancel install + ES_AddTitleCancel(); + goto exit; + //return ret; out: - // Free memory - if (header) - free(header); - if (p_certs) - free(p_certs); - if (p_crl) - free(p_crl); - if (p_tik) - free(p_tik); - if (p_tmd) - free(p_tmd); - goto exit; + // Free memory + if (header) + free(header); + if (p_certs) + free(p_certs); + if (p_crl) + free(p_crl); + if (p_tik) + free(p_tik); + if (p_tmd) + free(p_tmd); + goto exit; exit: - if (!fail)msg5Txt.SetText(tr("Finishing installation... Ok!")); - promptWindow.Append(&btn1); - while (btn1.GetState() != STATE_CLICKED) { - } + if (!fail)msg5Txt.SetText(tr("Finishing installation... Ok!")); + promptWindow.Append(&btn1); + while(btn1.GetState() != STATE_CLICKED){ + } - HaltGui(); - mainWindow->Remove(&promptWindow); - mainWindow->SetState(STATE_DEFAULT); - ResumeGui(); + HaltGui(); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); + ResumeGui(); - return ret; + return ret; } -s32 Wad_Uninstall(FILE *fp) { - //////start the gui shit - GuiWindow promptWindow(472,320); - promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - promptWindow.SetPosition(0, -10); +s32 Wad_Uninstall(FILE *fp) +{ + //////start the gui shit + GuiWindow promptWindow(472,320); + promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + promptWindow.SetPosition(0, -10); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if (!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + char imgPath[100]; + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); + GuiTrigger trigA; + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); - } + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes){ + dialogBoxImg.SetWidescreen(CFG.widescreen);} - GuiText btn1Txt(tr("OK"), 22, THEME.prompttext); - GuiImage btn1Img(&btnOutline); - if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); - } - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -55, &trigA, &btnSoundOver, btnClick2,1); - btn1.SetLabel(&btn1Txt); - btn1.SetState(STATE_SELECTED); + GuiText btn1Txt(tr("OK"), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes){ + btn1Txt.SetWidescreen(CFG.widescreen); + btn1Img.SetWidescreen(CFG.widescreen);} + GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -55, &trigA, &btnSoundOver, btnClick2,1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); char title[50]; - sprintf(title, "%s", tr("Uninstalling wad")); - GuiText titleTxt(title, 26, THEME.prompttext); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetPosition(0,40); + sprintf(title, "%s", tr("Uninstalling wad")); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0,40); - GuiText msg1Txt(NULL, 18, THEME.prompttext); - msg1Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg1Txt.SetPosition(50,75); + GuiText msg1Txt(NULL, 18, THEME.prompttext); + msg1Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg1Txt.SetPosition(50,75); - GuiText msg2Txt(NULL, 18, THEME.prompttext); - msg2Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg2Txt.SetPosition(50, 98); + GuiText msg2Txt(NULL, 18, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg2Txt.SetPosition(50, 98); - GuiText msg3Txt(NULL, 18, THEME.prompttext); - msg3Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg3Txt.SetPosition(50, 121); + GuiText msg3Txt(NULL, 18, THEME.prompttext); + msg3Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg3Txt.SetPosition(50, 121); - GuiText msg4Txt(NULL, 18, THEME.prompttext); - msg4Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg4Txt.SetPosition(50, 144); + GuiText msg4Txt(NULL, 18, THEME.prompttext); + msg4Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg4Txt.SetPosition(50, 144); - GuiText msg5Txt(NULL, 18, THEME.prompttext); - msg5Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - msg5Txt.SetPosition(50, 167); + GuiText msg5Txt(NULL, 18, THEME.prompttext); + msg5Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg5Txt.SetPosition(50, 167); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) {/////////////adjust for widescreen + if ((Settings.wsprompt == yes) && (CFG.widescreen)){/////////////adjust for widescreen - msg1Txt.SetPosition(70,95); - msg2Txt.SetPosition(70, 118); - msg3Txt.SetPosition(70, 141); - msg4Txt.SetPosition(70, 164); - msg5Txt.SetPosition(70, 187); + msg1Txt.SetPosition(70,95); + msg2Txt.SetPosition(70, 118); + msg3Txt.SetPosition(70, 141); + msg4Txt.SetPosition(70, 164); + msg5Txt.SetPosition(70, 187); - } - promptWindow.Append(&dialogBoxImg); - promptWindow.Append(&titleTxt); - promptWindow.Append(&msg5Txt); - promptWindow.Append(&msg4Txt); - promptWindow.Append(&msg3Txt); - promptWindow.Append(&msg1Txt); - promptWindow.Append(&msg2Txt); + } + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msg5Txt); + promptWindow.Append(&msg4Txt); + promptWindow.Append(&msg3Txt); + promptWindow.Append(&msg1Txt); + promptWindow.Append(&msg2Txt); - HaltGui(); - mainWindow->SetState(STATE_DISABLED); - mainWindow->Append(&promptWindow); - mainWindow->ChangeFocus(&promptWindow); - ResumeGui(); - //sleep(3); + HaltGui(); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); + ResumeGui(); + //sleep(3); - ///start the wad shit - wadHeader *header = NULL; - void *pvoid = NULL; - tikview *viewData = NULL; + ///start the wad shit + wadHeader *header = NULL; + void *pvoid = NULL; + tikview *viewData = NULL; - u64 tid; - u32 viewCnt; - s32 ret; + u64 tid; + u32 viewCnt; + s32 ret; - msg1Txt.SetText(tr(">> Reading WAD data...")); + msg1Txt.SetText(tr(">> Reading WAD data...")); - // WAD header - ret = __Wad_ReadAlloc(fp, &pvoid, 0, sizeof(wadHeader)); - if (ret < 0) { - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Reading WAD data...ERROR! "),ret); - msg1Txt.SetText(errTxt); - //printf(" ERROR! (ret = %d)\n", ret); - goto out; - } - SetPointer(header, pvoid); + // WAD header + ret = __Wad_ReadAlloc(fp, &pvoid, 0, sizeof(wadHeader)); + if (ret < 0) { + char errTxt[50]; + sprintf(errTxt,"%sret = %d",tr(">> Reading WAD data...ERROR! "),ret); + msg1Txt.SetText(errTxt); + //printf(" ERROR! (ret = %d)\n", ret); + goto out; + } + SetPointer(header, pvoid); - // Get title ID - ret = __Wad_GetTitleID(fp, header, &tid); - if (ret < 0) { - //printf(" ERROR! (ret = %d)\n", ret); - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Reading WAD data...ERROR! "),ret); - msg1Txt.SetText(errTxt); - goto out; - } + // Get title ID + ret = __Wad_GetTitleID(fp, header, &tid); + if (ret < 0) { + //printf(" ERROR! (ret = %d)\n", ret); + char errTxt[50]; + sprintf(errTxt,"%sret = %d",tr(">> Reading WAD data...ERROR! "),ret); + msg1Txt.SetText(errTxt); + goto out; + } - msg1Txt.SetText(tr(">> Reading WAD data...Ok!")); - msg2Txt.SetText(tr(">> Deleting tickets...")); + msg1Txt.SetText(tr(">> Reading WAD data...Ok!")); + msg2Txt.SetText(tr(">> Deleting tickets...")); - // Get ticket views - ret = Title_GetTicketViews(tid, &viewData, &viewCnt); - if (ret < 0) { - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting tickets...ERROR! "),ret); - msg2Txt.SetText(errTxt); - //printf(" ERROR! (ret = %d)\n", ret); - } - // Delete tickets - if (ret >= 0) { - u32 cnt; + // Get ticket views + ret = Title_GetTicketViews(tid, &viewData, &viewCnt); + if (ret < 0){ + char errTxt[50]; + sprintf(errTxt,"%sret = %d",tr(">> Deleting tickets...ERROR! "),ret); + msg2Txt.SetText(errTxt); + //printf(" ERROR! (ret = %d)\n", ret); + } + // Delete tickets + if (ret >= 0) { + u32 cnt; - // Delete all tickets - for (cnt = 0; cnt < viewCnt; cnt++) { - ret = ES_DeleteTicket(&viewData[cnt]); - if (ret < 0) - break; - } + // Delete all tickets + for (cnt = 0; cnt < viewCnt; cnt++) { + ret = ES_DeleteTicket(&viewData[cnt]); + if (ret < 0) + break; + } - if (ret < 0) { - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting tickets...ERROR! "),ret); - msg2Txt.SetText(errTxt); - } - //printf(" ERROR! (ret = %d\n", ret); - else - //printf(" OK!\n"); - msg2Txt.SetText(tr(">> Deleting tickets...Ok! ")); + if (ret < 0){ + char errTxt[50]; + sprintf(errTxt,"%sret = %d",tr(">> Deleting tickets...ERROR! "),ret); + msg2Txt.SetText(errTxt);} + //printf(" ERROR! (ret = %d\n", ret); + else + //printf(" OK!\n"); + msg2Txt.SetText(tr(">> Deleting tickets...Ok! ")); - } + } - msg3Txt.SetText(tr(">> Deleting title contents...")); - //WindowPrompt(">> Deleting title contents...",0,"Back",0,0); + msg3Txt.SetText(tr(">> Deleting title contents...")); + //WindowPrompt(">> Deleting title contents...",0,"Back",0,0); - // Delete title contents - ret = ES_DeleteTitleContent(tid); - if (ret < 0) { - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting title contents...ERROR! "),ret); - msg3Txt.SetText(errTxt); - } - //printf(" ERROR! (ret = %d)\n", ret); - else - //printf(" OK!\n"); - msg3Txt.SetText(tr(">> Deleting title contents...Ok!")); + // Delete title contents + ret = ES_DeleteTitleContent(tid); + if (ret < 0){ + char errTxt[50]; + sprintf(errTxt,"%sret = %d",tr(">> Deleting title contents...ERROR! "),ret); + msg3Txt.SetText(errTxt);} + //printf(" ERROR! (ret = %d)\n", ret); + else + //printf(" OK!\n"); + msg3Txt.SetText(tr(">> Deleting title contents...Ok!")); - msg4Txt.SetText(tr(">> Deleting title...")); - // Delete title - ret = ES_DeleteTitle(tid); - if (ret < 0) { - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting title ...ERROR! "),ret); - msg4Txt.SetText(errTxt); - } - //printf(" ERROR! (ret = %d)\n", ret); - else - //printf(" OK!\n"); - msg4Txt.SetText(tr(">> Deleting title ...Ok!")); + msg4Txt.SetText(tr(">> Deleting title...")); + // Delete title + ret = ES_DeleteTitle(tid); + if (ret < 0){ + char errTxt[50]; + sprintf(errTxt,"%sret = %d",tr(">> Deleting title ...ERROR! "),ret); + msg4Txt.SetText(errTxt);} + //printf(" ERROR! (ret = %d)\n", ret); + else + //printf(" OK!\n"); + msg4Txt.SetText(tr(">> Deleting title ...Ok!")); out: - // Free memory - if (header) - free(header); + // Free memory + if (header) + free(header); - goto exit; + goto exit; exit: - msg5Txt.SetText(tr("Done!")); - promptWindow.Append(&btn1); - while (btn1.GetState() != STATE_CLICKED) { - } + msg5Txt.SetText(tr("Done!")); + promptWindow.Append(&btn1); + while(btn1.GetState() != STATE_CLICKED){ + } - HaltGui(); - mainWindow->Remove(&promptWindow); - mainWindow->SetState(STATE_DEFAULT); - ResumeGui(); + HaltGui(); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); + ResumeGui(); - return ret; + return ret; } diff --git a/source/xml/xml.c b/source/xml/xml.c index 9e02eab8..d9b287f5 100644 --- a/source/xml/xml.c +++ b/source/xml/xml.c @@ -75,8 +75,8 @@ bool OpenXMLDatabase(char* xmlfilepath, char* argdblang, bool argJPtoEN, bool op snprintf(pathname, sizeof(pathname), "%s%s_%s.zip", pathname, xmlcfg_filename, game_partition); if (openfile) opensuccess = OpenXMLFile(pathname); if (!opensuccess) { - snprintf(pathname, sizeof(pathname), "%s", xmlfilepath); - if (xmlfilepath[strlen(xmlfilepath) - 1] != '/') snprintf(pathname, sizeof(pathname), "%s/",pathname); + snprintf(pathname, sizeof(pathname), "%s", xmlfilepath); + if (xmlfilepath[strlen(xmlfilepath) - 1] != '/') snprintf(pathname, sizeof(pathname), "%s/",pathname); snprintf(pathname, sizeof(pathname), "%swiitdb.zip", pathname); if (openfile) opensuccess = OpenXMLFile(pathname); } @@ -87,9 +87,9 @@ bool OpenXMLDatabase(char* xmlfilepath, char* argdblang, bool argJPtoEN, bool op if (loadtitles) LoadTitlesFromXML(argdblang, argJPtoEN); if (!keepopen) CloseXMLDatabase(); } else { - if (loadtitles) LoadTitlesFromXML(argdblang, argJPtoEN); + if (loadtitles) LoadTitlesFromXML(argdblang, argJPtoEN); if (!keepopen) CloseXMLDatabase(); - } + } return true; } @@ -208,9 +208,9 @@ char *GetLangSettingFromGame(char *gameid) { /* convert language text into ISO 639 two-letter language code (+ZHTW/ZHCN) */ char *ConvertLangTextToCode(char *languagetxt) { - // do not convert if languagetext seems to be a language code (can be 2 or 4 letters) - if (strlen(languagetxt) <= 4) - return languagetxt; + // do not convert if languagetext seems to be a language code (can be 2 or 4 letters) + if (strlen(languagetxt) <= 4) + return languagetxt; int i; for (i=0;i<=10;i++) { if (!strcasecmp(languagetxt,langlist[i])) // case insensitive comparison @@ -586,7 +586,7 @@ bool LoadGameInfoFromXML(char* gameid, char* langtxt) if (gameid[3] == 'S') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region)); if (gameid[3] == 'H') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region)); if (gameid[3] == 'U') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region)); - if (gameid[3] == 'X') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region)); + if (gameid[3] == 'X') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region)); if (gameid[3] == 'Y') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region)); if (gameid[3] == 'Z') strlcpy(gameinfo.region,"PAL",sizeof(gameinfo.region)); } @@ -746,7 +746,8 @@ char * get_nodetext(mxml_node_t *node, char *buffer, int buflen) { /* O - Text i return (buffer); } -int GetRatingForGame(char *gameid) { +int GetRatingForGame(char *gameid) +{ int retval=-1; if (!xml_loaded || nodedata == NULL) return -1; @@ -769,13 +770,13 @@ int GetRatingForGame(char *gameid) { } if (!strcmp(element_text,gameid)) { - char type[5], value[5], dest[5]; + char type[5], value[5], dest[5]; GetTextFromNode(nodeid, nodedata, "rating", "type", NULL, MXML_NO_DESCEND, type, sizeof(type)); GetTextFromNode(nodeid, nodedata, "rating", "value", NULL, MXML_NO_DESCEND, value, sizeof(value)); ConvertRating(value, type, "PEGI", dest, sizeof(dest)); - retval = atoi(dest); - } - return retval; + retval = atoi(dest); + } + return retval; } diff --git a/source/xml/xml.h b/source/xml/xml.h index 107f4852..7b93a3e2 100644 --- a/source/xml/xml.h +++ b/source/xml/xml.h @@ -65,8 +65,8 @@ extern "C" { char *MemInfo(); void GetTextFromNode(mxml_node_t *currentnode, mxml_node_t *topnode, char *nodename, char *attributename, char *value, int descend, char *dest, int destsize); - int GetRatingForGame(char *gameid); - char * get_nodetext(mxml_node_t *node, char *buffer, int buflen); + int GetRatingForGame(char *gameid); + char * get_nodetext(mxml_node_t *node, char *buffer, int buflen); #ifdef __cplusplus }